# HG changeset patch # User Frank Benoit # Date 1200123863 -3600 # Node ID 8cec8f536af3c5f7244610aa1703eb60b29253d4 # Parent a5c274fa5af97d065e564dead31a3cc843f569d9 All D sources complete gvim retab (4 spaces), bug with Composite moveAbove/moveBelow fixed. diff -r a5c274fa5af9 -r 8cec8f536af3 dsss.conf --- a/dsss.conf Sat Jan 12 07:02:08 2008 +0100 +++ b/dsss.conf Sat Jan 12 08:44:23 2008 +0100 @@ -29,7 +29,7 @@ buildflags+=-L-lglib-2.0 buildflags+=-L-lcairo buildflags+=-I/home/frank/jive -#buildflags+=-g -gc +buildflags+=-g -gc diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/SWT.d --- a/dwt/SWT.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/SWT.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -51,3317 +51,3317 @@ */ public class SWT { - /* Widget Event Constants */ - - /** - * The null event type (value is 0). - * - * @since 3.0 - */ - public static const int None = 0; - - /** - * The key down event type (value is 1). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addKeyListener - * @see dwt.widgets.Tracker#addKeyListener - * @see dwt.events.KeyListener#keyPressed - * @see dwt.events.KeyEvent - */ - public static const int KeyDown = 1; - - /** - * The key up event type (value is 2). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addKeyListener - * @see dwt.widgets.Tracker#addKeyListener - * @see dwt.events.KeyListener#keyReleased - * @see dwt.events.KeyEvent - */ - public static const int KeyUp = 2; - - /** - * The mouse down event type (value is 3). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseListener - * @see dwt.events.MouseListener#mouseDown - * @see dwt.events.MouseEvent - */ - public static const int MouseDown = 3; - - /** - * The mouse up event type (value is 4). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseListener - * @see dwt.events.MouseListener#mouseUp - * @see dwt.events.MouseEvent - */ - public static const int MouseUp = 4; - - /** - * The mouse move event type (value is 5). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseMoveListener - * @see dwt.events.MouseMoveListener#mouseMove - * @see dwt.events.MouseEvent - */ - public static const int MouseMove = 5; - - /** - * The mouse enter event type (value is 6). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseTrackListener - * @see dwt.events.MouseTrackListener#mouseEnter - * @see dwt.events.MouseEvent - */ - public static const int MouseEnter = 6; - - /** - * The mouse exit event type (value is 7). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseTrackListener - * @see dwt.events.MouseTrackListener#mouseExit - * @see dwt.events.MouseEvent - */ - public static const int MouseExit = 7; - - /** - * The mouse double click event type (value is 8). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseListener - * @see dwt.events.MouseListener#mouseDoubleClick - * @see dwt.events.MouseEvent - */ - public static const int MouseDoubleClick = 8; - - /** - * The paint event type (value is 9). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addPaintListener - * @see dwt.events.PaintListener#paintControl - * @see dwt.events.PaintEvent - */ - public static const int Paint = 9; - - /** - * The move event type (value is 10). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addControlListener - * @see dwt.widgets.TableColumn#addControlListener - * @see dwt.widgets.Tracker#addControlListener - * @see dwt.widgets.TreeColumn#addControlListener - * @see dwt.events.ControlListener#controlMoved - * @see dwt.events.ControlEvent - */ - public static const int Move = 10; - - /** - * The resize event type (value is 11). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addControlListener - * @see dwt.widgets.TableColumn#addControlListener - * @see dwt.widgets.Tracker#addControlListener - * @see dwt.widgets.TreeColumn#addControlListener - * @see dwt.events.ControlListener#controlResized - * @see dwt.events.ControlEvent - */ - public static const int Resize = 11; - - /** - * The dispose event type (value is 12). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Widget#addDisposeListener - * @see dwt.events.DisposeListener#widgetDisposed - * @see dwt.events.DisposeEvent - */ - public static const int Dispose = 12; - - /** - * The selection event type (value is 13). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Button#addSelectionListener - * @see dwt.widgets.Combo#addSelectionListener - * @see dwt.widgets.CoolItem#addSelectionListener - * @see dwt.widgets.Link#addSelectionListener - * @see dwt.widgets.List#addSelectionListener - * @see dwt.widgets.MenuItem#addSelectionListener - * @see dwt.widgets.Sash#addSelectionListener - * @see dwt.widgets.Scale#addSelectionListener - * @see dwt.widgets.ScrollBar#addSelectionListener - * @see dwt.widgets.Slider#addSelectionListener - * @see dwt.widgets.TabFolder#addSelectionListener - * @see dwt.widgets.Table#addSelectionListener - * @see dwt.widgets.TableColumn#addSelectionListener - * @see dwt.widgets.ToolItem#addSelectionListener - * @see dwt.widgets.TrayItem#addSelectionListener - * @see dwt.widgets.Tree#addSelectionListener - * @see dwt.widgets.TreeColumn#addSelectionListener - * @see dwt.events.SelectionListener#widgetSelected - * @see dwt.events.SelectionEvent - */ - public static const int Selection = 13; - - /** - * The default selection event type (value is 14). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Combo#addSelectionListener - * @see dwt.widgets.List#addSelectionListener - * @see dwt.widgets.Spinner#addSelectionListener - * @see dwt.widgets.Table#addSelectionListener - * @see dwt.widgets.Text#addSelectionListener - * @see dwt.widgets.TrayItem#addSelectionListener - * @see dwt.widgets.Tree#addSelectionListener - * @see dwt.events.SelectionListener#widgetDefaultSelected - * @see dwt.events.SelectionEvent - */ - public static const int DefaultSelection = 14; - - /** - * The focus in event type (value is 15). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addFocusListener - * @see dwt.events.FocusListener#focusGained - * @see dwt.events.FocusEvent - */ - public static const int FocusIn = 15; - - /** - * The focus out event type (value is 16). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addFocusListener - * @see dwt.events.FocusListener#focusLost - * @see dwt.events.FocusEvent - */ - public static const int FocusOut = 16; - - /** - * The expand event type (value is 17). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Tree#addTreeListener - * @see dwt.events.TreeListener#treeExpanded - * @see dwt.events.TreeEvent - */ - public static const int Expand = 17; - - /** - * The collapse event type (value is 18). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Tree#addTreeListener - * @see dwt.events.TreeListener#treeCollapsed - * @see dwt.events.TreeEvent - */ - public static const int Collapse = 18; - - /** - * The iconify event type (value is 19). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Shell#addShellListener - * @see dwt.events.ShellListener#shellIconified - * @see dwt.events.ShellEvent - */ - public static const int Iconify = 19; - - /** - * The de-iconify event type (value is 20). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Shell#addShellListener - * @see dwt.events.ShellListener#shellDeiconified - * @see dwt.events.ShellEvent - */ - public static const int Deiconify = 20; - - /** - * The close event type (value is 21). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Shell#addShellListener - * @see dwt.events.ShellListener#shellClosed - * @see dwt.events.ShellEvent - */ - public static const int Close = 21; - - /** - * The show event type (value is 22). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Menu#addMenuListener - * @see dwt.events.MenuListener#menuShown - * @see dwt.events.MenuEvent - */ - public static const int Show = 22; - - /** - * The hide event type (value is 23). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Menu#addMenuListener - * @see dwt.events.MenuListener#menuHidden - * @see dwt.events.MenuEvent - */ - public static const int Hide = 23; - - /** - * The modify event type (value is 24). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Combo#addModifyListener - * @see dwt.widgets.Spinner#addModifyListener - * @see dwt.widgets.Text#addModifyListener - * @see dwt.events.ModifyListener#modifyText - * @see dwt.events.ModifyEvent - */ - public static const int Modify = 24; - - /** - * The verify event type (value is 25). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Combo#addVerifyListener - * @see dwt.widgets.Text#addVerifyListener - * @see dwt.events.VerifyListener#verifyText - * @see dwt.events.VerifyEvent - */ - public static const int Verify = 25; - - /** - * The activate event type (value is 26). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Shell#addShellListener - * @see dwt.events.ShellListener#shellActivated - * @see dwt.events.ShellEvent - */ - public static const int Activate = 26; - - /** - * The deactivate event type (value is 27). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Shell#addShellListener - * @see dwt.events.ShellListener#shellDeactivated - * @see dwt.events.ShellEvent - */ - public static const int Deactivate = 27; - - /** - * The help event type (value is 28). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addHelpListener - * @see dwt.widgets.Menu#addHelpListener - * @see dwt.widgets.MenuItem#addHelpListener - * @see dwt.events.HelpListener#helpRequested - * @see dwt.events.HelpEvent - */ - public static const int Help = 28; - - /** - * The drag detect event type (value is 29). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.dnd.DragSource - */ - public static const int DragDetect = 29; - - /** - * The arm event type (value is 30). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.MenuItem#addArmListener - * @see dwt.events.ArmListener#widgetArmed - * @see dwt.events.ArmEvent - */ - public static const int Arm = 30; - - /** - * The traverse event type (value is 31). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addTraverseListener - * @see dwt.events.TraverseListener#keyTraversed - * @see dwt.events.TraverseEvent - */ - public static const int Traverse = 31; - - /** - * The mouse hover event type (value is 32). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Control#addMouseTrackListener - * @see dwt.events.MouseTrackListener#mouseHover - * @see dwt.events.MouseEvent - */ - public static const int MouseHover = 32; - - /** - * The hardware key down event type (value is 33). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - */ - public static const int HardKeyDown = 33; - - /** - * The hardware key up event type (value is 34). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - */ - public static const int HardKeyUp = 34; - - /** - * The menu detect event type (value is 35). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @since 3.0 - */ - public static const int MenuDetect = 35; - - /** - * The set data event type (value is 36). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @see dwt.widgets.Table - * @see dwt.widgets.Tree - * - * @since 3.0 - */ - public static const int SetData = 36; - - /** - * The mouse wheel event type (value is 37). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @since 3.1 - */ - public static const int MouseWheel = 37; - - /** - * The settings changed event type (value is 39). - *

- * The settings changed event is sent when an operating system - * property, such as a system font or color, has been changed. - * The event occurs after the property has been changed, but - * before any widget is redrawn. Applications that cache operating - * system properties can use this event to update their caches. - * A specific property change can be detected by querying the - * new value of a property and comparing it with the equivalent - * cached value. The operating system automatically redraws and - * lays out all widgets after this event is sent. - *

- * - * @see dwt.widgets.Display#addListener - * @see dwt.widgets.Event - * - * @since 3.2 - */ - public static const int Settings = 39; - - /** - * The erase item event type (value is 40). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @since 3.2 - */ - public static const int EraseItem = 40; - - /** - * The measure item event type (value is 41). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @since 3.2 - */ - public static const int MeasureItem = 41; - - /** - * The paint item event type (value is 42). - * - * @see dwt.widgets.Widget#addListener - * @see dwt.widgets.Display#addFilter - * @see dwt.widgets.Event - * - * @since 3.2 - */ - public static const int PaintItem = 42; - - /* Event Details */ - - /** - * Indicates that a user-interface component is being dragged, - * for example dragging the thumb of a scroll bar (value is 1). - */ - public static const int DRAG = 1; - - /** - * Event detail field that indicates a user-interface component - * state is selected (value is 1<<1). - * - * @since 3.2 - */ - public static const int SELECTED = 1 << 1; - - /** - * Event detail field that indicates a user-interface component - * state is focused (value is 1<<2). - * - * @since 3.2 - */ - public static const int FOCUSED = 1 << 2; - - /** - * Event detail field that indicates a user-interface component - * draws the background (value is 1<<3). - * - * @since 3.2 - */ - public static const int BACKGROUND = 1 << 3; - - /** - * Event detail field that indicates a user-interface component - * draws the foreground (value is 1<<4). - * - * @since 3.2 - */ - public static const int FOREGROUND = 1 << 4; - - /** - * Event detail field that indicates a user-interface component - * state is hot (value is 1<<5). - * - * @since 3.3 - */ - public static const int HOT = 1 << 5; - - /* This code is intentionally commented */ - //public static const int PRESSED = 1 << 3; - //public static const int ACTIVE = 1 << 4; - //public static const int DISABLED = 1 << 5; - //public static const int HOT = 1 << 6; - //public static const int DEFAULTED = 1 << 7; - - /** - * Traversal event detail field value indicating that no - * traversal action should be taken - * (value is 0). - */ - public static const int TRAVERSE_NONE = 0; - - /** - * Traversal event detail field value indicating that the - * key which designates that a dialog should be cancelled was - * pressed; typically, this is the ESC key - * (value is 1<<1). - */ - public static const int TRAVERSE_ESCAPE = 1 << 1; - - /** - * Traversal event detail field value indicating that the - * key which activates the default button in a dialog was - * pressed; typically, this is the ENTER key - * (value is 1<<2). - */ - public static const int TRAVERSE_RETURN = 1 << 2; - - /** - * Traversal event detail field value indicating that the - * key which designates that focus should be given to the - * previous tab group was pressed; typically, this is the - * SHIFT-TAB key sequence - * (value is 1<<3). - */ - public static const int TRAVERSE_TAB_PREVIOUS = 1 << 3; - - /** - * Traversal event detail field value indicating that the - * key which designates that focus should be given to the - * next tab group was pressed; typically, this is the - * TAB key - * (value is 1<<4). - */ - public static const int TRAVERSE_TAB_NEXT = 1 << 4; - - /** - * Traversal event detail field value indicating that the - * key which designates that focus should be given to the - * previous tab item was pressed; typically, this is either - * the LEFT-ARROW or UP-ARROW keys - * (value is 1<<5). - */ - public static const int TRAVERSE_ARROW_PREVIOUS = 1 << 5; - - /** - * Traversal event detail field value indicating that the - * key which designates that focus should be given to the - * previous tab item was pressed; typically, this is either - * the RIGHT-ARROW or DOWN-ARROW keys - * (value is 1<<6). - */ - public static const int TRAVERSE_ARROW_NEXT = 1 << 6; - - /** - * Traversal event detail field value indicating that a - * mnemonic key sequence was pressed - * (value is 1<<7). - */ - public static const int TRAVERSE_MNEMONIC = 1 << 7; - - /** - * Traversal event detail field value indicating that the - * key which designates that the previous page of a multi-page - * window should be shown was pressed; typically, this - * is the CTRL-PAGEUP key sequence - * (value is 1<<8). - */ - public static const int TRAVERSE_PAGE_PREVIOUS = 1 << 8; - - /** - * Traversal event detail field value indicating that the - * key which designates that the next page of a multi-page - * window should be shown was pressed; typically, this - * is the CTRL-PAGEDOWN key sequence - * (value is 1<<9). - */ - public static const int TRAVERSE_PAGE_NEXT = 1 << 9; - - /** - * A constant known to be zero (0), typically used in operations - * which take bit flags to indicate that "no bits are set". - */ - public static const int NONE = 0; - - /** - * A constant known to be zero (0), used in operations which - * take pointers to indicate a null argument. - */ - public static const int NULL = 0; - - /** - * Indicates that a default should be used (value is -1). - */ - public static const int DEFAULT = -1; - - /** - * Indicates that a property is off (value is 0). - * - * @since 3.1 - */ - public static const int OFF = 0; - - /** - * Indicates that a property is on (value is 1). - * - * @since 3.1 - */ - public static const int ON = 1; - - /** - * Indicates low quality (value is 1). - * - * @since 3.1 - */ - public static const int LOW = 1; - - /** - * Indicates high quality (value is 2). - * - * @since 3.1 - */ - public static const int HIGH = 2; - - /** - * Style constant for menu bar behavior (value is 1<<1). - *

Used By:

- */ - public static const int BAR = 1 << 1; - - /** - * Style constant for drop down menu/list behavior (value is 1<<2). - *

Used By:

- */ - public static const int DROP_DOWN = 1 << 2; - - /** - * Style constant for pop up menu behavior (value is 1<<3). - *

Used By:

- */ - public static const int POP_UP = 1 << 3; - - /** - * Style constant for line separator behavior (value is 1<<1). - *

Used By:

- */ - public static const int SEPARATOR = 1 << 1; - - /** - * Style constant for toggle button behavior (value is 1<<1). - *

Used By:

- */ - public static const int TOGGLE = 1 << 1; - - /** - * Style constant for arrow button behavior (value is 1<<2). - *

Used By:

- */ - public static const int ARROW = 1 << 2; - - /** - * Style constant for push button behavior (value is 1<<3). - *

Used By:

- */ - public static const int PUSH = 1 << 3; - - /** - * Style constant for radio button behavior (value is 1<<4). - *

Used By:

- */ - public static const int RADIO = 1 << 4; - - /** - * Style constant for check box behavior (value is 1<<5). - *

Used By:

- */ - public static const int CHECK = 1 << 5; - - /** - * Style constant for cascade behavior (value is 1<<6). - *

Used By:

- */ - public static const int CASCADE = 1 << 6; - - /** - * Style constant for multi-selection behavior in lists - * and multiple line support on text fields (value is 1<<1). - *

Used By:

- */ - public static const int MULTI = 1 << 1; - - /** - * Style constant for single selection behavior in lists - * and single line support on text fields (value is 1<<2). - *

Used By:

- */ - public static const int SINGLE = 1 << 2; - - /** - * Style constant for read-only behavior (value is 1<<3). - *

Used By:

- */ - public static const int READ_ONLY = 1 << 3; - - /** - * Style constant for automatic line wrap behavior (value is 1<<6). - *

Used By:

- */ - public static const int WRAP = 1 << 6; - - /** - * Style constant for search behavior (value is 1<<7). - *

Used By:

- * - * @since 3.3 - */ - public static const int SEARCH = 1 << 7; - - /** - * Style constant for simple (not drop down) behavior (value is 1<<6). - *

Used By:

- */ - public static const int SIMPLE = 1 << 6; - - /** - * Style constant for password behavior (value is 1<<22). - *

Used By:

- * - * @since 3.0 - */ - public static const int PASSWORD = 1 << 22; - - /** - * Style constant for shadow in behavior (value is 1<<2). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int SHADOW_IN = 1 << 2; - - /** - * Style constant for shadow out behavior (value is 1<<3). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int SHADOW_OUT = 1 << 3; - - /** - * Style constant for shadow etched in behavior (value is 1<<4). - *
Note that this is a HINT. It is ignored on all platforms except Motif. - *

Used By:

- */ - public static const int SHADOW_ETCHED_IN = 1 << 4; - - /** - * Style constant for shadow etched out behavior (value is 1<<6). - *
Note that this is a HINT. It is ignored on all platforms except Motif. - *

Used By:

- */ - public static const int SHADOW_ETCHED_OUT = 1 << 6; - - /** - * Style constant for no shadow behavior (value is 1<<5). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int SHADOW_NONE = 1 << 5; - - /** - * Style constant for progress bar behavior (value is 1<<1). - *

Used By:

- */ - public static const int INDETERMINATE = 1 << 1; - - /** - * Style constant for tool window behavior (value is 1<<2). - *

- * A tool window is a window intended to be used as a floating toolbar. - * It typically has a title bar that is shorter than a normal title bar, - * and the window title is typically drawn using a smaller font. - *
Note that this is a HINT. - *

Used By:

- */ - public static const int TOOL = 1 << 2; - - /** - * Style constant to ensure no trimmings are used (value is 1<<3). - *
Note that this overrides all other trim styles. - *

Used By:

- */ - public static const int NO_TRIM = 1 << 3; - - /** - * Style constant for resize box trim (value is 1<<4). - *

Used By:

- */ - public static const int RESIZE = 1 << 4; - - /** - * Style constant for title area trim (value is 1<<5). - *

Used By:

- */ - public static const int TITLE = 1 << 5; - - /** - * Style constant for close box trim (value is 1<<6, - * since we do not distinguish between CLOSE style and MENU style). - *

Used By:

- */ - public static const int CLOSE = 1 << 6; - - /** - * Style constant for shell menu trim (value is 1<<6, - * since we do not distinguish between CLOSE style and MENU style). - *

Used By:

- */ - public static const int MENU = CLOSE; - - /** - * Style constant for minimize box trim (value is 1<<7). - *

Used By:

- */ - public static const int MIN = 1 << 7; - - /** - * Style constant for maximize box trim (value is 1<<10). - *

Used By:

- */ - public static const int MAX = 1 << 10; - - /** - * Style constant for horizontal scrollbar behavior (value is 1<<8). - *

Used By:

- */ - public static const int H_SCROLL = 1 << 8; - - /** - * Style constant for vertical scrollbar behavior (value is 1<<9). - *

Used By:

- */ - public static const int V_SCROLL = 1 << 9; - - /** - * Style constant for bordered behavior (value is 1<<11). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int BORDER = 1 << 11; - - /** - * Style constant indicating that the window manager should clip - * a widget's children with respect to its viewable area. (value is 1<<12). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int CLIP_CHILDREN = 1 << 12; - - /** - * Style constant indicating that the window manager should clip - * a widget's siblings with respect to its viewable area. (value is 1<<13). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int CLIP_SIBLINGS = 1 << 13; - - /** - * Style constant for always on top behavior (value is 1<<14). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int ON_TOP = 1 << 14; - - /** - * Trim style convenience constant for the most common top level shell appearance - * (value is CLOSE|TITLE|MIN|MAX|RESIZE). - *

Used By:

- */ - public static const int SHELL_TRIM = CLOSE | TITLE | MIN | MAX | RESIZE; - - /** - * Trim style convenience constant for the most common dialog shell appearance - * (value is CLOSE|TITLE|BORDER). - *

Used By:

- */ - public static const int DIALOG_TRIM = TITLE | CLOSE | BORDER; - - /** - * Style constant for modeless behavior (value is 0). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int MODELESS = 0; - - /** - * Style constant for primary modal behavior (value is 1<<15). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int PRIMARY_MODAL = 1 << 15; - - /** - * Style constant for application modal behavior (value is 1<<16). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int APPLICATION_MODAL = 1 << 16; - - /** - * Style constant for system modal behavior (value is 1<<17). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int SYSTEM_MODAL = 1 << 17; - - /** - * Style constant for selection hiding behavior when the widget loses focus (value is 1<<15). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int HIDE_SELECTION = 1 << 15; - - /** - * Style constant for full row selection behavior and - * selection constant indicating that a full line should be - * drawn. (value is 1<<16). - *
Note that for some widgets this is a HINT. - *

Used By:

- */ - public static const int FULL_SELECTION = 1 << 16; - - /** - * Style constant for flat appearance. (value is 1<<23). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int FLAT = 1 << 23; - - /** - * Style constant for smooth appearance. (value is 1<<16). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int SMOOTH = 1 << 16; - - /** - * Style constant for no background behavior (value is 1<<18). - *

- * By default, before a widget paints, the client area is filled with the current background. - * When this style is specified, the background is not filled, and the application is responsible - * for filling every pixel of the client area. - * This style might be used as an alternative to "double-buffering" in order to reduce flicker. - * This style does not mean "transparent" - widgets that are obscured will not draw through. - *

Used By:

- */ - public static const int NO_BACKGROUND = 1 << 18; - - /** - * Style constant for no focus from the mouse behavior (value is 1<<19). - *
Note that this is a HINT. - *

Used By:

- */ - public static const int NO_FOCUS = 1 << 19; - - /** - * Style constant for no redraw on resize behavior (value is 1<<20). - *

- * This style stops the entire client area from being invalidated when the size - * of the Canvas changes. Specifically, when the size of the Canvas gets smaller, - * the SWT.Paint event is not sent. When it gets bigger, an SWT.Paint event is - * sent with a GC clipped to only the new areas to be painted. Without this - * style, the entire client area will be repainted. - *

Used By:

- */ - public static const int NO_REDRAW_RESIZE = 1 << 20; - - /** - * Style constant for no paint event merging behavior (value is 1<<21). - *

Used By:

- */ - public static const int NO_MERGE_PAINTS = 1 << 21; - - /** - * Style constant for preventing child radio group behavior (value is 1<<22). - *

Used By:

- */ - public static const int NO_RADIO_GROUP = 1 << 22; - - /** - * Style constant for left to right orientation (value is 1<<25). - *

- * When orientation is not explicitly specified, orientation is - * inherited. This means that children will be assigned the - * orientation of their parent. To override this behavior and - * force an orientation for a child, explicitly set the orientation - * of the child when that child is created. - *
Note that this is a HINT. - *

- *

Used By:

- * - * @since 2.1.2 - */ - public static const int LEFT_TO_RIGHT = 1 << 25; - - /** - * Style constant for right to left orientation (value is 1<<26). - *

- * When orientation is not explicitly specified, orientation is - * inherited. This means that children will be assigned the - * orientation of their parent. To override this behavior and - * force an orientation for a child, explicitly set the orientation - * of the child when that child is created. - *
Note that this is a HINT. - *

- *

Used By:

- * - * @since 2.1.2 - */ - public static const int RIGHT_TO_LEFT = 1 << 26; - - /** - * Style constant to indicate coordinate mirroring (value is 1<<27). - *

Used By:

- * - * @since 2.1.2 - */ - public static const int MIRRORED = 1 << 27; - - /** - * Style constant to allow embedding (value is 1<<24). - *

Used By:

- * - * @since 3.0 - */ - public static const int EMBEDDED = 1 << 24; - - /** - * Style constant to allow virtual data (value is 1<<28). - *

Used By:

- * - * @since 3.0 - */ - public static const int VIRTUAL = 1 << 28; - - /** - * Style constant to indicate double buffering (value is 1<<29). - *

Used By:

- * - * @since 3.1 - */ - public static const int DOUBLE_BUFFERED = 1 << 29; - - /** - * Style constant for align up behavior (value is 1<<7, - * since align UP and align TOP are considered the same). - *

Used By:

- */ - public static const int UP = 1 << 7; - - /** - * Style constant for align top behavior (value is 1<<7, - * since align UP and align TOP are considered the same). - *

Used By:

- */ - public static const int TOP = UP; - - /** - * Style constant for align down behavior (value is 1<<10, - * since align DOWN and align BOTTOM are considered the same). - *

Used By:

- */ - public static const int DOWN = 1 << 10; - - /** - * Style constant for align bottom behavior (value is 1<<10, - * since align DOWN and align BOTTOM are considered the same). - *

Used By:

- */ - public static const int BOTTOM = DOWN; - - /** - * Style constant for leading alignment (value is 1<<14). - *

Used By:

- * - * @since 2.1.2 - */ - public static const int LEAD = 1 << 14; - - /** - * Style constant for align left behavior (value is 1<<14). - * This is a synonym for LEAD (value is 1<<14). Newer - * applications should use LEAD instead of LEFT to make code more - * understandable on right-to-left platforms. - */ - public static const int LEFT = LEAD; - - /** - * Style constant for trailing alignment (value is 1<<17). - *

Used By:

- * - * @since 2.1.2 - */ - public static const int TRAIL = 1 << 17; - - /** - * Style constant for align right behavior (value is 1<<17). - * This is a synonym for TRAIL (value is 1<<17). Newer - * applications should use TRAIL instead of RIGHT to make code more - * understandable on right-to-left platforms. - */ - public static const int RIGHT = TRAIL; - - /** - * Style constant for align center behavior (value is 1<<24). - *

Used By:

- */ - public static const int CENTER = 1 << 24; - - /** - * Style constant for horizontal alignment or orientation behavior (value is 1<<8). - *

Used By:

- */ - public static const int HORIZONTAL = 1 << 8; - - /** - * Style constant for vertical alignment or orientation behavior (value is 1<<9). - *

Used By:

- */ - public static const int VERTICAL = 1 << 9; - - /** - * Style constant for date display (value is 1<<5). - *

Used By:

- * - * @since 3.3 - */ - public static const int DATE = 1 << 5; - - /** - * Style constant for time display (value is 1<<7). - *

Used By:

- * - * @since 3.3 - */ - public static const int TIME = 1 << 7; - - /** - * Style constant for calendar display (value is 1<<10). - *

Used By:

- * - * @since 3.3 - */ - public static const int CALENDAR = 1 << 10; - - /** - * Style constant for short date/time format (value is 1<<15). - *

- * A short date displays the month and year. - * A short time displays hours and minutes. - *
Note that this is a HINT. - *

- *

Used By:

- * - * @since 3.3 - */ - public static const int SHORT = 1 << 15; - - /** - * Style constant for medium date/time format (value is 1<<16). - *

- * A medium date displays the day, month and year. - * A medium time displays hours, minutes, and seconds. - *
Note that this is a HINT. - *

- *

Used By:

- * - * @since 3.3 - */ - public static const int MEDIUM = 1 << 16; - - /** - * Style constant for long date/time format (value is 1<<28). - *

- * A long date displays the day, month and year. - * A long time displays hours, minutes, and seconds. - * The day and month names may be displayed. - *
Note that this is a HINT. - *

- *

Used By:

- * - * @since 3.3 - */ - public static const int LONG = 1 << 28; - - /** - * Style constant specifying that a Browser should use a Mozilla GRE - * for rendering its content (value is 1<<15). - *

- *

Used By:

- * - * @since 3.3 - */ - public static const int MOZILLA = 1 << 15; - - /** - * Style constant for balloon behavior (value is 1<<12). - *

Used By:

- * - * @since 3.2 - */ - public static const int BALLOON = 1 << 12; - - /** - * Style constant for vertical alignment or orientation behavior (value is 1). - *

Used By:

- */ - public static const int BEGINNING = 1; - - /** - * Style constant for vertical alignment or orientation behavior (value is 4). - *

Used By:

- */ - public static const int FILL = 4; - - /** - * Input Method Editor style constant for double byte - * input behavior (value is 1<<1). - */ - public static const int DBCS = 1 << 1; - - /** - * Input Method Editor style constant for alpha - * input behavior (value is 1<<2). - */ - public static const int ALPHA = 1 << 2; - - /** - * Input Method Editor style constant for native - * input behavior (value is 1<<3). - */ - public static const int NATIVE = 1 << 3; - - /** - * Input Method Editor style constant for phonetic - * input behavior (value is 1<<4). - */ - public static const int PHONETIC = 1 << 4; - - /** - * Input Method Editor style constant for romanicized - * input behavior (value is 1<<5). - */ - public static const int ROMAN = 1 << 5; - - /** - * ASCII character convenience constant for the backspace character - * (value is the char '\b'). - */ - public static const char BS = '\b'; - - /** - * ASCII character convenience constant for the carriage return character - * (value is the char '\r'). - */ - public static const char CR = '\r'; - - /** - * ASCII character convenience constant for the delete character - * (value is the char with value 127). - */ - public static const char DEL = 0x7F; - - /** - * ASCII character convenience constant for the escape character - * (value is the char with value 27). - */ - public static const char ESC = 0x1B; - - /** - * ASCII character convenience constant for the line feed character - * (value is the char '\n'). - */ - public static const char LF = '\n'; - - /** - * ASCII character convenience constant for the tab character - * (value is the char '\t'). - * - * @since 2.1 - */ - public static const char TAB = '\t'; - - /** - * keyboard and/or mouse event mask indicating that the ALT key - * was pushed on the keyboard when the event was generated - * (value is 1<<16). - */ - public static const int ALT = 1 << 16; - - /** - * Keyboard and/or mouse event mask indicating that the SHIFT key - * was pushed on the keyboard when the event was generated - * (value is 1<<17). - */ - public static const int SHIFT = 1 << 17; - - /** - * Keyboard and/or mouse event mask indicating that the CTRL key - * was pushed on the keyboard when the event was generated - * (value is 1<<18). - */ - public static const int CTRL = 1 << 18; - - /** - * Keyboard and/or mouse event mask indicating that the CTRL key - * was pushed on the keyboard when the event was generated. This - * is a synonym for CTRL (value is 1<<18). - */ - public static const int CONTROL = CTRL; - - /** - * Keyboard and/or mouse event mask indicating that the COMMAND key - * was pushed on the keyboard when the event was generated - * (value is 1<<22). - * - * @since 2.1 - */ - public static const int COMMAND = 1 << 22; - - /** - * Keyboard and/or mouse event mask indicating all possible - * keyboard modifiers. - * - * To allow for the future, this mask is intended to be used in - * place of code that references each individual keyboard mask. - * For example, the following expression will determine whether - * any modifier is pressed and will continue to work as new modifier - * masks are added. - * - * (stateMask & SWT.MODIFIER_MASK) != 0. - * - * @since 2.1 - */ - public static /*const*/ int MODIFIER_MASK; - - /** - * Keyboard and/or mouse event mask indicating that mouse button one - * was pushed when the event was generated. (value is 1<<19). - */ - public static const int BUTTON1 = 1 << 19; - - /** - * Keyboard and/or mouse event mask indicating that mouse button two - * was pushed when the event was generated. (value is 1<<20). - */ - public static const int BUTTON2 = 1 << 20; - - /** - * Keyboard and/or mouse event mask indicating that mouse button three - * was pushed when the event was generated. (value is 1<<21). - */ - public static const int BUTTON3 = 1 << 21; - - /** - * Keyboard and/or mouse event mask indicating that mouse button four - * was pushed when the event was generated. (value is 1<<23). - * - * @since 3.1 - */ - public static const int BUTTON4 = 1 << 23; - - /** - * Keyboard and/or mouse event mask indicating that mouse button five - * was pushed when the event was generated. (value is 1<<25). - * - * @since 3.1 - */ - public static const int BUTTON5 = 1 << 25; - - /** - * Keyboard and/or mouse event mask indicating all possible - * mouse buttons. - * - * To allow for the future, this mask is intended to be used - * in place of code that references each individual button mask. - * For example, the following expression will determine whether - * any button is pressed and will continue to work as new button - * masks are added. - * - * (stateMask & SWT.BUTTON_MASK) != 0. - * - * @since 2.1 - */ - public static /*const*/ int BUTTON_MASK; - - /** - * Keyboard and/or mouse event mask indicating that the MOD1 key - * was pushed on the keyboard when the event was generated. - * - * This is the primary keyboard modifier for the platform. - * - * @since 2.1 - */ - public static /*const*/ int MOD1; - - /** - * Keyboard and/or mouse event mask indicating that the MOD2 key - * was pushed on the keyboard when the event was generated. - * - * This is the secondary keyboard modifier for the platform. - * - * @since 2.1 - */ - public static /*const*/ int MOD2; - - /** - * Keyboard and/or mouse event mask indicating that the MOD3 key - * was pushed on the keyboard when the event was generated. - * - * @since 2.1 - */ - public static /*const*/ int MOD3; - - /** - * Keyboard and/or mouse event mask indicating that the MOD4 key - * was pushed on the keyboard when the event was generated. - * - * @since 2.1 - */ - public static /*const*/ int MOD4; - - /** - * Constants to indicate line scrolling (value is 1). - *

Used By:

- * - * @since 3.1 - */ - public static const int SCROLL_LINE = 1; - - /** - * Constants to indicate page scrolling (value is 2). - *

Used By:

- * - * @since 3.1 - */ - public static const int SCROLL_PAGE = 2; - - /** - * Accelerator constant used to differentiate a key code from a - * unicode character. - * - * If this bit is set, then the key stroke - * portion of an accelerator represents a key code. If this bit - * is not set, then the key stroke portion of an accelerator is - * a unicode character. - * - * The following expression is false: - * - * ((SWT.MOD1 | SWT.MOD2 | 'T') & SWT.KEYCODE_BIT) != 0. - * - * The following expression is true: - * - * ((SWT.MOD3 | SWT.F2) & SWT.KEYCODE_BIT) != 0. - * - * (value is (1<<24)) - * - * @since 2.1 - */ - public static const int KEYCODE_BIT = (1 << 24); - - /** - * Accelerator constant used to extract the key stroke portion of - * an accelerator. - * - * The key stroke may be a key code or a unicode - * value. If the key stroke is a key code KEYCODE_BIT - * will be set. - * - * @since 2.1 - */ - public static const int KEY_MASK = KEYCODE_BIT + 0xFFFF; - - /** - * Keyboard event constant representing the UP ARROW key - * (value is (1<<24)+1). - */ - public static const int ARROW_UP = KEYCODE_BIT + 1; - - /** - * Keyboard event constant representing the DOWN ARROW key - * (value is (1<<24)+2). - */ - public static const int ARROW_DOWN = KEYCODE_BIT + 2; - - /** - * Keyboard event constant representing the LEFT ARROW key - * (value is (1<<24)+3). - */ - public static const int ARROW_LEFT = KEYCODE_BIT + 3; - - /** - * Keyboard event constant representing the RIGHT ARROW key - * (value is (1<<24)+4). - */ - public static const int ARROW_RIGHT = KEYCODE_BIT + 4; - - /** - * Keyboard event constant representing the PAGE UP key - * (value is (1<<24)+5). - */ - public static const int PAGE_UP = KEYCODE_BIT + 5; - - /** - * Keyboard event constant representing the PAGE DOWN key - * (value is (1<<24)+6). - */ - public static const int PAGE_DOWN = KEYCODE_BIT + 6; - - /** - * Keyboard event constant representing the HOME key - * (value is (1<<24)+7). - */ - public static const int HOME = KEYCODE_BIT + 7; - - /** - * Keyboard event constant representing the END key - * (value is (1<<24)+8). - */ - public static const int END = KEYCODE_BIT + 8; - - /** - * Keyboard event constant representing the INSERT key - * (value is (1<<24)+9). - */ - public static const int INSERT = KEYCODE_BIT + 9; - - /** - * Keyboard event constant representing the F1 key - * (value is (1<<24)+10). - */ - public static const int F1 = KEYCODE_BIT + 10; - - /** - * Keyboard event constant representing the F2 key - * (value is (1<<24)+11). - */ - public static const int F2 = KEYCODE_BIT + 11; - - /** - * Keyboard event constant representing the F3 key - * (value is (1<<24)+12). - */ - public static const int F3 = KEYCODE_BIT + 12; - - /** - * Keyboard event constant representing the F4 key - * (value is (1<<24)+13). - */ - public static const int F4 = KEYCODE_BIT + 13; - - /** - * Keyboard event constant representing the F5 key - * (value is (1<<24)+14). - */ - public static const int F5 = KEYCODE_BIT + 14; - - /** - * Keyboard event constant representing the F6 key - * (value is (1<<24)+15). - */ - public static const int F6 = KEYCODE_BIT + 15; - - /** - * Keyboard event constant representing the F7 key - * (value is (1<<24)+16). - */ - public static const int F7 = KEYCODE_BIT + 16; - - /** - * Keyboard event constant representing the F8 key - * (value is (1<<24)+17). - */ - public static const int F8 = KEYCODE_BIT + 17; - - /** - * Keyboard event constant representing the F9 key - * (value is (1<<24)+18). - */ - public static const int F9 = KEYCODE_BIT + 18; - - /** - * Keyboard event constant representing the F10 key - * (value is (1<<24)+19). - */ - public static const int F10 = KEYCODE_BIT + 19; - - /** - * Keyboard event constant representing the F11 key - * (value is (1<<24)+20). - */ - public static const int F11 = KEYCODE_BIT + 20; - - /** - * Keyboard event constant representing the F12 key - * (value is (1<<24)+21). - */ - public static const int F12 = KEYCODE_BIT + 21; - - /** - * Keyboard event constant representing the F13 key - * (value is (1<<24)+22). - * - * @since 3.0 - */ - public static const int F13 = KEYCODE_BIT + 22; - - /** - * Keyboard event constant representing the F14 key - * (value is (1<<24)+23). - * - * @since 3.0 - */ - public static const int F14 = KEYCODE_BIT + 23; - - /** - * Keyboard event constant representing the F15 key - * (value is (1<<24)+24). - * - * @since 3.0 - */ - public static const int F15 = KEYCODE_BIT + 24; - - /** - * Keyboard event constant representing the numeric key - * pad multiply key (value is (1<<24)+42). - * - * @since 3.0 - */ - public static const int KEYPAD_MULTIPLY = KEYCODE_BIT + 42; - - /** - * Keyboard event constant representing the numeric key - * pad add key (value is (1<<24)+43). - * - * @since 3.0 - */ - public static const int KEYPAD_ADD = KEYCODE_BIT + 43; - - /** - * Keyboard event constant representing the numeric key - * pad subtract key (value is (1<<24)+45). - * - * @since 3.0 - */ - public static const int KEYPAD_SUBTRACT = KEYCODE_BIT + 45; - - /** - * Keyboard event constant representing the numeric key - * pad decimal key (value is (1<<24)+46). - * - * @since 3.0 - */ - public static const int KEYPAD_DECIMAL = KEYCODE_BIT + 46; - - /** - * Keyboard event constant representing the numeric key - * pad divide key (value is (1<<24)+47). - * - * @since 3.0 - */ - public static const int KEYPAD_DIVIDE = KEYCODE_BIT + 47; - - /** - * Keyboard event constant representing the numeric key - * pad zero key (value is (1<<24)+48). - * - * @since 3.0 - */ - public static const int KEYPAD_0 = KEYCODE_BIT + 48; - - /** - * Keyboard event constant representing the numeric key - * pad one key (value is (1<<24)+49). - * - * @since 3.0 - */ - public static const int KEYPAD_1 = KEYCODE_BIT + 49; - - /** - * Keyboard event constant representing the numeric key - * pad two key (value is (1<<24)+50). - * - * @since 3.0 - */ - public static const int KEYPAD_2 = KEYCODE_BIT + 50; - - /** - * Keyboard event constant representing the numeric key - * pad three key (value is (1<<24)+51). - * - * @since 3.0 - */ - public static const int KEYPAD_3 = KEYCODE_BIT + 51; - - /** - * Keyboard event constant representing the numeric key - * pad four key (value is (1<<24)+52). - * - * @since 3.0 - */ - public static const int KEYPAD_4 = KEYCODE_BIT + 52; - - /** - * Keyboard event constant representing the numeric key - * pad five key (value is (1<<24)+53). - * - * @since 3.0 - */ - public static const int KEYPAD_5 = KEYCODE_BIT + 53; - - /** - * Keyboard event constant representing the numeric key - * pad six key (value is (1<<24)+54). - * - * @since 3.0 - */ - public static const int KEYPAD_6 = KEYCODE_BIT + 54; - - /** - * Keyboard event constant representing the numeric key - * pad seven key (value is (1<<24)+55). - * - * @since 3.0 - */ - public static const int KEYPAD_7 = KEYCODE_BIT + 55; - - /** - * Keyboard event constant representing the numeric key - * pad eight key (value is (1<<24)+56). - * - * @since 3.0 - */ - public static const int KEYPAD_8 = KEYCODE_BIT + 56; - - /** - * Keyboard event constant representing the numeric key - * pad nine key (value is (1<<24)+57). - * - * @since 3.0 - */ - public static const int KEYPAD_9 = KEYCODE_BIT + 57; - - /** - * Keyboard event constant representing the numeric key - * pad equal key (value is (1<<24)+61). - * - * @since 3.0 - */ - public static const int KEYPAD_EQUAL = KEYCODE_BIT + 61; - - /** - * Keyboard event constant representing the numeric key - * pad enter key (value is (1<<24)+80). - * - * @since 3.0 - */ - public static const int KEYPAD_CR = KEYCODE_BIT + 80; - - /** - * Keyboard event constant representing the help - * key (value is (1<<24)+81). - * - * NOTE: The HELP key maps to the key labeled "help", - * not "F1". If your keyboard does not have a HELP key, - * you will never see this key press. To listen for - * help on a control, use SWT.Help. - * - * @since 3.0 - * - * @see SWT#Help - */ - public static const int HELP = KEYCODE_BIT + 81; - - /** - * Keyboard event constant representing the caps - * lock key (value is (1<<24)+82). - * - * @since 3.0 - */ - public static const int CAPS_LOCK = KEYCODE_BIT + 82; - - /** - * Keyboard event constant representing the num - * lock key (value is (1<<24)+83). - * - * @since 3.0 - */ - public static const int NUM_LOCK = KEYCODE_BIT + 83; - - /** - * Keyboard event constant representing the scroll - * lock key (value is (1<<24)+84). - * - * @since 3.0 - */ - public static const int SCROLL_LOCK = KEYCODE_BIT + 84; - - /** - * Keyboard event constant representing the pause - * key (value is (1<<24)+85). - * - * @since 3.0 - */ - public static const int PAUSE = KEYCODE_BIT + 85; - - /** - * Keyboard event constant representing the break - * key (value is (1<<24)+86). - * - * @since 3.0 - */ - public static const int BREAK = KEYCODE_BIT + 86; - - /** - * Keyboard event constant representing the print screen - * key (value is (1<<24)+87). - * - * @since 3.0 - */ - public static const int PRINT_SCREEN = KEYCODE_BIT + 87; - - /** - * The MessageBox style constant for error icon - * behavior (value is 1). - */ - public static const int ICON_ERROR = 1; - - /** - * The MessageBox style constant for information icon - * behavior (value is 1<<1). - */ - public static const int ICON_INFORMATION = 1 << 1; - - /** - * The MessageBox style constant for question icon - * behavior (value is 1<<2). - */ - public static const int ICON_QUESTION = 1 << 2; - - /** - * The MessageBox style constant for warning icon - * behavior (value is 1<<3). - */ - public static const int ICON_WARNING = 1 << 3; - - /** - * The MessageBox style constant for "working" icon - * behavior (value is 1<<4). - */ - public static const int ICON_WORKING = 1 << 4; - - /** - * The MessageBox style constant for an OK button; - * valid combinations are OK, OK|CANCEL - * (value is 1<<5). - */ - public static const int OK = 1 << 5; - - /** - * The MessageBox style constant for YES button; - * valid combinations are YES|NO, YES|NO|CANCEL - * (value is 1<<6). - */ - public static const int YES = 1 << 6; - - /** - * The MessageBox style constant for NO button; - * valid combinations are YES|NO, YES|NO|CANCEL - * (value is 1<<7). - */ - public static const int NO = 1 << 7; - - /** - * The MessageBox style constant for a CANCEL button; - * valid combinations are OK|CANCEL, YES|NO|CANCEL, RETRY|CANCEL - * (value is 1<<8). This style constant is also used with - * Text in combination with SEARCH. - * - *

Used By:

- */ - public static const int CANCEL = 1 << 8; - - /** - * The MessageBox style constant for an ABORT button; - * the only valid combination is ABORT|RETRY|IGNORE - * (value is 1<<9). - */ - public static const int ABORT = 1 << 9; - - /** - * The MessageBox style constant for a RETRY button; - * valid combinations are ABORT|RETRY|IGNORE, RETRY|CANCEL - * (value is 1<<10). - */ - public static const int RETRY = 1 << 10; - - /** - * The MessageBox style constant for an IGNORE button; - * the only valid combination is ABORT|RETRY|IGNORE - * (value is 1<<11). - */ - public static const int IGNORE = 1 << 11; - - /** - * The FileDialog style constant for open file dialog behavior - * (value is 1<<12). - */ - public static const int OPEN = 1 << 12; - - /** - * The FileDialog style constant for save file dialog behavior - * (value is 1<<13). - */ - public static const int SAVE = 1 << 13; - - /** - * The Composite constant to indicate that - * an attribute (such as background) is not inherited - * by the children (value is 0). - * - * @since 3.2 - */ - public static const int INHERIT_NONE = 0; - - /** - * The Composite constant to indicate that - * an attribute (such as background) is inherited by - * children who choose this value as their "default" - * (value is 1). For example, a label child will - * typically choose to inherit the background color - * of a composite while a list or table will not. - * - * @since 3.2 - */ - public static const int INHERIT_DEFAULT = 1; - - /** - * The Composite constant to indicate that - * an attribute (such as background) is inherited by - * all children. - * - * @since 3.2 - */ - public static const int INHERIT_FORCE = 2; - - /** - * Default color white (value is 1). - */ - public static const int COLOR_WHITE = 1; - - /** - * Default color black (value is 2). - */ - public static const int COLOR_BLACK = 2; - - /** - * Default color red (value is 3). - */ - public static const int COLOR_RED = 3; - - /** - * Default color dark red (value is 4). - */ - public static const int COLOR_DARK_RED = 4; - - /** - * Default color green (value is 5). - */ - public static const int COLOR_GREEN = 5; - - /** - * Default color dark green (value is 6). - */ - public static const int COLOR_DARK_GREEN = 6; - - /** - * Default color yellow (value is 7). - */ - public static const int COLOR_YELLOW = 7; - - /** - * Default color dark yellow (value is 8). - */ - public static const int COLOR_DARK_YELLOW = 8; - - /** - * Default color blue (value is 9). - */ - public static const int COLOR_BLUE = 9; - - /** - * Default color dark blue (value is 10). - */ - public static const int COLOR_DARK_BLUE = 10; - - /** - * Default color magenta (value is 11). - */ - public static const int COLOR_MAGENTA = 11; - - /** - * Default color dark magenta (value is 12). - */ - public static const int COLOR_DARK_MAGENTA = 12; - - /** - * Default color cyan (value is 13). - */ - public static const int COLOR_CYAN = 13; - - /** - * Default color dark cyan (value is 14). - */ - public static const int COLOR_DARK_CYAN = 14; - - /** - * Default color gray (value is 15). - */ - public static const int COLOR_GRAY = 15; - - /** - * Default color dark gray (value is 16). - */ - public static const int COLOR_DARK_GRAY = 16; - - /* - * System Colors - * - * Dealing with system colors is an area where there are - * many platform differences. On some platforms, system - * colors can change dynamically while the program is - * running. On other platforms, system colors can be - * changed for all instances of a particular widget. - * Therefore, the only truly portable method to obtain - * a widget color query is to query the color from an - * instance of the widget. - * - * It is expected that the list of supported colors - * will grow over time. - */ - - /** - * System color used to paint dark shadow areas (value is 17). - */ - public static const int COLOR_WIDGET_DARK_SHADOW = 17; - - /** - * System color used to paint normal shadow areas (value is 18). - */ - public static const int COLOR_WIDGET_NORMAL_SHADOW = 18; - - /** - * System color used to paint light shadow areas (value is 19). - */ - public static const int COLOR_WIDGET_LIGHT_SHADOW = 19; - - /** - * System color used to paint highlight shadow areas (value is 20). - */ - public static const int COLOR_WIDGET_HIGHLIGHT_SHADOW = 20; - - /** - * System color used to paint foreground areas (value is 21). - */ - public static const int COLOR_WIDGET_FOREGROUND = 21; - - /** - * System color used to paint background areas (value is 22). - */ - public static const int COLOR_WIDGET_BACKGROUND = 22; - - /** - * System color used to paint border areas (value is 23). - */ - public static const int COLOR_WIDGET_BORDER = 23; - - /** - * System color used to paint list foreground areas (value is 24). - */ - public static const int COLOR_LIST_FOREGROUND = 24; - - /** - * System color used to paint list background areas (value is 25). - */ - public static const int COLOR_LIST_BACKGROUND = 25; - - /** - * System color used to paint list selection background areas (value is 26). - */ - public static const int COLOR_LIST_SELECTION = 26; - - /** - * System color used to paint list selected text (value is 27). - */ - public static const int COLOR_LIST_SELECTION_TEXT = 27; - - /** - * System color used to paint tooltip text (value is 28). - */ - public static const int COLOR_INFO_FOREGROUND = 28; - - /** - * System color used to paint tooltip background areas (value is 29). - */ - public static const int COLOR_INFO_BACKGROUND = 29; - - /** - * System color used to paint title text (value is 30). - */ - public static const int COLOR_TITLE_FOREGROUND = 30; - - /** - * System color used to paint title background areas (value is 31). - */ - public static const int COLOR_TITLE_BACKGROUND = 31; - - /** - * System color used to paint title background gradient (value is 32). - */ - public static const int COLOR_TITLE_BACKGROUND_GRADIENT = 32; - - /** - * System color used to paint inactive title text (value is 33). - */ - public static const int COLOR_TITLE_INACTIVE_FOREGROUND = 33; - - /** - * System color used to paint inactive title background areas (value is 34). - */ - public static const int COLOR_TITLE_INACTIVE_BACKGROUND = 34; - - /** - * System color used to paint inactive title background gradient (value is 35). - */ - public static const int COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT = 35; - - /** - * Draw constant indicating whether the drawing operation - * should fill the background (value is 1<<0). - */ - public static const int DRAW_TRANSPARENT = 1 << 0; - - /** - * Draw constant indicating whether the string drawing operation - * should handle line-delimiters (value is 1<<1). - */ - public static const int DRAW_DELIMITER = 1 << 1; - - /** - * Draw constant indicating whether the string drawing operation - * should expand TAB characters (value is 1<<2). - */ - public static const int DRAW_TAB = 1 << 2; - - /** - * Draw constant indicating whether the string drawing operation - * should handle mnemonics (value is 1<<3). - */ - public static const int DRAW_MNEMONIC = 1 << 3; - - - /** - * Selection constant indicating that a line delimiter should be - * drawn (value is 1<<17). - * - *

Used By:

- * - * @see #FULL_SELECTION - * @see #LAST_LINE_SELECTION - * - * @since 3.3 - */ - public static const int DELIMITER_SELECTION = 1 << 17; - - /** - * Selection constant indicating that the last line is selected - * to the end and should be drawn using either a line delimiter - * or full line selection (value is 1<<20). - * - *

Used By:

- * - * @see #DELIMITER_SELECTION - * @see #FULL_SELECTION - * - * @since 3.3 - */ - public static const int LAST_LINE_SELECTION = 1 << 20; - - /** - * SWT error constant indicating that no error number was specified - * (value is 1). - */ - public static const int ERROR_UNSPECIFIED = 1; - - /** - * SWT error constant indicating that no more handles for an - * operating system resource are available - * (value is 2). - */ - public static const int ERROR_NO_HANDLES = 2; - - /** - * SWT error constant indicating that no more callback resources are available - * (value is 3). - */ - public static const int ERROR_NO_MORE_CALLBACKS = 3; - - /** - * SWT error constant indicating that a null argument was passed in - * (value is 4). - */ - public static const int ERROR_NULL_ARGUMENT = 4; - - /** - * SWT error constant indicating that an invalid argument was passed in - * (value is 5). - */ - public static const int ERROR_INVALID_ARGUMENT = 5; - - /** - * SWT error constant indicating that a value was found to be - * outside the allowable range - * (value is 6). - */ - public static const int ERROR_INVALID_RANGE = 6; - - /** - * SWT error constant indicating that a value which can not be - * zero was found to be - * (value is 7). - */ - public static const int ERROR_CANNOT_BE_ZERO = 7; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide the value of an item - * (value is 8). - */ - public static const int ERROR_CANNOT_GET_ITEM = 8; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide the selection - * (value is 9). - */ - public static const int ERROR_CANNOT_GET_SELECTION = 9; - - /** - * SWT error constant indicating that the matrix is not invertible - * (value is 10). - * - * @since 3.1 - */ - public static const int ERROR_CANNOT_INVERT_MATRIX = 10; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide the height of an item - * (value is 11). - */ - public static const int ERROR_CANNOT_GET_ITEM_HEIGHT = 11; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide the text of a widget - * (value is 12). - */ - public static const int ERROR_CANNOT_GET_TEXT = 12; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to set the text of a widget - * (value is 13). - */ - public static const int ERROR_CANNOT_SET_TEXT = 13; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to add an item - * (value is 14). - */ - public static const int ERROR_ITEM_NOT_ADDED = 14; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to remove an item - * (value is 15). - */ - public static const int ERROR_ITEM_NOT_REMOVED = 15; - - /** - * SWT error constant indicating that the graphics library - * is not available - * (value is 16). - */ - public static const int ERROR_NO_GRAPHICS_LIBRARY = 16; - - /** - * SWT error constant indicating that a particular feature has - * not been implemented on this platform - * (value is 20). - */ - public static const int ERROR_NOT_IMPLEMENTED = 20; - - /** - * SWT error constant indicating that a menu which needed - * to have the drop down style had some other style instead - * (value is 21). - */ - public static const int ERROR_MENU_NOT_DROP_DOWN = 21; - - /** - * SWT error constant indicating that an attempt was made to - * invoke an SWT operation which can only be executed by the - * user-interface thread from some other thread - * (value is 22). - */ - public static const int ERROR_THREAD_INVALID_ACCESS = 22; - - /** - * SWT error constant indicating that an attempt was made to - * invoke an SWT operation using a widget which had already - * been disposed - * (value is 24). - */ - public static const int ERROR_WIDGET_DISPOSED = 24; - - /** - * SWT error constant indicating that a menu item which needed - * to have the cascade style had some other style instead - * (value is 27). - */ - public static const int ERROR_MENUITEM_NOT_CASCADE = 27; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to set the selection of a widget - * (value is 28). - */ - public static const int ERROR_CANNOT_SET_SELECTION = 28; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to set the menu - * (value is 29). - */ - public static const int ERROR_CANNOT_SET_MENU = 29; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to set the enabled state - * (value is 30). - */ - public static const int ERROR_CANNOT_SET_ENABLED = 30; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide enabled/disabled state information - * (value is 31). - */ - public static const int ERROR_CANNOT_GET_ENABLED = 31; - - /** - * SWT error constant indicating that a provided widget can - * not be used as a parent in the current operation - * (value is 32). - */ - public static const int ERROR_INVALID_PARENT = 32; - - /** - * SWT error constant indicating that a menu which needed - * to have the menu bar style had some other style instead - * (value is 33). - */ - public static const int ERROR_MENU_NOT_BAR = 33; - - /** - * SWT error constant indicating that the underlying operating - * system was unable to provide count information - * (value is 36). - */ - public static const int ERROR_CANNOT_GET_COUNT = 36; - - /** - * SWT error constant indicating that a menu which needed - * to have the pop up menu style had some other style instead - * (value is 37). - */ - public static const int ERROR_MENU_NOT_POP_UP = 37; - - /** - * SWT error constant indicating that a graphics operation - * was attempted with an image of an unsupported depth - * (value is 38). - */ - public static const int ERROR_UNSUPPORTED_DEPTH = 38; - - /** - * SWT error constant indicating that an input/output operation - * failed during the execution of an SWT operation - * (value is 39). - */ - public static const int ERROR_IO = 39; - - /** - * SWT error constant indicating that a graphics operation - * was attempted with an image having an invalid format - * (value is 40). - */ - public static const int ERROR_INVALID_IMAGE = 40; - - /** - * SWT error constant indicating that a graphics operation - * was attempted with an image having a valid but unsupported - * format - * (value is 42). - */ - public static const int ERROR_UNSUPPORTED_FORMAT = 42; - - /** - * SWT error constant indicating that an attempt was made - * to subclass an SWT widget class without implementing the - * checkSubclass() method - * (value is 43). - * - * For additional information see the comment in - * Widget.checkSubclass(). - * - * @see dwt.widgets.Widget#checkSubclass - */ - public static const int ERROR_INVALID_SUBCLASS = 43; - - /** - * SWT error constant indicating that an attempt was made to - * invoke an SWT operation using a graphics object which had - * already been disposed - * (value is 44). - */ - public static const int ERROR_GRAPHIC_DISPOSED = 44; - - /** - * SWT error constant indicating that an attempt was made to - * invoke an SWT operation using a device which had already - * been disposed - * (value is 45). - */ - public static const int ERROR_DEVICE_DISPOSED = 45; - - /** - * SWT error constant indicating that an exception happened - * when executing a runnable - * (value is 46). - */ - public static const int ERROR_FAILED_EXEC = 46; - - /** - * SWT error constant indicating that an unsatisfied link - * error occurred while attempting to load a library - * (value is 47). - * - * @since 3.1 - */ - public static const int ERROR_FAILED_LOAD_LIBRARY = 47; - - /** - * SWT error constant indicating that a font is not valid - * (value is 48). - * - * @since 3.1 - */ - public static const int ERROR_INVALID_FONT = 48; - - /** - * Constant indicating that an image or operation is of type bitmap (value is 0). - */ - public static const int BITMAP = 0; - - /** - * Constant indicating that an image or operation is of type icon (value is 1). - */ - public static const int ICON = 1; - - /** - * The Image constructor argument indicating that - * the new image should be a copy of the image provided as - * an argument (value is 0). - */ - public static const int IMAGE_COPY = 0; - - /** - * The Image constructor argument indicating that - * the new image should have the appearance of a "disabled" - * (using the platform's rules for how this should look) - * copy of the image provided as an argument (value is 1). - */ - public static const int IMAGE_DISABLE = 1; - - /** - * The Image constructor argument indicating that - * the new image should have the appearance of a "gray scaled" - * copy of the image provided as an argument (value is 2). - */ - public static const int IMAGE_GRAY = 2; - - /** - * The font style constant indicating a normal weight, non-italic font - * (value is 0). - */ - public static const int NORMAL = 0; - - /** - * The font style constant indicating a bold weight font - * (value is 1<<0). - */ - public static const int BOLD = 1 << 0; - - /** - * The font style constant indicating an italic font - * (value is 1<<1). - */ - public static const int ITALIC = 1 << 1; - - /** - * System arrow cursor (value is 0). - */ - public static const int CURSOR_ARROW = 0; - - /** - * System wait cursor (value is 1). - */ - public static const int CURSOR_WAIT = 1; - - /** - * System cross hair cursor (value is 2). - */ - public static const int CURSOR_CROSS = 2; - - /** - * System app startup cursor (value is 3). - */ - public static const int CURSOR_APPSTARTING = 3; - - /** - * System help cursor (value is 4). - */ - public static const int CURSOR_HELP = 4; - - /** - * System resize all directions cursor (value is 5). - */ - public static const int CURSOR_SIZEALL = 5; - - /** - * System resize north-east-south-west cursor (value is 6). - */ - public static const int CURSOR_SIZENESW = 6; - - /** - * System resize north-south cursor (value is 7). - */ - public static const int CURSOR_SIZENS = 7; - - /** - * System resize north-west-south-east cursor (value is 8). - */ - public static const int CURSOR_SIZENWSE = 8; - - /** - * System resize west-east cursor (value is 9). - */ - public static const int CURSOR_SIZEWE = 9; - - /** - * System resize north cursor (value is 10). - */ - public static const int CURSOR_SIZEN = 10; - - /** - * System resize south cursor (value is 11). - */ - public static const int CURSOR_SIZES = 11; - - /** - * System resize east cursor (value is 12). - */ - public static const int CURSOR_SIZEE = 12; - - /** - * System resize west cursor (value is 13). - */ - public static const int CURSOR_SIZEW = 13; - - /** - * System resize north-east cursor (value is 14). - */ - public static const int CURSOR_SIZENE = 14; - - /** - * System resize south-east cursor (value is 15). - */ - public static const int CURSOR_SIZESE = 15; - - /** - * System resize south-west cursor (value is 16). - */ - public static const int CURSOR_SIZESW = 16; - - /** - * System resize north-west cursor (value is 17). - */ - public static const int CURSOR_SIZENW = 17; - - /** - * System up arrow cursor (value is 18). - */ - public static const int CURSOR_UPARROW = 18; - - /** - * System i-beam cursor (value is 19). - */ - public static const int CURSOR_IBEAM = 19; - - /** - * System "not allowed" cursor (value is 20). - */ - public static const int CURSOR_NO = 20; - - /** - * System hand cursor (value is 21). - */ - public static const int CURSOR_HAND = 21; - - /** - * Line drawing style for flat end caps (value is 1). - * - * @see dwt.graphics.GC#setLineCap(int) - * @see dwt.graphics.GC#getLineCap() - * - * @since 3.1 - */ - public static const int CAP_FLAT = 1; - - /** - * Line drawing style for rounded end caps (value is 2). - * - * @see dwt.graphics.GC#setLineCap(int) - * @see dwt.graphics.GC#getLineCap() - * - * @since 3.1 - */ - public static const int CAP_ROUND = 2; - - /** - * Line drawing style for square end caps (value is 3). - * - * @see dwt.graphics.GC#setLineCap(int) - * @see dwt.graphics.GC#getLineCap() - * - * @since 3.1 - */ - public static const int CAP_SQUARE = 3; - - /** - * Line drawing style for miter joins (value is 1). - * - * @see dwt.graphics.GC#setLineJoin(int) - * @see dwt.graphics.GC#getLineJoin() - * - * @since 3.1 - */ - public static const int JOIN_MITER = 1; - - /** - * Line drawing style for rounded joins (value is 2). - * - * @see dwt.graphics.GC#setLineJoin(int) - * @see dwt.graphics.GC#getLineJoin() - * - * @since 3.1 - */ - public static const int JOIN_ROUND = 2; - - /** - * Line drawing style for bevel joins (value is 3). - * - * @see dwt.graphics.GC#setLineJoin(int) - * @see dwt.graphics.GC#getLineJoin() - * - * @since 3.1 - */ - public static const int JOIN_BEVEL = 3; - - /** - * Line drawing style for solid lines (value is 1). - */ - public static const int LINE_SOLID = 1; - - /** - * Line drawing style for dashed lines (value is 2). - */ - public static const int LINE_DASH = 2; - - /** - * Line drawing style for dotted lines (value is 3). - */ - public static const int LINE_DOT = 3; - - /** - * Line drawing style for alternating dash-dot lines (value is 4). - */ - public static const int LINE_DASHDOT = 4; - - /** - * Line drawing style for dash-dot-dot lines (value is 5). - */ - public static const int LINE_DASHDOTDOT = 5; - - /** - * Line drawing style for custom dashed lines (value is 6). - * - * @see dwt.graphics.GC#setLineDash(int[]) - * @see dwt.graphics.GC#getLineDash() - * - * @since 3.1 - */ - public static const int LINE_CUSTOM = 6; - - /** - * Path constant that represents a "move to" operation (value is 1). - * - * @since 3.1 - */ - public static const int PATH_MOVE_TO = 1; - - /** - * Path constant that represents a "line to" operation (value is 2). - * - * @since 3.1 - */ - public static const int PATH_LINE_TO = 2; - - /** - * Path constant that represents a "quadratic curve to" operation (value is 3). - * - * @since 3.1 - */ - public static const int PATH_QUAD_TO = 3; - - /** - * Path constant that represents a "cubic curve to" operation (value is 4). - * - * @since 3.1 - */ - public static const int PATH_CUBIC_TO = 4; - - /** - * Path constant that represents a "close" operation (value is 5). - * - * @since 3.1 - */ - public static const int PATH_CLOSE = 5; - - /** - * Even odd rule for filling operations (value is 1). - * - * @since 3.1 - */ - public static const int FILL_EVEN_ODD = 1; - - /** - * Winding rule for filling operations (value is 2). - * - * @since 3.1 - */ - public static const int FILL_WINDING = 2; - - /** - * Image format constant indicating an unknown image type (value is -1). - */ - public static const int IMAGE_UNDEFINED = -1; - - /** - * Image format constant indicating a Windows BMP format image (value is 0). - */ - public static const int IMAGE_BMP = 0; - - /** - * Image format constant indicating a run-length encoded - * Windows BMP format image (value is 1). - */ - public static const int IMAGE_BMP_RLE = 1; - - /** - * Image format constant indicating a GIF format image (value is 2). - */ - public static const int IMAGE_GIF = 2; - - /** - * Image format constant indicating a ICO format image (value is 3). - */ - public static const int IMAGE_ICO = 3; - - /** - * Image format constant indicating a JPEG format image (value is 4). - */ - public static const int IMAGE_JPEG = 4; - - /** - * Image format constant indicating a PNG format image (value is 5). - */ - public static const int IMAGE_PNG = 5; - - /** - * Image format constant indicating a TIFF format image (value is 6). - */ - public static const int IMAGE_TIFF = 6; - - /** - * Image format constant indicating an OS/2 BMP format image (value is 7). - */ - public static const int IMAGE_OS2_BMP = 7; - - /** - * GIF image disposal method constants indicating that the - * disposal method is unspecified (value is 0). - */ - public static const int DM_UNSPECIFIED = 0x0; - - /** - * GIF image disposal method constants indicating that the - * disposal method is to do nothing; that is, to leave the - * previous image in place (value is 1). - */ - public static const int DM_FILL_NONE = 0x1; - - /** - * GIF image disposal method constants indicating that the - * the previous images should be covered with the background - * color before displaying the next image (value is 2). - */ - public static const int DM_FILL_BACKGROUND = 0x2; - - /** - * GIF image disposal method constants indicating that the - * disposal method is to restore the previous picture - * (value is 3). - */ - public static const int DM_FILL_PREVIOUS = 0x3; - - /** - * Image transparency constant indicating that the image - * contains no transparency information (value is 0). - */ - public static const int TRANSPARENCY_NONE = 0x0; - - /** - * Image transparency constant indicating that the image - * contains alpha transparency information (value is 1<<0). - */ - public static const int TRANSPARENCY_ALPHA = 1 << 0; - - /** - * Image transparency constant indicating that the image - * contains a transparency mask (value is 1<<1). - */ - public static const int TRANSPARENCY_MASK = 1 << 1; - - /** - * Image transparency constant indicating that the image - * contains a transparent pixel (value is 1<<2). - */ - public static const int TRANSPARENCY_PIXEL = 1 << 2; - - /** - * The character movement type (value is 1<<0). - * This constant is used to move a text offset over a character. - * - * @see dwt.graphics.TextLayout#getNextOffset(int, int) - * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) - * - * @since 3.0 - */ - public static const int MOVEMENT_CHAR = 1 << 0; - - /** - * The cluster movement type (value is 1<<1). - * This constant is used to move a text offset over a cluster. - * A cluster groups one or more characters. A cluster is - * undivisible, this means that a caret offset can not be placed in the - * middle of a cluster. - * - * @see dwt.graphics.TextLayout#getNextOffset(int, int) - * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) - * - * @since 3.0 - */ - public static const int MOVEMENT_CLUSTER = 1 << 1; - - /** - * The word movement type (value is 1<<2). - * This constant is used to move a text offset over a word. - * The behavior of this constant depends on the platform and on the - * direction of the movement. For example, on Windows the stop is - * always at the start of the word. On GTK and Mac the stop is at the end - * of the word if the direction is next and at the start of the word if the - * direction is previous. - * - * @see dwt.graphics.TextLayout#getNextOffset(int, int) - * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) - * - * @since 3.0 - */ - public static const int MOVEMENT_WORD = 1 << 2; - - /** - * The word end movement type (value is 1<<3). - * This constant is used to move a text offset to the next or previous - * word end. The behavior of this constant does not depend on the platform. - * - * - * @see dwt.graphics.TextLayout#getNextOffset(int, int) - * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) - * - * @since 3.3 - */ - public static const int MOVEMENT_WORD_END = 1 << 3; - - /** - * The word start movement type (value is 1<<4). - * This constant is used to move a text offset to the next or previous - * word start. The behavior of this constant does not depend on the platform. - * - * @see dwt.graphics.TextLayout#getNextOffset(int, int) - * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) - * - * @since 3.3 - */ - public static const int MOVEMENT_WORD_START = 1 << 4; + /* Widget Event Constants */ + + /** + * The null event type (value is 0). + * + * @since 3.0 + */ + public static const int None = 0; + + /** + * The key down event type (value is 1). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addKeyListener + * @see dwt.widgets.Tracker#addKeyListener + * @see dwt.events.KeyListener#keyPressed + * @see dwt.events.KeyEvent + */ + public static const int KeyDown = 1; + + /** + * The key up event type (value is 2). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addKeyListener + * @see dwt.widgets.Tracker#addKeyListener + * @see dwt.events.KeyListener#keyReleased + * @see dwt.events.KeyEvent + */ + public static const int KeyUp = 2; + + /** + * The mouse down event type (value is 3). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseListener + * @see dwt.events.MouseListener#mouseDown + * @see dwt.events.MouseEvent + */ + public static const int MouseDown = 3; + + /** + * The mouse up event type (value is 4). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseListener + * @see dwt.events.MouseListener#mouseUp + * @see dwt.events.MouseEvent + */ + public static const int MouseUp = 4; + + /** + * The mouse move event type (value is 5). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseMoveListener + * @see dwt.events.MouseMoveListener#mouseMove + * @see dwt.events.MouseEvent + */ + public static const int MouseMove = 5; + + /** + * The mouse enter event type (value is 6). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseTrackListener + * @see dwt.events.MouseTrackListener#mouseEnter + * @see dwt.events.MouseEvent + */ + public static const int MouseEnter = 6; + + /** + * The mouse exit event type (value is 7). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseTrackListener + * @see dwt.events.MouseTrackListener#mouseExit + * @see dwt.events.MouseEvent + */ + public static const int MouseExit = 7; + + /** + * The mouse double click event type (value is 8). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseListener + * @see dwt.events.MouseListener#mouseDoubleClick + * @see dwt.events.MouseEvent + */ + public static const int MouseDoubleClick = 8; + + /** + * The paint event type (value is 9). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addPaintListener + * @see dwt.events.PaintListener#paintControl + * @see dwt.events.PaintEvent + */ + public static const int Paint = 9; + + /** + * The move event type (value is 10). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addControlListener + * @see dwt.widgets.TableColumn#addControlListener + * @see dwt.widgets.Tracker#addControlListener + * @see dwt.widgets.TreeColumn#addControlListener + * @see dwt.events.ControlListener#controlMoved + * @see dwt.events.ControlEvent + */ + public static const int Move = 10; + + /** + * The resize event type (value is 11). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addControlListener + * @see dwt.widgets.TableColumn#addControlListener + * @see dwt.widgets.Tracker#addControlListener + * @see dwt.widgets.TreeColumn#addControlListener + * @see dwt.events.ControlListener#controlResized + * @see dwt.events.ControlEvent + */ + public static const int Resize = 11; + + /** + * The dispose event type (value is 12). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Widget#addDisposeListener + * @see dwt.events.DisposeListener#widgetDisposed + * @see dwt.events.DisposeEvent + */ + public static const int Dispose = 12; + + /** + * The selection event type (value is 13). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Button#addSelectionListener + * @see dwt.widgets.Combo#addSelectionListener + * @see dwt.widgets.CoolItem#addSelectionListener + * @see dwt.widgets.Link#addSelectionListener + * @see dwt.widgets.List#addSelectionListener + * @see dwt.widgets.MenuItem#addSelectionListener + * @see dwt.widgets.Sash#addSelectionListener + * @see dwt.widgets.Scale#addSelectionListener + * @see dwt.widgets.ScrollBar#addSelectionListener + * @see dwt.widgets.Slider#addSelectionListener + * @see dwt.widgets.TabFolder#addSelectionListener + * @see dwt.widgets.Table#addSelectionListener + * @see dwt.widgets.TableColumn#addSelectionListener + * @see dwt.widgets.ToolItem#addSelectionListener + * @see dwt.widgets.TrayItem#addSelectionListener + * @see dwt.widgets.Tree#addSelectionListener + * @see dwt.widgets.TreeColumn#addSelectionListener + * @see dwt.events.SelectionListener#widgetSelected + * @see dwt.events.SelectionEvent + */ + public static const int Selection = 13; + + /** + * The default selection event type (value is 14). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Combo#addSelectionListener + * @see dwt.widgets.List#addSelectionListener + * @see dwt.widgets.Spinner#addSelectionListener + * @see dwt.widgets.Table#addSelectionListener + * @see dwt.widgets.Text#addSelectionListener + * @see dwt.widgets.TrayItem#addSelectionListener + * @see dwt.widgets.Tree#addSelectionListener + * @see dwt.events.SelectionListener#widgetDefaultSelected + * @see dwt.events.SelectionEvent + */ + public static const int DefaultSelection = 14; + + /** + * The focus in event type (value is 15). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addFocusListener + * @see dwt.events.FocusListener#focusGained + * @see dwt.events.FocusEvent + */ + public static const int FocusIn = 15; + + /** + * The focus out event type (value is 16). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addFocusListener + * @see dwt.events.FocusListener#focusLost + * @see dwt.events.FocusEvent + */ + public static const int FocusOut = 16; + + /** + * The expand event type (value is 17). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Tree#addTreeListener + * @see dwt.events.TreeListener#treeExpanded + * @see dwt.events.TreeEvent + */ + public static const int Expand = 17; + + /** + * The collapse event type (value is 18). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Tree#addTreeListener + * @see dwt.events.TreeListener#treeCollapsed + * @see dwt.events.TreeEvent + */ + public static const int Collapse = 18; + + /** + * The iconify event type (value is 19). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Shell#addShellListener + * @see dwt.events.ShellListener#shellIconified + * @see dwt.events.ShellEvent + */ + public static const int Iconify = 19; + + /** + * The de-iconify event type (value is 20). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Shell#addShellListener + * @see dwt.events.ShellListener#shellDeiconified + * @see dwt.events.ShellEvent + */ + public static const int Deiconify = 20; + + /** + * The close event type (value is 21). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Shell#addShellListener + * @see dwt.events.ShellListener#shellClosed + * @see dwt.events.ShellEvent + */ + public static const int Close = 21; + + /** + * The show event type (value is 22). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Menu#addMenuListener + * @see dwt.events.MenuListener#menuShown + * @see dwt.events.MenuEvent + */ + public static const int Show = 22; + + /** + * The hide event type (value is 23). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Menu#addMenuListener + * @see dwt.events.MenuListener#menuHidden + * @see dwt.events.MenuEvent + */ + public static const int Hide = 23; + + /** + * The modify event type (value is 24). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Combo#addModifyListener + * @see dwt.widgets.Spinner#addModifyListener + * @see dwt.widgets.Text#addModifyListener + * @see dwt.events.ModifyListener#modifyText + * @see dwt.events.ModifyEvent + */ + public static const int Modify = 24; + + /** + * The verify event type (value is 25). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Combo#addVerifyListener + * @see dwt.widgets.Text#addVerifyListener + * @see dwt.events.VerifyListener#verifyText + * @see dwt.events.VerifyEvent + */ + public static const int Verify = 25; + + /** + * The activate event type (value is 26). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Shell#addShellListener + * @see dwt.events.ShellListener#shellActivated + * @see dwt.events.ShellEvent + */ + public static const int Activate = 26; + + /** + * The deactivate event type (value is 27). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Shell#addShellListener + * @see dwt.events.ShellListener#shellDeactivated + * @see dwt.events.ShellEvent + */ + public static const int Deactivate = 27; + + /** + * The help event type (value is 28). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addHelpListener + * @see dwt.widgets.Menu#addHelpListener + * @see dwt.widgets.MenuItem#addHelpListener + * @see dwt.events.HelpListener#helpRequested + * @see dwt.events.HelpEvent + */ + public static const int Help = 28; + + /** + * The drag detect event type (value is 29). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.dnd.DragSource + */ + public static const int DragDetect = 29; + + /** + * The arm event type (value is 30). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.MenuItem#addArmListener + * @see dwt.events.ArmListener#widgetArmed + * @see dwt.events.ArmEvent + */ + public static const int Arm = 30; + + /** + * The traverse event type (value is 31). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addTraverseListener + * @see dwt.events.TraverseListener#keyTraversed + * @see dwt.events.TraverseEvent + */ + public static const int Traverse = 31; + + /** + * The mouse hover event type (value is 32). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Control#addMouseTrackListener + * @see dwt.events.MouseTrackListener#mouseHover + * @see dwt.events.MouseEvent + */ + public static const int MouseHover = 32; + + /** + * The hardware key down event type (value is 33). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + */ + public static const int HardKeyDown = 33; + + /** + * The hardware key up event type (value is 34). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + */ + public static const int HardKeyUp = 34; + + /** + * The menu detect event type (value is 35). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @since 3.0 + */ + public static const int MenuDetect = 35; + + /** + * The set data event type (value is 36). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @see dwt.widgets.Table + * @see dwt.widgets.Tree + * + * @since 3.0 + */ + public static const int SetData = 36; + + /** + * The mouse wheel event type (value is 37). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @since 3.1 + */ + public static const int MouseWheel = 37; + + /** + * The settings changed event type (value is 39). + *

+ * The settings changed event is sent when an operating system + * property, such as a system font or color, has been changed. + * The event occurs after the property has been changed, but + * before any widget is redrawn. Applications that cache operating + * system properties can use this event to update their caches. + * A specific property change can be detected by querying the + * new value of a property and comparing it with the equivalent + * cached value. The operating system automatically redraws and + * lays out all widgets after this event is sent. + *

+ * + * @see dwt.widgets.Display#addListener + * @see dwt.widgets.Event + * + * @since 3.2 + */ + public static const int Settings = 39; + + /** + * The erase item event type (value is 40). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @since 3.2 + */ + public static const int EraseItem = 40; + + /** + * The measure item event type (value is 41). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @since 3.2 + */ + public static const int MeasureItem = 41; + + /** + * The paint item event type (value is 42). + * + * @see dwt.widgets.Widget#addListener + * @see dwt.widgets.Display#addFilter + * @see dwt.widgets.Event + * + * @since 3.2 + */ + public static const int PaintItem = 42; + + /* Event Details */ + + /** + * Indicates that a user-interface component is being dragged, + * for example dragging the thumb of a scroll bar (value is 1). + */ + public static const int DRAG = 1; + + /** + * Event detail field that indicates a user-interface component + * state is selected (value is 1<<1). + * + * @since 3.2 + */ + public static const int SELECTED = 1 << 1; + + /** + * Event detail field that indicates a user-interface component + * state is focused (value is 1<<2). + * + * @since 3.2 + */ + public static const int FOCUSED = 1 << 2; + + /** + * Event detail field that indicates a user-interface component + * draws the background (value is 1<<3). + * + * @since 3.2 + */ + public static const int BACKGROUND = 1 << 3; + + /** + * Event detail field that indicates a user-interface component + * draws the foreground (value is 1<<4). + * + * @since 3.2 + */ + public static const int FOREGROUND = 1 << 4; + + /** + * Event detail field that indicates a user-interface component + * state is hot (value is 1<<5). + * + * @since 3.3 + */ + public static const int HOT = 1 << 5; + + /* This code is intentionally commented */ + //public static const int PRESSED = 1 << 3; + //public static const int ACTIVE = 1 << 4; + //public static const int DISABLED = 1 << 5; + //public static const int HOT = 1 << 6; + //public static const int DEFAULTED = 1 << 7; + + /** + * Traversal event detail field value indicating that no + * traversal action should be taken + * (value is 0). + */ + public static const int TRAVERSE_NONE = 0; + + /** + * Traversal event detail field value indicating that the + * key which designates that a dialog should be cancelled was + * pressed; typically, this is the ESC key + * (value is 1<<1). + */ + public static const int TRAVERSE_ESCAPE = 1 << 1; + + /** + * Traversal event detail field value indicating that the + * key which activates the default button in a dialog was + * pressed; typically, this is the ENTER key + * (value is 1<<2). + */ + public static const int TRAVERSE_RETURN = 1 << 2; + + /** + * Traversal event detail field value indicating that the + * key which designates that focus should be given to the + * previous tab group was pressed; typically, this is the + * SHIFT-TAB key sequence + * (value is 1<<3). + */ + public static const int TRAVERSE_TAB_PREVIOUS = 1 << 3; + + /** + * Traversal event detail field value indicating that the + * key which designates that focus should be given to the + * next tab group was pressed; typically, this is the + * TAB key + * (value is 1<<4). + */ + public static const int TRAVERSE_TAB_NEXT = 1 << 4; + + /** + * Traversal event detail field value indicating that the + * key which designates that focus should be given to the + * previous tab item was pressed; typically, this is either + * the LEFT-ARROW or UP-ARROW keys + * (value is 1<<5). + */ + public static const int TRAVERSE_ARROW_PREVIOUS = 1 << 5; + + /** + * Traversal event detail field value indicating that the + * key which designates that focus should be given to the + * previous tab item was pressed; typically, this is either + * the RIGHT-ARROW or DOWN-ARROW keys + * (value is 1<<6). + */ + public static const int TRAVERSE_ARROW_NEXT = 1 << 6; + + /** + * Traversal event detail field value indicating that a + * mnemonic key sequence was pressed + * (value is 1<<7). + */ + public static const int TRAVERSE_MNEMONIC = 1 << 7; + + /** + * Traversal event detail field value indicating that the + * key which designates that the previous page of a multi-page + * window should be shown was pressed; typically, this + * is the CTRL-PAGEUP key sequence + * (value is 1<<8). + */ + public static const int TRAVERSE_PAGE_PREVIOUS = 1 << 8; + + /** + * Traversal event detail field value indicating that the + * key which designates that the next page of a multi-page + * window should be shown was pressed; typically, this + * is the CTRL-PAGEDOWN key sequence + * (value is 1<<9). + */ + public static const int TRAVERSE_PAGE_NEXT = 1 << 9; + + /** + * A constant known to be zero (0), typically used in operations + * which take bit flags to indicate that "no bits are set". + */ + public static const int NONE = 0; + + /** + * A constant known to be zero (0), used in operations which + * take pointers to indicate a null argument. + */ + public static const int NULL = 0; + + /** + * Indicates that a default should be used (value is -1). + */ + public static const int DEFAULT = -1; + + /** + * Indicates that a property is off (value is 0). + * + * @since 3.1 + */ + public static const int OFF = 0; + + /** + * Indicates that a property is on (value is 1). + * + * @since 3.1 + */ + public static const int ON = 1; + + /** + * Indicates low quality (value is 1). + * + * @since 3.1 + */ + public static const int LOW = 1; + + /** + * Indicates high quality (value is 2). + * + * @since 3.1 + */ + public static const int HIGH = 2; + + /** + * Style constant for menu bar behavior (value is 1<<1). + *

Used By:

+ */ + public static const int BAR = 1 << 1; + + /** + * Style constant for drop down menu/list behavior (value is 1<<2). + *

Used By:

+ */ + public static const int DROP_DOWN = 1 << 2; + + /** + * Style constant for pop up menu behavior (value is 1<<3). + *

Used By:

+ */ + public static const int POP_UP = 1 << 3; + + /** + * Style constant for line separator behavior (value is 1<<1). + *

Used By:

+ */ + public static const int SEPARATOR = 1 << 1; + + /** + * Style constant for toggle button behavior (value is 1<<1). + *

Used By:

+ */ + public static const int TOGGLE = 1 << 1; + + /** + * Style constant for arrow button behavior (value is 1<<2). + *

Used By:

+ */ + public static const int ARROW = 1 << 2; + + /** + * Style constant for push button behavior (value is 1<<3). + *

Used By:

+ */ + public static const int PUSH = 1 << 3; + + /** + * Style constant for radio button behavior (value is 1<<4). + *

Used By:

+ */ + public static const int RADIO = 1 << 4; + + /** + * Style constant for check box behavior (value is 1<<5). + *

Used By:

+ */ + public static const int CHECK = 1 << 5; + + /** + * Style constant for cascade behavior (value is 1<<6). + *

Used By:

+ */ + public static const int CASCADE = 1 << 6; + + /** + * Style constant for multi-selection behavior in lists + * and multiple line support on text fields (value is 1<<1). + *

Used By:

+ */ + public static const int MULTI = 1 << 1; + + /** + * Style constant for single selection behavior in lists + * and single line support on text fields (value is 1<<2). + *

Used By:

+ */ + public static const int SINGLE = 1 << 2; + + /** + * Style constant for read-only behavior (value is 1<<3). + *

Used By:

+ */ + public static const int READ_ONLY = 1 << 3; + + /** + * Style constant for automatic line wrap behavior (value is 1<<6). + *

Used By:

+ */ + public static const int WRAP = 1 << 6; + + /** + * Style constant for search behavior (value is 1<<7). + *

Used By:

+ * + * @since 3.3 + */ + public static const int SEARCH = 1 << 7; + + /** + * Style constant for simple (not drop down) behavior (value is 1<<6). + *

Used By:

+ */ + public static const int SIMPLE = 1 << 6; + + /** + * Style constant for password behavior (value is 1<<22). + *

Used By:

+ * + * @since 3.0 + */ + public static const int PASSWORD = 1 << 22; + + /** + * Style constant for shadow in behavior (value is 1<<2). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int SHADOW_IN = 1 << 2; + + /** + * Style constant for shadow out behavior (value is 1<<3). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int SHADOW_OUT = 1 << 3; + + /** + * Style constant for shadow etched in behavior (value is 1<<4). + *
Note that this is a HINT. It is ignored on all platforms except Motif. + *

Used By:

+ */ + public static const int SHADOW_ETCHED_IN = 1 << 4; + + /** + * Style constant for shadow etched out behavior (value is 1<<6). + *
Note that this is a HINT. It is ignored on all platforms except Motif. + *

Used By:

+ */ + public static const int SHADOW_ETCHED_OUT = 1 << 6; + + /** + * Style constant for no shadow behavior (value is 1<<5). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int SHADOW_NONE = 1 << 5; + + /** + * Style constant for progress bar behavior (value is 1<<1). + *

Used By:

+ */ + public static const int INDETERMINATE = 1 << 1; + + /** + * Style constant for tool window behavior (value is 1<<2). + *

+ * A tool window is a window intended to be used as a floating toolbar. + * It typically has a title bar that is shorter than a normal title bar, + * and the window title is typically drawn using a smaller font. + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int TOOL = 1 << 2; + + /** + * Style constant to ensure no trimmings are used (value is 1<<3). + *
Note that this overrides all other trim styles. + *

Used By:

+ */ + public static const int NO_TRIM = 1 << 3; + + /** + * Style constant for resize box trim (value is 1<<4). + *

Used By:

+ */ + public static const int RESIZE = 1 << 4; + + /** + * Style constant for title area trim (value is 1<<5). + *

Used By:

+ */ + public static const int TITLE = 1 << 5; + + /** + * Style constant for close box trim (value is 1<<6, + * since we do not distinguish between CLOSE style and MENU style). + *

Used By:

+ */ + public static const int CLOSE = 1 << 6; + + /** + * Style constant for shell menu trim (value is 1<<6, + * since we do not distinguish between CLOSE style and MENU style). + *

Used By:

+ */ + public static const int MENU = CLOSE; + + /** + * Style constant for minimize box trim (value is 1<<7). + *

Used By:

+ */ + public static const int MIN = 1 << 7; + + /** + * Style constant for maximize box trim (value is 1<<10). + *

Used By:

+ */ + public static const int MAX = 1 << 10; + + /** + * Style constant for horizontal scrollbar behavior (value is 1<<8). + *

Used By:

+ */ + public static const int H_SCROLL = 1 << 8; + + /** + * Style constant for vertical scrollbar behavior (value is 1<<9). + *

Used By:

+ */ + public static const int V_SCROLL = 1 << 9; + + /** + * Style constant for bordered behavior (value is 1<<11). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int BORDER = 1 << 11; + + /** + * Style constant indicating that the window manager should clip + * a widget's children with respect to its viewable area. (value is 1<<12). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int CLIP_CHILDREN = 1 << 12; + + /** + * Style constant indicating that the window manager should clip + * a widget's siblings with respect to its viewable area. (value is 1<<13). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int CLIP_SIBLINGS = 1 << 13; + + /** + * Style constant for always on top behavior (value is 1<<14). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int ON_TOP = 1 << 14; + + /** + * Trim style convenience constant for the most common top level shell appearance + * (value is CLOSE|TITLE|MIN|MAX|RESIZE). + *

Used By:

+ */ + public static const int SHELL_TRIM = CLOSE | TITLE | MIN | MAX | RESIZE; + + /** + * Trim style convenience constant for the most common dialog shell appearance + * (value is CLOSE|TITLE|BORDER). + *

Used By:

+ */ + public static const int DIALOG_TRIM = TITLE | CLOSE | BORDER; + + /** + * Style constant for modeless behavior (value is 0). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int MODELESS = 0; + + /** + * Style constant for primary modal behavior (value is 1<<15). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int PRIMARY_MODAL = 1 << 15; + + /** + * Style constant for application modal behavior (value is 1<<16). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int APPLICATION_MODAL = 1 << 16; + + /** + * Style constant for system modal behavior (value is 1<<17). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int SYSTEM_MODAL = 1 << 17; + + /** + * Style constant for selection hiding behavior when the widget loses focus (value is 1<<15). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int HIDE_SELECTION = 1 << 15; + + /** + * Style constant for full row selection behavior and + * selection constant indicating that a full line should be + * drawn. (value is 1<<16). + *
Note that for some widgets this is a HINT. + *

Used By:

+ */ + public static const int FULL_SELECTION = 1 << 16; + + /** + * Style constant for flat appearance. (value is 1<<23). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int FLAT = 1 << 23; + + /** + * Style constant for smooth appearance. (value is 1<<16). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int SMOOTH = 1 << 16; + + /** + * Style constant for no background behavior (value is 1<<18). + *

+ * By default, before a widget paints, the client area is filled with the current background. + * When this style is specified, the background is not filled, and the application is responsible + * for filling every pixel of the client area. + * This style might be used as an alternative to "double-buffering" in order to reduce flicker. + * This style does not mean "transparent" - widgets that are obscured will not draw through. + *

Used By:

+ */ + public static const int NO_BACKGROUND = 1 << 18; + + /** + * Style constant for no focus from the mouse behavior (value is 1<<19). + *
Note that this is a HINT. + *

Used By:

+ */ + public static const int NO_FOCUS = 1 << 19; + + /** + * Style constant for no redraw on resize behavior (value is 1<<20). + *

+ * This style stops the entire client area from being invalidated when the size + * of the Canvas changes. Specifically, when the size of the Canvas gets smaller, + * the SWT.Paint event is not sent. When it gets bigger, an SWT.Paint event is + * sent with a GC clipped to only the new areas to be painted. Without this + * style, the entire client area will be repainted. + *

Used By:

+ */ + public static const int NO_REDRAW_RESIZE = 1 << 20; + + /** + * Style constant for no paint event merging behavior (value is 1<<21). + *

Used By:

+ */ + public static const int NO_MERGE_PAINTS = 1 << 21; + + /** + * Style constant for preventing child radio group behavior (value is 1<<22). + *

Used By:

+ */ + public static const int NO_RADIO_GROUP = 1 << 22; + + /** + * Style constant for left to right orientation (value is 1<<25). + *

+ * When orientation is not explicitly specified, orientation is + * inherited. This means that children will be assigned the + * orientation of their parent. To override this behavior and + * force an orientation for a child, explicitly set the orientation + * of the child when that child is created. + *
Note that this is a HINT. + *

+ *

Used By:

+ * + * @since 2.1.2 + */ + public static const int LEFT_TO_RIGHT = 1 << 25; + + /** + * Style constant for right to left orientation (value is 1<<26). + *

+ * When orientation is not explicitly specified, orientation is + * inherited. This means that children will be assigned the + * orientation of their parent. To override this behavior and + * force an orientation for a child, explicitly set the orientation + * of the child when that child is created. + *
Note that this is a HINT. + *

+ *

Used By:

+ * + * @since 2.1.2 + */ + public static const int RIGHT_TO_LEFT = 1 << 26; + + /** + * Style constant to indicate coordinate mirroring (value is 1<<27). + *

Used By:

+ * + * @since 2.1.2 + */ + public static const int MIRRORED = 1 << 27; + + /** + * Style constant to allow embedding (value is 1<<24). + *

Used By:

+ * + * @since 3.0 + */ + public static const int EMBEDDED = 1 << 24; + + /** + * Style constant to allow virtual data (value is 1<<28). + *

Used By:

+ * + * @since 3.0 + */ + public static const int VIRTUAL = 1 << 28; + + /** + * Style constant to indicate double buffering (value is 1<<29). + *

Used By:

+ * + * @since 3.1 + */ + public static const int DOUBLE_BUFFERED = 1 << 29; + + /** + * Style constant for align up behavior (value is 1<<7, + * since align UP and align TOP are considered the same). + *

Used By:

+ */ + public static const int UP = 1 << 7; + + /** + * Style constant for align top behavior (value is 1<<7, + * since align UP and align TOP are considered the same). + *

Used By:

+ */ + public static const int TOP = UP; + + /** + * Style constant for align down behavior (value is 1<<10, + * since align DOWN and align BOTTOM are considered the same). + *

Used By:

+ */ + public static const int DOWN = 1 << 10; + + /** + * Style constant for align bottom behavior (value is 1<<10, + * since align DOWN and align BOTTOM are considered the same). + *

Used By:

+ */ + public static const int BOTTOM = DOWN; + + /** + * Style constant for leading alignment (value is 1<<14). + *

Used By:

+ * + * @since 2.1.2 + */ + public static const int LEAD = 1 << 14; + + /** + * Style constant for align left behavior (value is 1<<14). + * This is a synonym for LEAD (value is 1<<14). Newer + * applications should use LEAD instead of LEFT to make code more + * understandable on right-to-left platforms. + */ + public static const int LEFT = LEAD; + + /** + * Style constant for trailing alignment (value is 1<<17). + *

Used By:

+ * + * @since 2.1.2 + */ + public static const int TRAIL = 1 << 17; + + /** + * Style constant for align right behavior (value is 1<<17). + * This is a synonym for TRAIL (value is 1<<17). Newer + * applications should use TRAIL instead of RIGHT to make code more + * understandable on right-to-left platforms. + */ + public static const int RIGHT = TRAIL; + + /** + * Style constant for align center behavior (value is 1<<24). + *

Used By:

+ */ + public static const int CENTER = 1 << 24; + + /** + * Style constant for horizontal alignment or orientation behavior (value is 1<<8). + *

Used By:

+ */ + public static const int HORIZONTAL = 1 << 8; + + /** + * Style constant for vertical alignment or orientation behavior (value is 1<<9). + *

Used By:

+ */ + public static const int VERTICAL = 1 << 9; + + /** + * Style constant for date display (value is 1<<5). + *

Used By:

+ * + * @since 3.3 + */ + public static const int DATE = 1 << 5; + + /** + * Style constant for time display (value is 1<<7). + *

Used By:

+ * + * @since 3.3 + */ + public static const int TIME = 1 << 7; + + /** + * Style constant for calendar display (value is 1<<10). + *

Used By:

+ * + * @since 3.3 + */ + public static const int CALENDAR = 1 << 10; + + /** + * Style constant for short date/time format (value is 1<<15). + *

+ * A short date displays the month and year. + * A short time displays hours and minutes. + *
Note that this is a HINT. + *

+ *

Used By:

+ * + * @since 3.3 + */ + public static const int SHORT = 1 << 15; + + /** + * Style constant for medium date/time format (value is 1<<16). + *

+ * A medium date displays the day, month and year. + * A medium time displays hours, minutes, and seconds. + *
Note that this is a HINT. + *

+ *

Used By:

+ * + * @since 3.3 + */ + public static const int MEDIUM = 1 << 16; + + /** + * Style constant for long date/time format (value is 1<<28). + *

+ * A long date displays the day, month and year. + * A long time displays hours, minutes, and seconds. + * The day and month names may be displayed. + *
Note that this is a HINT. + *

+ *

Used By:

+ * + * @since 3.3 + */ + public static const int LONG = 1 << 28; + + /** + * Style constant specifying that a Browser should use a Mozilla GRE + * for rendering its content (value is 1<<15). + *

+ *

Used By:

+ * + * @since 3.3 + */ + public static const int MOZILLA = 1 << 15; + + /** + * Style constant for balloon behavior (value is 1<<12). + *

Used By:

+ * + * @since 3.2 + */ + public static const int BALLOON = 1 << 12; + + /** + * Style constant for vertical alignment or orientation behavior (value is 1). + *

Used By:

+ */ + public static const int BEGINNING = 1; + + /** + * Style constant for vertical alignment or orientation behavior (value is 4). + *

Used By:

+ */ + public static const int FILL = 4; + + /** + * Input Method Editor style constant for double byte + * input behavior (value is 1<<1). + */ + public static const int DBCS = 1 << 1; + + /** + * Input Method Editor style constant for alpha + * input behavior (value is 1<<2). + */ + public static const int ALPHA = 1 << 2; + + /** + * Input Method Editor style constant for native + * input behavior (value is 1<<3). + */ + public static const int NATIVE = 1 << 3; + + /** + * Input Method Editor style constant for phonetic + * input behavior (value is 1<<4). + */ + public static const int PHONETIC = 1 << 4; + + /** + * Input Method Editor style constant for romanicized + * input behavior (value is 1<<5). + */ + public static const int ROMAN = 1 << 5; + + /** + * ASCII character convenience constant for the backspace character + * (value is the char '\b'). + */ + public static const char BS = '\b'; + + /** + * ASCII character convenience constant for the carriage return character + * (value is the char '\r'). + */ + public static const char CR = '\r'; + + /** + * ASCII character convenience constant for the delete character + * (value is the char with value 127). + */ + public static const char DEL = 0x7F; + + /** + * ASCII character convenience constant for the escape character + * (value is the char with value 27). + */ + public static const char ESC = 0x1B; + + /** + * ASCII character convenience constant for the line feed character + * (value is the char '\n'). + */ + public static const char LF = '\n'; + + /** + * ASCII character convenience constant for the tab character + * (value is the char '\t'). + * + * @since 2.1 + */ + public static const char TAB = '\t'; + + /** + * keyboard and/or mouse event mask indicating that the ALT key + * was pushed on the keyboard when the event was generated + * (value is 1<<16). + */ + public static const int ALT = 1 << 16; + + /** + * Keyboard and/or mouse event mask indicating that the SHIFT key + * was pushed on the keyboard when the event was generated + * (value is 1<<17). + */ + public static const int SHIFT = 1 << 17; + + /** + * Keyboard and/or mouse event mask indicating that the CTRL key + * was pushed on the keyboard when the event was generated + * (value is 1<<18). + */ + public static const int CTRL = 1 << 18; + + /** + * Keyboard and/or mouse event mask indicating that the CTRL key + * was pushed on the keyboard when the event was generated. This + * is a synonym for CTRL (value is 1<<18). + */ + public static const int CONTROL = CTRL; + + /** + * Keyboard and/or mouse event mask indicating that the COMMAND key + * was pushed on the keyboard when the event was generated + * (value is 1<<22). + * + * @since 2.1 + */ + public static const int COMMAND = 1 << 22; + + /** + * Keyboard and/or mouse event mask indicating all possible + * keyboard modifiers. + * + * To allow for the future, this mask is intended to be used in + * place of code that references each individual keyboard mask. + * For example, the following expression will determine whether + * any modifier is pressed and will continue to work as new modifier + * masks are added. + * + * (stateMask & SWT.MODIFIER_MASK) != 0. + * + * @since 2.1 + */ + public static /*const*/ int MODIFIER_MASK; + + /** + * Keyboard and/or mouse event mask indicating that mouse button one + * was pushed when the event was generated. (value is 1<<19). + */ + public static const int BUTTON1 = 1 << 19; + + /** + * Keyboard and/or mouse event mask indicating that mouse button two + * was pushed when the event was generated. (value is 1<<20). + */ + public static const int BUTTON2 = 1 << 20; + + /** + * Keyboard and/or mouse event mask indicating that mouse button three + * was pushed when the event was generated. (value is 1<<21). + */ + public static const int BUTTON3 = 1 << 21; + + /** + * Keyboard and/or mouse event mask indicating that mouse button four + * was pushed when the event was generated. (value is 1<<23). + * + * @since 3.1 + */ + public static const int BUTTON4 = 1 << 23; + + /** + * Keyboard and/or mouse event mask indicating that mouse button five + * was pushed when the event was generated. (value is 1<<25). + * + * @since 3.1 + */ + public static const int BUTTON5 = 1 << 25; + + /** + * Keyboard and/or mouse event mask indicating all possible + * mouse buttons. + * + * To allow for the future, this mask is intended to be used + * in place of code that references each individual button mask. + * For example, the following expression will determine whether + * any button is pressed and will continue to work as new button + * masks are added. + * + * (stateMask & SWT.BUTTON_MASK) != 0. + * + * @since 2.1 + */ + public static /*const*/ int BUTTON_MASK; + + /** + * Keyboard and/or mouse event mask indicating that the MOD1 key + * was pushed on the keyboard when the event was generated. + * + * This is the primary keyboard modifier for the platform. + * + * @since 2.1 + */ + public static /*const*/ int MOD1; + + /** + * Keyboard and/or mouse event mask indicating that the MOD2 key + * was pushed on the keyboard when the event was generated. + * + * This is the secondary keyboard modifier for the platform. + * + * @since 2.1 + */ + public static /*const*/ int MOD2; + + /** + * Keyboard and/or mouse event mask indicating that the MOD3 key + * was pushed on the keyboard when the event was generated. + * + * @since 2.1 + */ + public static /*const*/ int MOD3; + + /** + * Keyboard and/or mouse event mask indicating that the MOD4 key + * was pushed on the keyboard when the event was generated. + * + * @since 2.1 + */ + public static /*const*/ int MOD4; + + /** + * Constants to indicate line scrolling (value is 1). + *

Used By:

+ * + * @since 3.1 + */ + public static const int SCROLL_LINE = 1; + + /** + * Constants to indicate page scrolling (value is 2). + *

Used By:

+ * + * @since 3.1 + */ + public static const int SCROLL_PAGE = 2; + + /** + * Accelerator constant used to differentiate a key code from a + * unicode character. + * + * If this bit is set, then the key stroke + * portion of an accelerator represents a key code. If this bit + * is not set, then the key stroke portion of an accelerator is + * a unicode character. + * + * The following expression is false: + * + * ((SWT.MOD1 | SWT.MOD2 | 'T') & SWT.KEYCODE_BIT) != 0. + * + * The following expression is true: + * + * ((SWT.MOD3 | SWT.F2) & SWT.KEYCODE_BIT) != 0. + * + * (value is (1<<24)) + * + * @since 2.1 + */ + public static const int KEYCODE_BIT = (1 << 24); + + /** + * Accelerator constant used to extract the key stroke portion of + * an accelerator. + * + * The key stroke may be a key code or a unicode + * value. If the key stroke is a key code KEYCODE_BIT + * will be set. + * + * @since 2.1 + */ + public static const int KEY_MASK = KEYCODE_BIT + 0xFFFF; + + /** + * Keyboard event constant representing the UP ARROW key + * (value is (1<<24)+1). + */ + public static const int ARROW_UP = KEYCODE_BIT + 1; + + /** + * Keyboard event constant representing the DOWN ARROW key + * (value is (1<<24)+2). + */ + public static const int ARROW_DOWN = KEYCODE_BIT + 2; + + /** + * Keyboard event constant representing the LEFT ARROW key + * (value is (1<<24)+3). + */ + public static const int ARROW_LEFT = KEYCODE_BIT + 3; + + /** + * Keyboard event constant representing the RIGHT ARROW key + * (value is (1<<24)+4). + */ + public static const int ARROW_RIGHT = KEYCODE_BIT + 4; + + /** + * Keyboard event constant representing the PAGE UP key + * (value is (1<<24)+5). + */ + public static const int PAGE_UP = KEYCODE_BIT + 5; + + /** + * Keyboard event constant representing the PAGE DOWN key + * (value is (1<<24)+6). + */ + public static const int PAGE_DOWN = KEYCODE_BIT + 6; + + /** + * Keyboard event constant representing the HOME key + * (value is (1<<24)+7). + */ + public static const int HOME = KEYCODE_BIT + 7; + + /** + * Keyboard event constant representing the END key + * (value is (1<<24)+8). + */ + public static const int END = KEYCODE_BIT + 8; + + /** + * Keyboard event constant representing the INSERT key + * (value is (1<<24)+9). + */ + public static const int INSERT = KEYCODE_BIT + 9; + + /** + * Keyboard event constant representing the F1 key + * (value is (1<<24)+10). + */ + public static const int F1 = KEYCODE_BIT + 10; + + /** + * Keyboard event constant representing the F2 key + * (value is (1<<24)+11). + */ + public static const int F2 = KEYCODE_BIT + 11; + + /** + * Keyboard event constant representing the F3 key + * (value is (1<<24)+12). + */ + public static const int F3 = KEYCODE_BIT + 12; + + /** + * Keyboard event constant representing the F4 key + * (value is (1<<24)+13). + */ + public static const int F4 = KEYCODE_BIT + 13; + + /** + * Keyboard event constant representing the F5 key + * (value is (1<<24)+14). + */ + public static const int F5 = KEYCODE_BIT + 14; + + /** + * Keyboard event constant representing the F6 key + * (value is (1<<24)+15). + */ + public static const int F6 = KEYCODE_BIT + 15; + + /** + * Keyboard event constant representing the F7 key + * (value is (1<<24)+16). + */ + public static const int F7 = KEYCODE_BIT + 16; + + /** + * Keyboard event constant representing the F8 key + * (value is (1<<24)+17). + */ + public static const int F8 = KEYCODE_BIT + 17; + + /** + * Keyboard event constant representing the F9 key + * (value is (1<<24)+18). + */ + public static const int F9 = KEYCODE_BIT + 18; + + /** + * Keyboard event constant representing the F10 key + * (value is (1<<24)+19). + */ + public static const int F10 = KEYCODE_BIT + 19; + + /** + * Keyboard event constant representing the F11 key + * (value is (1<<24)+20). + */ + public static const int F11 = KEYCODE_BIT + 20; + + /** + * Keyboard event constant representing the F12 key + * (value is (1<<24)+21). + */ + public static const int F12 = KEYCODE_BIT + 21; + + /** + * Keyboard event constant representing the F13 key + * (value is (1<<24)+22). + * + * @since 3.0 + */ + public static const int F13 = KEYCODE_BIT + 22; + + /** + * Keyboard event constant representing the F14 key + * (value is (1<<24)+23). + * + * @since 3.0 + */ + public static const int F14 = KEYCODE_BIT + 23; + + /** + * Keyboard event constant representing the F15 key + * (value is (1<<24)+24). + * + * @since 3.0 + */ + public static const int F15 = KEYCODE_BIT + 24; + + /** + * Keyboard event constant representing the numeric key + * pad multiply key (value is (1<<24)+42). + * + * @since 3.0 + */ + public static const int KEYPAD_MULTIPLY = KEYCODE_BIT + 42; + + /** + * Keyboard event constant representing the numeric key + * pad add key (value is (1<<24)+43). + * + * @since 3.0 + */ + public static const int KEYPAD_ADD = KEYCODE_BIT + 43; + + /** + * Keyboard event constant representing the numeric key + * pad subtract key (value is (1<<24)+45). + * + * @since 3.0 + */ + public static const int KEYPAD_SUBTRACT = KEYCODE_BIT + 45; + + /** + * Keyboard event constant representing the numeric key + * pad decimal key (value is (1<<24)+46). + * + * @since 3.0 + */ + public static const int KEYPAD_DECIMAL = KEYCODE_BIT + 46; + + /** + * Keyboard event constant representing the numeric key + * pad divide key (value is (1<<24)+47). + * + * @since 3.0 + */ + public static const int KEYPAD_DIVIDE = KEYCODE_BIT + 47; + + /** + * Keyboard event constant representing the numeric key + * pad zero key (value is (1<<24)+48). + * + * @since 3.0 + */ + public static const int KEYPAD_0 = KEYCODE_BIT + 48; + + /** + * Keyboard event constant representing the numeric key + * pad one key (value is (1<<24)+49). + * + * @since 3.0 + */ + public static const int KEYPAD_1 = KEYCODE_BIT + 49; + + /** + * Keyboard event constant representing the numeric key + * pad two key (value is (1<<24)+50). + * + * @since 3.0 + */ + public static const int KEYPAD_2 = KEYCODE_BIT + 50; + + /** + * Keyboard event constant representing the numeric key + * pad three key (value is (1<<24)+51). + * + * @since 3.0 + */ + public static const int KEYPAD_3 = KEYCODE_BIT + 51; + + /** + * Keyboard event constant representing the numeric key + * pad four key (value is (1<<24)+52). + * + * @since 3.0 + */ + public static const int KEYPAD_4 = KEYCODE_BIT + 52; + + /** + * Keyboard event constant representing the numeric key + * pad five key (value is (1<<24)+53). + * + * @since 3.0 + */ + public static const int KEYPAD_5 = KEYCODE_BIT + 53; + + /** + * Keyboard event constant representing the numeric key + * pad six key (value is (1<<24)+54). + * + * @since 3.0 + */ + public static const int KEYPAD_6 = KEYCODE_BIT + 54; + + /** + * Keyboard event constant representing the numeric key + * pad seven key (value is (1<<24)+55). + * + * @since 3.0 + */ + public static const int KEYPAD_7 = KEYCODE_BIT + 55; + + /** + * Keyboard event constant representing the numeric key + * pad eight key (value is (1<<24)+56). + * + * @since 3.0 + */ + public static const int KEYPAD_8 = KEYCODE_BIT + 56; + + /** + * Keyboard event constant representing the numeric key + * pad nine key (value is (1<<24)+57). + * + * @since 3.0 + */ + public static const int KEYPAD_9 = KEYCODE_BIT + 57; + + /** + * Keyboard event constant representing the numeric key + * pad equal key (value is (1<<24)+61). + * + * @since 3.0 + */ + public static const int KEYPAD_EQUAL = KEYCODE_BIT + 61; + + /** + * Keyboard event constant representing the numeric key + * pad enter key (value is (1<<24)+80). + * + * @since 3.0 + */ + public static const int KEYPAD_CR = KEYCODE_BIT + 80; + + /** + * Keyboard event constant representing the help + * key (value is (1<<24)+81). + * + * NOTE: The HELP key maps to the key labeled "help", + * not "F1". If your keyboard does not have a HELP key, + * you will never see this key press. To listen for + * help on a control, use SWT.Help. + * + * @since 3.0 + * + * @see SWT#Help + */ + public static const int HELP = KEYCODE_BIT + 81; + + /** + * Keyboard event constant representing the caps + * lock key (value is (1<<24)+82). + * + * @since 3.0 + */ + public static const int CAPS_LOCK = KEYCODE_BIT + 82; + + /** + * Keyboard event constant representing the num + * lock key (value is (1<<24)+83). + * + * @since 3.0 + */ + public static const int NUM_LOCK = KEYCODE_BIT + 83; + + /** + * Keyboard event constant representing the scroll + * lock key (value is (1<<24)+84). + * + * @since 3.0 + */ + public static const int SCROLL_LOCK = KEYCODE_BIT + 84; + + /** + * Keyboard event constant representing the pause + * key (value is (1<<24)+85). + * + * @since 3.0 + */ + public static const int PAUSE = KEYCODE_BIT + 85; + + /** + * Keyboard event constant representing the break + * key (value is (1<<24)+86). + * + * @since 3.0 + */ + public static const int BREAK = KEYCODE_BIT + 86; + + /** + * Keyboard event constant representing the print screen + * key (value is (1<<24)+87). + * + * @since 3.0 + */ + public static const int PRINT_SCREEN = KEYCODE_BIT + 87; + + /** + * The MessageBox style constant for error icon + * behavior (value is 1). + */ + public static const int ICON_ERROR = 1; + + /** + * The MessageBox style constant for information icon + * behavior (value is 1<<1). + */ + public static const int ICON_INFORMATION = 1 << 1; + + /** + * The MessageBox style constant for question icon + * behavior (value is 1<<2). + */ + public static const int ICON_QUESTION = 1 << 2; + + /** + * The MessageBox style constant for warning icon + * behavior (value is 1<<3). + */ + public static const int ICON_WARNING = 1 << 3; + + /** + * The MessageBox style constant for "working" icon + * behavior (value is 1<<4). + */ + public static const int ICON_WORKING = 1 << 4; + + /** + * The MessageBox style constant for an OK button; + * valid combinations are OK, OK|CANCEL + * (value is 1<<5). + */ + public static const int OK = 1 << 5; + + /** + * The MessageBox style constant for YES button; + * valid combinations are YES|NO, YES|NO|CANCEL + * (value is 1<<6). + */ + public static const int YES = 1 << 6; + + /** + * The MessageBox style constant for NO button; + * valid combinations are YES|NO, YES|NO|CANCEL + * (value is 1<<7). + */ + public static const int NO = 1 << 7; + + /** + * The MessageBox style constant for a CANCEL button; + * valid combinations are OK|CANCEL, YES|NO|CANCEL, RETRY|CANCEL + * (value is 1<<8). This style constant is also used with + * Text in combination with SEARCH. + * + *

Used By:

+ */ + public static const int CANCEL = 1 << 8; + + /** + * The MessageBox style constant for an ABORT button; + * the only valid combination is ABORT|RETRY|IGNORE + * (value is 1<<9). + */ + public static const int ABORT = 1 << 9; + + /** + * The MessageBox style constant for a RETRY button; + * valid combinations are ABORT|RETRY|IGNORE, RETRY|CANCEL + * (value is 1<<10). + */ + public static const int RETRY = 1 << 10; + + /** + * The MessageBox style constant for an IGNORE button; + * the only valid combination is ABORT|RETRY|IGNORE + * (value is 1<<11). + */ + public static const int IGNORE = 1 << 11; + + /** + * The FileDialog style constant for open file dialog behavior + * (value is 1<<12). + */ + public static const int OPEN = 1 << 12; + + /** + * The FileDialog style constant for save file dialog behavior + * (value is 1<<13). + */ + public static const int SAVE = 1 << 13; + + /** + * The Composite constant to indicate that + * an attribute (such as background) is not inherited + * by the children (value is 0). + * + * @since 3.2 + */ + public static const int INHERIT_NONE = 0; + + /** + * The Composite constant to indicate that + * an attribute (such as background) is inherited by + * children who choose this value as their "default" + * (value is 1). For example, a label child will + * typically choose to inherit the background color + * of a composite while a list or table will not. + * + * @since 3.2 + */ + public static const int INHERIT_DEFAULT = 1; + + /** + * The Composite constant to indicate that + * an attribute (such as background) is inherited by + * all children. + * + * @since 3.2 + */ + public static const int INHERIT_FORCE = 2; + + /** + * Default color white (value is 1). + */ + public static const int COLOR_WHITE = 1; + + /** + * Default color black (value is 2). + */ + public static const int COLOR_BLACK = 2; + + /** + * Default color red (value is 3). + */ + public static const int COLOR_RED = 3; + + /** + * Default color dark red (value is 4). + */ + public static const int COLOR_DARK_RED = 4; + + /** + * Default color green (value is 5). + */ + public static const int COLOR_GREEN = 5; + + /** + * Default color dark green (value is 6). + */ + public static const int COLOR_DARK_GREEN = 6; + + /** + * Default color yellow (value is 7). + */ + public static const int COLOR_YELLOW = 7; + + /** + * Default color dark yellow (value is 8). + */ + public static const int COLOR_DARK_YELLOW = 8; + + /** + * Default color blue (value is 9). + */ + public static const int COLOR_BLUE = 9; + + /** + * Default color dark blue (value is 10). + */ + public static const int COLOR_DARK_BLUE = 10; + + /** + * Default color magenta (value is 11). + */ + public static const int COLOR_MAGENTA = 11; + + /** + * Default color dark magenta (value is 12). + */ + public static const int COLOR_DARK_MAGENTA = 12; + + /** + * Default color cyan (value is 13). + */ + public static const int COLOR_CYAN = 13; + + /** + * Default color dark cyan (value is 14). + */ + public static const int COLOR_DARK_CYAN = 14; + + /** + * Default color gray (value is 15). + */ + public static const int COLOR_GRAY = 15; + + /** + * Default color dark gray (value is 16). + */ + public static const int COLOR_DARK_GRAY = 16; + + /* + * System Colors + * + * Dealing with system colors is an area where there are + * many platform differences. On some platforms, system + * colors can change dynamically while the program is + * running. On other platforms, system colors can be + * changed for all instances of a particular widget. + * Therefore, the only truly portable method to obtain + * a widget color query is to query the color from an + * instance of the widget. + * + * It is expected that the list of supported colors + * will grow over time. + */ + + /** + * System color used to paint dark shadow areas (value is 17). + */ + public static const int COLOR_WIDGET_DARK_SHADOW = 17; + + /** + * System color used to paint normal shadow areas (value is 18). + */ + public static const int COLOR_WIDGET_NORMAL_SHADOW = 18; + + /** + * System color used to paint light shadow areas (value is 19). + */ + public static const int COLOR_WIDGET_LIGHT_SHADOW = 19; + + /** + * System color used to paint highlight shadow areas (value is 20). + */ + public static const int COLOR_WIDGET_HIGHLIGHT_SHADOW = 20; + + /** + * System color used to paint foreground areas (value is 21). + */ + public static const int COLOR_WIDGET_FOREGROUND = 21; + + /** + * System color used to paint background areas (value is 22). + */ + public static const int COLOR_WIDGET_BACKGROUND = 22; + + /** + * System color used to paint border areas (value is 23). + */ + public static const int COLOR_WIDGET_BORDER = 23; + + /** + * System color used to paint list foreground areas (value is 24). + */ + public static const int COLOR_LIST_FOREGROUND = 24; + + /** + * System color used to paint list background areas (value is 25). + */ + public static const int COLOR_LIST_BACKGROUND = 25; + + /** + * System color used to paint list selection background areas (value is 26). + */ + public static const int COLOR_LIST_SELECTION = 26; + + /** + * System color used to paint list selected text (value is 27). + */ + public static const int COLOR_LIST_SELECTION_TEXT = 27; + + /** + * System color used to paint tooltip text (value is 28). + */ + public static const int COLOR_INFO_FOREGROUND = 28; + + /** + * System color used to paint tooltip background areas (value is 29). + */ + public static const int COLOR_INFO_BACKGROUND = 29; + + /** + * System color used to paint title text (value is 30). + */ + public static const int COLOR_TITLE_FOREGROUND = 30; + + /** + * System color used to paint title background areas (value is 31). + */ + public static const int COLOR_TITLE_BACKGROUND = 31; + + /** + * System color used to paint title background gradient (value is 32). + */ + public static const int COLOR_TITLE_BACKGROUND_GRADIENT = 32; + + /** + * System color used to paint inactive title text (value is 33). + */ + public static const int COLOR_TITLE_INACTIVE_FOREGROUND = 33; + + /** + * System color used to paint inactive title background areas (value is 34). + */ + public static const int COLOR_TITLE_INACTIVE_BACKGROUND = 34; + + /** + * System color used to paint inactive title background gradient (value is 35). + */ + public static const int COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT = 35; + + /** + * Draw constant indicating whether the drawing operation + * should fill the background (value is 1<<0). + */ + public static const int DRAW_TRANSPARENT = 1 << 0; + + /** + * Draw constant indicating whether the string drawing operation + * should handle line-delimiters (value is 1<<1). + */ + public static const int DRAW_DELIMITER = 1 << 1; + + /** + * Draw constant indicating whether the string drawing operation + * should expand TAB characters (value is 1<<2). + */ + public static const int DRAW_TAB = 1 << 2; + + /** + * Draw constant indicating whether the string drawing operation + * should handle mnemonics (value is 1<<3). + */ + public static const int DRAW_MNEMONIC = 1 << 3; + + + /** + * Selection constant indicating that a line delimiter should be + * drawn (value is 1<<17). + * + *

Used By:

+ * + * @see #FULL_SELECTION + * @see #LAST_LINE_SELECTION + * + * @since 3.3 + */ + public static const int DELIMITER_SELECTION = 1 << 17; + + /** + * Selection constant indicating that the last line is selected + * to the end and should be drawn using either a line delimiter + * or full line selection (value is 1<<20). + * + *

Used By:

+ * + * @see #DELIMITER_SELECTION + * @see #FULL_SELECTION + * + * @since 3.3 + */ + public static const int LAST_LINE_SELECTION = 1 << 20; + + /** + * SWT error constant indicating that no error number was specified + * (value is 1). + */ + public static const int ERROR_UNSPECIFIED = 1; + + /** + * SWT error constant indicating that no more handles for an + * operating system resource are available + * (value is 2). + */ + public static const int ERROR_NO_HANDLES = 2; + + /** + * SWT error constant indicating that no more callback resources are available + * (value is 3). + */ + public static const int ERROR_NO_MORE_CALLBACKS = 3; + + /** + * SWT error constant indicating that a null argument was passed in + * (value is 4). + */ + public static const int ERROR_NULL_ARGUMENT = 4; + + /** + * SWT error constant indicating that an invalid argument was passed in + * (value is 5). + */ + public static const int ERROR_INVALID_ARGUMENT = 5; + + /** + * SWT error constant indicating that a value was found to be + * outside the allowable range + * (value is 6). + */ + public static const int ERROR_INVALID_RANGE = 6; + + /** + * SWT error constant indicating that a value which can not be + * zero was found to be + * (value is 7). + */ + public static const int ERROR_CANNOT_BE_ZERO = 7; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide the value of an item + * (value is 8). + */ + public static const int ERROR_CANNOT_GET_ITEM = 8; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide the selection + * (value is 9). + */ + public static const int ERROR_CANNOT_GET_SELECTION = 9; + + /** + * SWT error constant indicating that the matrix is not invertible + * (value is 10). + * + * @since 3.1 + */ + public static const int ERROR_CANNOT_INVERT_MATRIX = 10; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide the height of an item + * (value is 11). + */ + public static const int ERROR_CANNOT_GET_ITEM_HEIGHT = 11; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide the text of a widget + * (value is 12). + */ + public static const int ERROR_CANNOT_GET_TEXT = 12; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to set the text of a widget + * (value is 13). + */ + public static const int ERROR_CANNOT_SET_TEXT = 13; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to add an item + * (value is 14). + */ + public static const int ERROR_ITEM_NOT_ADDED = 14; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to remove an item + * (value is 15). + */ + public static const int ERROR_ITEM_NOT_REMOVED = 15; + + /** + * SWT error constant indicating that the graphics library + * is not available + * (value is 16). + */ + public static const int ERROR_NO_GRAPHICS_LIBRARY = 16; + + /** + * SWT error constant indicating that a particular feature has + * not been implemented on this platform + * (value is 20). + */ + public static const int ERROR_NOT_IMPLEMENTED = 20; + + /** + * SWT error constant indicating that a menu which needed + * to have the drop down style had some other style instead + * (value is 21). + */ + public static const int ERROR_MENU_NOT_DROP_DOWN = 21; + + /** + * SWT error constant indicating that an attempt was made to + * invoke an SWT operation which can only be executed by the + * user-interface thread from some other thread + * (value is 22). + */ + public static const int ERROR_THREAD_INVALID_ACCESS = 22; + + /** + * SWT error constant indicating that an attempt was made to + * invoke an SWT operation using a widget which had already + * been disposed + * (value is 24). + */ + public static const int ERROR_WIDGET_DISPOSED = 24; + + /** + * SWT error constant indicating that a menu item which needed + * to have the cascade style had some other style instead + * (value is 27). + */ + public static const int ERROR_MENUITEM_NOT_CASCADE = 27; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to set the selection of a widget + * (value is 28). + */ + public static const int ERROR_CANNOT_SET_SELECTION = 28; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to set the menu + * (value is 29). + */ + public static const int ERROR_CANNOT_SET_MENU = 29; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to set the enabled state + * (value is 30). + */ + public static const int ERROR_CANNOT_SET_ENABLED = 30; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide enabled/disabled state information + * (value is 31). + */ + public static const int ERROR_CANNOT_GET_ENABLED = 31; + + /** + * SWT error constant indicating that a provided widget can + * not be used as a parent in the current operation + * (value is 32). + */ + public static const int ERROR_INVALID_PARENT = 32; + + /** + * SWT error constant indicating that a menu which needed + * to have the menu bar style had some other style instead + * (value is 33). + */ + public static const int ERROR_MENU_NOT_BAR = 33; + + /** + * SWT error constant indicating that the underlying operating + * system was unable to provide count information + * (value is 36). + */ + public static const int ERROR_CANNOT_GET_COUNT = 36; + + /** + * SWT error constant indicating that a menu which needed + * to have the pop up menu style had some other style instead + * (value is 37). + */ + public static const int ERROR_MENU_NOT_POP_UP = 37; + + /** + * SWT error constant indicating that a graphics operation + * was attempted with an image of an unsupported depth + * (value is 38). + */ + public static const int ERROR_UNSUPPORTED_DEPTH = 38; + + /** + * SWT error constant indicating that an input/output operation + * failed during the execution of an SWT operation + * (value is 39). + */ + public static const int ERROR_IO = 39; + + /** + * SWT error constant indicating that a graphics operation + * was attempted with an image having an invalid format + * (value is 40). + */ + public static const int ERROR_INVALID_IMAGE = 40; + + /** + * SWT error constant indicating that a graphics operation + * was attempted with an image having a valid but unsupported + * format + * (value is 42). + */ + public static const int ERROR_UNSUPPORTED_FORMAT = 42; + + /** + * SWT error constant indicating that an attempt was made + * to subclass an SWT widget class without implementing the + * checkSubclass() method + * (value is 43). + * + * For additional information see the comment in + * Widget.checkSubclass(). + * + * @see dwt.widgets.Widget#checkSubclass + */ + public static const int ERROR_INVALID_SUBCLASS = 43; + + /** + * SWT error constant indicating that an attempt was made to + * invoke an SWT operation using a graphics object which had + * already been disposed + * (value is 44). + */ + public static const int ERROR_GRAPHIC_DISPOSED = 44; + + /** + * SWT error constant indicating that an attempt was made to + * invoke an SWT operation using a device which had already + * been disposed + * (value is 45). + */ + public static const int ERROR_DEVICE_DISPOSED = 45; + + /** + * SWT error constant indicating that an exception happened + * when executing a runnable + * (value is 46). + */ + public static const int ERROR_FAILED_EXEC = 46; + + /** + * SWT error constant indicating that an unsatisfied link + * error occurred while attempting to load a library + * (value is 47). + * + * @since 3.1 + */ + public static const int ERROR_FAILED_LOAD_LIBRARY = 47; + + /** + * SWT error constant indicating that a font is not valid + * (value is 48). + * + * @since 3.1 + */ + public static const int ERROR_INVALID_FONT = 48; + + /** + * Constant indicating that an image or operation is of type bitmap (value is 0). + */ + public static const int BITMAP = 0; + + /** + * Constant indicating that an image or operation is of type icon (value is 1). + */ + public static const int ICON = 1; + + /** + * The Image constructor argument indicating that + * the new image should be a copy of the image provided as + * an argument (value is 0). + */ + public static const int IMAGE_COPY = 0; + + /** + * The Image constructor argument indicating that + * the new image should have the appearance of a "disabled" + * (using the platform's rules for how this should look) + * copy of the image provided as an argument (value is 1). + */ + public static const int IMAGE_DISABLE = 1; + + /** + * The Image constructor argument indicating that + * the new image should have the appearance of a "gray scaled" + * copy of the image provided as an argument (value is 2). + */ + public static const int IMAGE_GRAY = 2; + + /** + * The font style constant indicating a normal weight, non-italic font + * (value is 0). + */ + public static const int NORMAL = 0; + + /** + * The font style constant indicating a bold weight font + * (value is 1<<0). + */ + public static const int BOLD = 1 << 0; + + /** + * The font style constant indicating an italic font + * (value is 1<<1). + */ + public static const int ITALIC = 1 << 1; + + /** + * System arrow cursor (value is 0). + */ + public static const int CURSOR_ARROW = 0; + + /** + * System wait cursor (value is 1). + */ + public static const int CURSOR_WAIT = 1; + + /** + * System cross hair cursor (value is 2). + */ + public static const int CURSOR_CROSS = 2; + + /** + * System app startup cursor (value is 3). + */ + public static const int CURSOR_APPSTARTING = 3; + + /** + * System help cursor (value is 4). + */ + public static const int CURSOR_HELP = 4; + + /** + * System resize all directions cursor (value is 5). + */ + public static const int CURSOR_SIZEALL = 5; + + /** + * System resize north-east-south-west cursor (value is 6). + */ + public static const int CURSOR_SIZENESW = 6; + + /** + * System resize north-south cursor (value is 7). + */ + public static const int CURSOR_SIZENS = 7; + + /** + * System resize north-west-south-east cursor (value is 8). + */ + public static const int CURSOR_SIZENWSE = 8; + + /** + * System resize west-east cursor (value is 9). + */ + public static const int CURSOR_SIZEWE = 9; + + /** + * System resize north cursor (value is 10). + */ + public static const int CURSOR_SIZEN = 10; + + /** + * System resize south cursor (value is 11). + */ + public static const int CURSOR_SIZES = 11; + + /** + * System resize east cursor (value is 12). + */ + public static const int CURSOR_SIZEE = 12; + + /** + * System resize west cursor (value is 13). + */ + public static const int CURSOR_SIZEW = 13; + + /** + * System resize north-east cursor (value is 14). + */ + public static const int CURSOR_SIZENE = 14; + + /** + * System resize south-east cursor (value is 15). + */ + public static const int CURSOR_SIZESE = 15; + + /** + * System resize south-west cursor (value is 16). + */ + public static const int CURSOR_SIZESW = 16; + + /** + * System resize north-west cursor (value is 17). + */ + public static const int CURSOR_SIZENW = 17; + + /** + * System up arrow cursor (value is 18). + */ + public static const int CURSOR_UPARROW = 18; + + /** + * System i-beam cursor (value is 19). + */ + public static const int CURSOR_IBEAM = 19; + + /** + * System "not allowed" cursor (value is 20). + */ + public static const int CURSOR_NO = 20; + + /** + * System hand cursor (value is 21). + */ + public static const int CURSOR_HAND = 21; + + /** + * Line drawing style for flat end caps (value is 1). + * + * @see dwt.graphics.GC#setLineCap(int) + * @see dwt.graphics.GC#getLineCap() + * + * @since 3.1 + */ + public static const int CAP_FLAT = 1; + + /** + * Line drawing style for rounded end caps (value is 2). + * + * @see dwt.graphics.GC#setLineCap(int) + * @see dwt.graphics.GC#getLineCap() + * + * @since 3.1 + */ + public static const int CAP_ROUND = 2; + + /** + * Line drawing style for square end caps (value is 3). + * + * @see dwt.graphics.GC#setLineCap(int) + * @see dwt.graphics.GC#getLineCap() + * + * @since 3.1 + */ + public static const int CAP_SQUARE = 3; + + /** + * Line drawing style for miter joins (value is 1). + * + * @see dwt.graphics.GC#setLineJoin(int) + * @see dwt.graphics.GC#getLineJoin() + * + * @since 3.1 + */ + public static const int JOIN_MITER = 1; + + /** + * Line drawing style for rounded joins (value is 2). + * + * @see dwt.graphics.GC#setLineJoin(int) + * @see dwt.graphics.GC#getLineJoin() + * + * @since 3.1 + */ + public static const int JOIN_ROUND = 2; + + /** + * Line drawing style for bevel joins (value is 3). + * + * @see dwt.graphics.GC#setLineJoin(int) + * @see dwt.graphics.GC#getLineJoin() + * + * @since 3.1 + */ + public static const int JOIN_BEVEL = 3; + + /** + * Line drawing style for solid lines (value is 1). + */ + public static const int LINE_SOLID = 1; + + /** + * Line drawing style for dashed lines (value is 2). + */ + public static const int LINE_DASH = 2; + + /** + * Line drawing style for dotted lines (value is 3). + */ + public static const int LINE_DOT = 3; + + /** + * Line drawing style for alternating dash-dot lines (value is 4). + */ + public static const int LINE_DASHDOT = 4; + + /** + * Line drawing style for dash-dot-dot lines (value is 5). + */ + public static const int LINE_DASHDOTDOT = 5; + + /** + * Line drawing style for custom dashed lines (value is 6). + * + * @see dwt.graphics.GC#setLineDash(int[]) + * @see dwt.graphics.GC#getLineDash() + * + * @since 3.1 + */ + public static const int LINE_CUSTOM = 6; + + /** + * Path constant that represents a "move to" operation (value is 1). + * + * @since 3.1 + */ + public static const int PATH_MOVE_TO = 1; + + /** + * Path constant that represents a "line to" operation (value is 2). + * + * @since 3.1 + */ + public static const int PATH_LINE_TO = 2; + + /** + * Path constant that represents a "quadratic curve to" operation (value is 3). + * + * @since 3.1 + */ + public static const int PATH_QUAD_TO = 3; + + /** + * Path constant that represents a "cubic curve to" operation (value is 4). + * + * @since 3.1 + */ + public static const int PATH_CUBIC_TO = 4; + + /** + * Path constant that represents a "close" operation (value is 5). + * + * @since 3.1 + */ + public static const int PATH_CLOSE = 5; + + /** + * Even odd rule for filling operations (value is 1). + * + * @since 3.1 + */ + public static const int FILL_EVEN_ODD = 1; + + /** + * Winding rule for filling operations (value is 2). + * + * @since 3.1 + */ + public static const int FILL_WINDING = 2; + + /** + * Image format constant indicating an unknown image type (value is -1). + */ + public static const int IMAGE_UNDEFINED = -1; + + /** + * Image format constant indicating a Windows BMP format image (value is 0). + */ + public static const int IMAGE_BMP = 0; + + /** + * Image format constant indicating a run-length encoded + * Windows BMP format image (value is 1). + */ + public static const int IMAGE_BMP_RLE = 1; + + /** + * Image format constant indicating a GIF format image (value is 2). + */ + public static const int IMAGE_GIF = 2; + + /** + * Image format constant indicating a ICO format image (value is 3). + */ + public static const int IMAGE_ICO = 3; + + /** + * Image format constant indicating a JPEG format image (value is 4). + */ + public static const int IMAGE_JPEG = 4; + + /** + * Image format constant indicating a PNG format image (value is 5). + */ + public static const int IMAGE_PNG = 5; + + /** + * Image format constant indicating a TIFF format image (value is 6). + */ + public static const int IMAGE_TIFF = 6; + + /** + * Image format constant indicating an OS/2 BMP format image (value is 7). + */ + public static const int IMAGE_OS2_BMP = 7; + + /** + * GIF image disposal method constants indicating that the + * disposal method is unspecified (value is 0). + */ + public static const int DM_UNSPECIFIED = 0x0; + + /** + * GIF image disposal method constants indicating that the + * disposal method is to do nothing; that is, to leave the + * previous image in place (value is 1). + */ + public static const int DM_FILL_NONE = 0x1; + + /** + * GIF image disposal method constants indicating that the + * the previous images should be covered with the background + * color before displaying the next image (value is 2). + */ + public static const int DM_FILL_BACKGROUND = 0x2; + + /** + * GIF image disposal method constants indicating that the + * disposal method is to restore the previous picture + * (value is 3). + */ + public static const int DM_FILL_PREVIOUS = 0x3; + + /** + * Image transparency constant indicating that the image + * contains no transparency information (value is 0). + */ + public static const int TRANSPARENCY_NONE = 0x0; + + /** + * Image transparency constant indicating that the image + * contains alpha transparency information (value is 1<<0). + */ + public static const int TRANSPARENCY_ALPHA = 1 << 0; + + /** + * Image transparency constant indicating that the image + * contains a transparency mask (value is 1<<1). + */ + public static const int TRANSPARENCY_MASK = 1 << 1; + + /** + * Image transparency constant indicating that the image + * contains a transparent pixel (value is 1<<2). + */ + public static const int TRANSPARENCY_PIXEL = 1 << 2; + + /** + * The character movement type (value is 1<<0). + * This constant is used to move a text offset over a character. + * + * @see dwt.graphics.TextLayout#getNextOffset(int, int) + * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) + * + * @since 3.0 + */ + public static const int MOVEMENT_CHAR = 1 << 0; + + /** + * The cluster movement type (value is 1<<1). + * This constant is used to move a text offset over a cluster. + * A cluster groups one or more characters. A cluster is + * undivisible, this means that a caret offset can not be placed in the + * middle of a cluster. + * + * @see dwt.graphics.TextLayout#getNextOffset(int, int) + * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) + * + * @since 3.0 + */ + public static const int MOVEMENT_CLUSTER = 1 << 1; + + /** + * The word movement type (value is 1<<2). + * This constant is used to move a text offset over a word. + * The behavior of this constant depends on the platform and on the + * direction of the movement. For example, on Windows the stop is + * always at the start of the word. On GTK and Mac the stop is at the end + * of the word if the direction is next and at the start of the word if the + * direction is previous. + * + * @see dwt.graphics.TextLayout#getNextOffset(int, int) + * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) + * + * @since 3.0 + */ + public static const int MOVEMENT_WORD = 1 << 2; + + /** + * The word end movement type (value is 1<<3). + * This constant is used to move a text offset to the next or previous + * word end. The behavior of this constant does not depend on the platform. + * + * + * @see dwt.graphics.TextLayout#getNextOffset(int, int) + * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) + * + * @since 3.3 + */ + public static const int MOVEMENT_WORD_END = 1 << 3; + + /** + * The word start movement type (value is 1<<4). + * This constant is used to move a text offset to the next or previous + * word start. The behavior of this constant does not depend on the platform. + * + * @see dwt.graphics.TextLayout#getNextOffset(int, int) + * @see dwt.graphics.TextLayout#getPreviousOffset(int, int) + * + * @since 3.3 + */ + public static const int MOVEMENT_WORD_START = 1 << 4; /** @@ -3373,49 +3373,49 @@ * @see SWT */ static char[] findErrorText (int code) { - switch (code) { - case ERROR_UNSPECIFIED: return "Unspecified error"; //$NON-NLS-1$ - case ERROR_NO_HANDLES: return "No more handles"; //$NON-NLS-1$ - case ERROR_NO_MORE_CALLBACKS: return "No more callbacks"; //$NON-NLS-1$ - case ERROR_NULL_ARGUMENT: return "Argument cannot be null"; //$NON-NLS-1$ - case ERROR_INVALID_ARGUMENT: return "Argument not valid"; //$NON-NLS-1$ - case ERROR_INVALID_RANGE: return "Index out of bounds"; //$NON-NLS-1$ - case ERROR_CANNOT_BE_ZERO: return "Argument cannot be zero"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_ITEM: return "Cannot get item"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_SELECTION: return "Cannot get selection"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_ITEM_HEIGHT: return "Cannot get item height"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_TEXT: return "Cannot get text"; //$NON-NLS-1$ - case ERROR_CANNOT_SET_TEXT: return "Cannot set text"; //$NON-NLS-1$ - case ERROR_ITEM_NOT_ADDED: return "Item not added"; //$NON-NLS-1$ - case ERROR_ITEM_NOT_REMOVED: return "Item not removed"; //$NON-NLS-1$ - case ERROR_NOT_IMPLEMENTED: return "Not implemented"; //$NON-NLS-1$ - case ERROR_MENU_NOT_DROP_DOWN: return "Menu must be a drop down"; //$NON-NLS-1$ - case ERROR_THREAD_INVALID_ACCESS: return "Invalid thread access"; //$NON-NLS-1$ - case ERROR_WIDGET_DISPOSED: return "Widget is disposed"; //$NON-NLS-1$ - case ERROR_MENUITEM_NOT_CASCADE: return "Menu item is not a CASCADE"; //$NON-NLS-1$ - case ERROR_CANNOT_SET_SELECTION: return "Cannot set selection"; //$NON-NLS-1$ - case ERROR_CANNOT_SET_MENU: return "Cannot set menu"; //$NON-NLS-1$ - case ERROR_CANNOT_SET_ENABLED: return "Cannot set the enabled state"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_ENABLED: return "Cannot get the enabled state"; //$NON-NLS-1$ - case ERROR_INVALID_PARENT: return "Widget has the wrong parent"; //$NON-NLS-1$ - case ERROR_MENU_NOT_BAR: return "Menu is not a BAR"; //$NON-NLS-1$ - case ERROR_CANNOT_GET_COUNT: return "Cannot get count"; //$NON-NLS-1$ - case ERROR_MENU_NOT_POP_UP: return "Menu is not a POP_UP"; //$NON-NLS-1$ - case ERROR_UNSUPPORTED_DEPTH: return "Unsupported color depth"; //$NON-NLS-1$ - case ERROR_IO: return "i/o error"; //$NON-NLS-1$ - case ERROR_INVALID_IMAGE: return "Invalid image"; //$NON-NLS-1$ - case ERROR_UNSUPPORTED_FORMAT: return "Unsupported or unrecognized format"; //$NON-NLS-1$ - case ERROR_INVALID_SUBCLASS: return "Subclassing not allowed"; //$NON-NLS-1$ - case ERROR_GRAPHIC_DISPOSED: return "Graphic is disposed"; //$NON-NLS-1$ - case ERROR_DEVICE_DISPOSED: return "Device is disposed"; //$NON-NLS-1$ - case ERROR_FAILED_EXEC: return "Failed to execute runnable"; //$NON-NLS-1$ - case ERROR_FAILED_LOAD_LIBRARY: return "Unable to load library"; //$NON-NLS-1$ - case ERROR_CANNOT_INVERT_MATRIX: return "Cannot invert matrix"; //$NON-NLS-1$ - case ERROR_NO_GRAPHICS_LIBRARY: return "Unable to load graphics library"; //$NON-NLS-1$ - case ERROR_INVALID_FONT: return "Font not valid"; //$NON-NLS-1$ + switch (code) { + case ERROR_UNSPECIFIED: return "Unspecified error"; //$NON-NLS-1$ + case ERROR_NO_HANDLES: return "No more handles"; //$NON-NLS-1$ + case ERROR_NO_MORE_CALLBACKS: return "No more callbacks"; //$NON-NLS-1$ + case ERROR_NULL_ARGUMENT: return "Argument cannot be null"; //$NON-NLS-1$ + case ERROR_INVALID_ARGUMENT: return "Argument not valid"; //$NON-NLS-1$ + case ERROR_INVALID_RANGE: return "Index out of bounds"; //$NON-NLS-1$ + case ERROR_CANNOT_BE_ZERO: return "Argument cannot be zero"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_ITEM: return "Cannot get item"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_SELECTION: return "Cannot get selection"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_ITEM_HEIGHT: return "Cannot get item height"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_TEXT: return "Cannot get text"; //$NON-NLS-1$ + case ERROR_CANNOT_SET_TEXT: return "Cannot set text"; //$NON-NLS-1$ + case ERROR_ITEM_NOT_ADDED: return "Item not added"; //$NON-NLS-1$ + case ERROR_ITEM_NOT_REMOVED: return "Item not removed"; //$NON-NLS-1$ + case ERROR_NOT_IMPLEMENTED: return "Not implemented"; //$NON-NLS-1$ + case ERROR_MENU_NOT_DROP_DOWN: return "Menu must be a drop down"; //$NON-NLS-1$ + case ERROR_THREAD_INVALID_ACCESS: return "Invalid thread access"; //$NON-NLS-1$ + case ERROR_WIDGET_DISPOSED: return "Widget is disposed"; //$NON-NLS-1$ + case ERROR_MENUITEM_NOT_CASCADE: return "Menu item is not a CASCADE"; //$NON-NLS-1$ + case ERROR_CANNOT_SET_SELECTION: return "Cannot set selection"; //$NON-NLS-1$ + case ERROR_CANNOT_SET_MENU: return "Cannot set menu"; //$NON-NLS-1$ + case ERROR_CANNOT_SET_ENABLED: return "Cannot set the enabled state"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_ENABLED: return "Cannot get the enabled state"; //$NON-NLS-1$ + case ERROR_INVALID_PARENT: return "Widget has the wrong parent"; //$NON-NLS-1$ + case ERROR_MENU_NOT_BAR: return "Menu is not a BAR"; //$NON-NLS-1$ + case ERROR_CANNOT_GET_COUNT: return "Cannot get count"; //$NON-NLS-1$ + case ERROR_MENU_NOT_POP_UP: return "Menu is not a POP_UP"; //$NON-NLS-1$ + case ERROR_UNSUPPORTED_DEPTH: return "Unsupported color depth"; //$NON-NLS-1$ + case ERROR_IO: return "i/o error"; //$NON-NLS-1$ + case ERROR_INVALID_IMAGE: return "Invalid image"; //$NON-NLS-1$ + case ERROR_UNSUPPORTED_FORMAT: return "Unsupported or unrecognized format"; //$NON-NLS-1$ + case ERROR_INVALID_SUBCLASS: return "Subclassing not allowed"; //$NON-NLS-1$ + case ERROR_GRAPHIC_DISPOSED: return "Graphic is disposed"; //$NON-NLS-1$ + case ERROR_DEVICE_DISPOSED: return "Device is disposed"; //$NON-NLS-1$ + case ERROR_FAILED_EXEC: return "Failed to execute runnable"; //$NON-NLS-1$ + case ERROR_FAILED_LOAD_LIBRARY: return "Unable to load library"; //$NON-NLS-1$ + case ERROR_CANNOT_INVERT_MATRIX: return "Cannot invert matrix"; //$NON-NLS-1$ + case ERROR_NO_GRAPHICS_LIBRARY: return "Unable to load graphics library"; //$NON-NLS-1$ + case ERROR_INVALID_FONT: return "Font not valid"; //$NON-NLS-1$ default: - } - return "Unknown error"; //$NON-NLS-1$ + } + return "Unknown error"; //$NON-NLS-1$ } @@ -3432,7 +3432,7 @@ public static char[] getMessage(char[] key) { // PORTING_FIXME: Implement return "msg not found"; - //return Compatibility.getMessage(key); + //return Compatibility.getMessage(key); } /** @@ -3442,7 +3442,7 @@ * @return the SWT platform name */ public static char[] getPlatform () { - return Platform.PLATFORM; + return Platform.PLATFORM; } /** @@ -3452,7 +3452,7 @@ * @return the SWT version number */ public static int getVersion () { - return Library.SWT_VERSION; + return Library.SWT_VERSION; } /** @@ -3461,7 +3461,7 @@ * @param code the SWT error code */ public static void error (int code) { - error (code, null); + error (code, null); } /** @@ -3490,7 +3490,7 @@ * @see IllegalArgumentException */ public static void error (int code, TracedException throwable) { - error (code, throwable, null); + error (code, throwable, null); } /** @@ -3523,120 +3523,120 @@ */ public static void error (int code, TracedException throwable, char[] detail) { - /* - * This code prevents the creation of "chains" of SWTErrors and - * SWTExceptions which in turn contain other SWTErrors and - * SWTExceptions as their throwable. This can occur when low level - * code throws an exception past a point where a higher layer is - * being "safe" and catching all exceptions. (Note that, this is - * _a_bad_thing_ which we always try to avoid.) - * - * On the theory that the low level code is closest to the - * original problem, we simply re-throw the original exception here. - * - * NOTE: Exceptions thrown in syncExec and asyncExec must be - * wrapped. - */ - if (code != SWT.ERROR_FAILED_EXEC) { - if (auto t = cast(SWTError)throwable) throw t; - if (auto t = cast(SWTException)throwable) throw t; - } - - char[] message = findErrorText (code); - if (detail != null) message ~= detail; - switch (code) { - - /* Illegal Arguments (non-fatal) */ - case ERROR_NULL_ARGUMENT: - case ERROR_CANNOT_BE_ZERO: - case ERROR_INVALID_ARGUMENT: - case ERROR_MENU_NOT_BAR: - case ERROR_MENU_NOT_DROP_DOWN: - case ERROR_MENU_NOT_POP_UP: - case ERROR_MENUITEM_NOT_CASCADE: - case ERROR_INVALID_PARENT: - case ERROR_INVALID_RANGE: { - throw new IllegalArgumentException (message); - } - - /* SWT Exceptions (non-fatal) */ - case ERROR_INVALID_SUBCLASS: - case ERROR_THREAD_INVALID_ACCESS: - case ERROR_WIDGET_DISPOSED: - case ERROR_GRAPHIC_DISPOSED: - case ERROR_DEVICE_DISPOSED: - case ERROR_INVALID_IMAGE: - case ERROR_UNSUPPORTED_DEPTH: - case ERROR_UNSUPPORTED_FORMAT: - case ERROR_FAILED_EXEC: - case ERROR_CANNOT_INVERT_MATRIX: - case ERROR_NO_GRAPHICS_LIBRARY: - case ERROR_IO: { - SWTException exception = new SWTException (code, message); - exception.throwable = throwable; - throw exception; - } - - /* Operation System Errors (fatal, may occur only on some platforms) */ - case ERROR_CANNOT_GET_COUNT: - case ERROR_CANNOT_GET_ENABLED: - case ERROR_CANNOT_GET_ITEM: - case ERROR_CANNOT_GET_ITEM_HEIGHT: - case ERROR_CANNOT_GET_SELECTION: - case ERROR_CANNOT_GET_TEXT: - case ERROR_CANNOT_SET_ENABLED: - case ERROR_CANNOT_SET_MENU: - case ERROR_CANNOT_SET_SELECTION: - case ERROR_CANNOT_SET_TEXT: - case ERROR_ITEM_NOT_ADDED: - case ERROR_ITEM_NOT_REMOVED: - case ERROR_NO_HANDLES: - //FALL THROUGH - - /* SWT Errors (fatal, may occur only on some platforms) */ - case ERROR_FAILED_LOAD_LIBRARY: - case ERROR_NO_MORE_CALLBACKS: - case ERROR_NOT_IMPLEMENTED: - case ERROR_UNSPECIFIED: { - SWTError error = new SWTError (code, message); - error.throwable = throwable; - throw error; - } + /* + * This code prevents the creation of "chains" of SWTErrors and + * SWTExceptions which in turn contain other SWTErrors and + * SWTExceptions as their throwable. This can occur when low level + * code throws an exception past a point where a higher layer is + * being "safe" and catching all exceptions. (Note that, this is + * _a_bad_thing_ which we always try to avoid.) + * + * On the theory that the low level code is closest to the + * original problem, we simply re-throw the original exception here. + * + * NOTE: Exceptions thrown in syncExec and asyncExec must be + * wrapped. + */ + if (code != SWT.ERROR_FAILED_EXEC) { + if (auto t = cast(SWTError)throwable) throw t; + if (auto t = cast(SWTException)throwable) throw t; + } + + char[] message = findErrorText (code); + if (detail != null) message ~= detail; + switch (code) { + + /* Illegal Arguments (non-fatal) */ + case ERROR_NULL_ARGUMENT: + case ERROR_CANNOT_BE_ZERO: + case ERROR_INVALID_ARGUMENT: + case ERROR_MENU_NOT_BAR: + case ERROR_MENU_NOT_DROP_DOWN: + case ERROR_MENU_NOT_POP_UP: + case ERROR_MENUITEM_NOT_CASCADE: + case ERROR_INVALID_PARENT: + case ERROR_INVALID_RANGE: { + throw new IllegalArgumentException (message); + } + + /* SWT Exceptions (non-fatal) */ + case ERROR_INVALID_SUBCLASS: + case ERROR_THREAD_INVALID_ACCESS: + case ERROR_WIDGET_DISPOSED: + case ERROR_GRAPHIC_DISPOSED: + case ERROR_DEVICE_DISPOSED: + case ERROR_INVALID_IMAGE: + case ERROR_UNSUPPORTED_DEPTH: + case ERROR_UNSUPPORTED_FORMAT: + case ERROR_FAILED_EXEC: + case ERROR_CANNOT_INVERT_MATRIX: + case ERROR_NO_GRAPHICS_LIBRARY: + case ERROR_IO: { + SWTException exception = new SWTException (code, message); + exception.throwable = throwable; + throw exception; + } + + /* Operation System Errors (fatal, may occur only on some platforms) */ + case ERROR_CANNOT_GET_COUNT: + case ERROR_CANNOT_GET_ENABLED: + case ERROR_CANNOT_GET_ITEM: + case ERROR_CANNOT_GET_ITEM_HEIGHT: + case ERROR_CANNOT_GET_SELECTION: + case ERROR_CANNOT_GET_TEXT: + case ERROR_CANNOT_SET_ENABLED: + case ERROR_CANNOT_SET_MENU: + case ERROR_CANNOT_SET_SELECTION: + case ERROR_CANNOT_SET_TEXT: + case ERROR_ITEM_NOT_ADDED: + case ERROR_ITEM_NOT_REMOVED: + case ERROR_NO_HANDLES: + //FALL THROUGH + + /* SWT Errors (fatal, may occur only on some platforms) */ + case ERROR_FAILED_LOAD_LIBRARY: + case ERROR_NO_MORE_CALLBACKS: + case ERROR_NOT_IMPLEMENTED: + case ERROR_UNSPECIFIED: { + SWTError error = new SWTError (code, message); + error.throwable = throwable; + throw error; + } default: - } - - /* Unknown/Undefined Error */ - SWTError error = new SWTError (code, message); - error.throwable = throwable; - throw error; + } + + /* Unknown/Undefined Error */ + SWTError error = new SWTError (code, message); + error.throwable = throwable; + throw error; } public static void static_this() { - /* - * These values represent bit masks that may need to - * expand in the future. Therefore they are not initialized - * in the declaration to stop the compiler from inlining. - */ - BUTTON_MASK = BUTTON1 | BUTTON2 | BUTTON3 | BUTTON4 | BUTTON5; - MODIFIER_MASK = ALT | SHIFT | CTRL | COMMAND; - - /* - * These values can be different on different platforms. - * Therefore they are not initialized in the declaration - * to stop the compiler from inlining. - */ - char[] platform = getPlatform (); - if ("carbon" == platform ) { //$NON-NLS-1$ - MOD1 = COMMAND; - MOD2 = SHIFT; - MOD3 = ALT; - MOD4 = CONTROL; - } else { - MOD1 = CONTROL; - MOD2 = SHIFT; - MOD3 = ALT; - MOD4 = 0; - } + /* + * These values represent bit masks that may need to + * expand in the future. Therefore they are not initialized + * in the declaration to stop the compiler from inlining. + */ + BUTTON_MASK = BUTTON1 | BUTTON2 | BUTTON3 | BUTTON4 | BUTTON5; + MODIFIER_MASK = ALT | SHIFT | CTRL | COMMAND; + + /* + * These values can be different on different platforms. + * Therefore they are not initialized in the declaration + * to stop the compiler from inlining. + */ + char[] platform = getPlatform (); + if ("carbon" == platform ) { //$NON-NLS-1$ + MOD1 = COMMAND; + MOD2 = SHIFT; + MOD3 = ALT; + MOD4 = CONTROL; + } else { + MOD1 = CONTROL; + MOD2 = SHIFT; + MOD3 = ALT; + MOD4 = 0; + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/SWTError.d --- a/dwt/SWTError.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/SWTError.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -45,13 +45,13 @@ /** * The SWT error code, one of SWT.ERROR_*. */ - public int code; + public int code; - /** - * The underlying throwable that caused the problem, - * or null if this information is not available. - */ - public TracedException throwable; + /** + * The underlying throwable that caused the problem, + * or null if this information is not available. + */ + public TracedException throwable; //static final long serialVersionUID = 3833467327105808433L; @@ -61,7 +61,7 @@ * unspecified value. */ public this () { - this (SWT.ERROR_UNSPECIFIED); + this (SWT.ERROR_UNSPECIFIED); } /** @@ -73,7 +73,7 @@ * @param message the detail message for the exception */ public this (char[] message) { - this (SWT.ERROR_UNSPECIFIED, message); + this (SWT.ERROR_UNSPECIFIED, message); } /** @@ -83,7 +83,7 @@ * @param code the SWT error code */ public this (int code) { - this (code, SWT.findErrorText (code)); + this (code, SWT.findErrorText (code)); } /** @@ -96,8 +96,8 @@ * @param message the detail message for the exception */ public this (int code, char[] message) { - super (message); - this.code = code; + super (message); + this.code = code; } /** @@ -113,7 +113,7 @@ * @since 3.1 */ public Exception getCause() { - return throwable; + return throwable; } /** @@ -125,9 +125,9 @@ * @return the error message string of this SWTError object */ public char[] getMessage () { - if (throwable is null) + if (throwable is null) return super.toString(); - return super.toString () ~ " (" ~ throwable.toString () ~ ")"; //$NON-NLS-1$ //$NON-NLS-2$ + return super.toString () ~ " (" ~ throwable.toString () ~ ")"; //$NON-NLS-1$ //$NON-NLS-2$ } /** @@ -143,12 +143,12 @@ foreach( msg; this ){ Stderr.formatln( "{}", msg ); } - if ( throwable !is null) { - Stderr.formatln ("*** Stack trace of contained error ***"); //$NON-NLS-1$ + if ( throwable !is null) { + Stderr.formatln ("*** Stack trace of contained error ***"); //$NON-NLS-1$ foreach( msg; throwable ){ Stderr.formatln( "{}", msg ); } - } + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/SWTException.d --- a/dwt/SWTException.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/SWTException.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -33,18 +33,18 @@ */ public class SWTException : TracedException { - /** - * The SWT error code, one of SWT.ERROR_*. - */ - public int code; + /** + * The SWT error code, one of SWT.ERROR_*. + */ + public int code; - /** - * The underlying throwable that caused the problem, - * or null if this information is not available. - */ - public TracedException throwable; + /** + * The underlying throwable that caused the problem, + * or null if this information is not available. + */ + public TracedException throwable; - //static final long serialVersionUID = 3257282552304842547L; + //static final long serialVersionUID = 3257282552304842547L; /** * Constructs a new instance of this class with its @@ -52,7 +52,7 @@ * unspecified value. */ public this () { - this (SWT.ERROR_UNSPECIFIED); + this (SWT.ERROR_UNSPECIFIED); } /** @@ -64,7 +64,7 @@ * @param message the detail message for the exception */ public this (char[] message) { - this (SWT.ERROR_UNSPECIFIED, message); + this (SWT.ERROR_UNSPECIFIED, message); } /** @@ -74,7 +74,7 @@ * @param code the SWT error code */ public this (int code) { - this (code, SWT.findErrorText (code)); + this (code, SWT.findErrorText (code)); } /** @@ -87,8 +87,8 @@ * @param message the detail message for the exception */ public this (int code, char[] message) { - super (message); - this.code = code; + super (message); + this.code = code; } /** @@ -104,7 +104,7 @@ * @since 3.1 */ public TracedException getCause() { - return throwable; + return throwable; } /** @@ -116,8 +116,8 @@ * @return the error message string of this SWTException object */ public char[] getMessage () { - if (throwable is null) return super.toString (); - return super.toString () ~ " (" ~ throwable.toString () ~ ")"; //$NON-NLS-1$ //$NON-NLS-2$ + if (throwable is null) return super.toString (); + return super.toString () ~ " (" ~ throwable.toString () ~ ")"; //$NON-NLS-1$ //$NON-NLS-2$ } /** @@ -134,11 +134,11 @@ Stderr.formatln( "{}", msg ); } if ( throwable !is null) { - Stderr.formatln ("*** Stack trace of contained exception ***"); //$NON-NLS-1$ + Stderr.formatln ("*** Stack trace of contained exception ***"); //$NON-NLS-1$ foreach( msg; throwable ){ Stderr.formatln( "{}", msg ); } - } + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/ACC.d --- a/dwt/accessibility/ACC.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/ACC.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -18,60 +18,60 @@ * @since 2.0 */ public class ACC { - public static const int STATE_NORMAL = 0x00000000; - public static const int STATE_SELECTED = 0x00000002; - public static const int STATE_SELECTABLE = 0x00200000; - public static const int STATE_MULTISELECTABLE = 0x1000000; - public static const int STATE_FOCUSED = 0x00000004; - public static const int STATE_FOCUSABLE = 0x00100000; - public static const int STATE_PRESSED = 0x8; - public static const int STATE_CHECKED = 0x10; - public static const int STATE_EXPANDED = 0x200; - public static const int STATE_COLLAPSED = 0x400; - public static const int STATE_HOTTRACKED = 0x80; - public static const int STATE_BUSY = 0x800; - public static const int STATE_READONLY = 0x40; - public static const int STATE_INVISIBLE = 0x8000; - public static const int STATE_OFFSCREEN = 0x10000; - public static const int STATE_SIZEABLE = 0x20000; - public static const int STATE_LINKED = 0x400000; + public static const int STATE_NORMAL = 0x00000000; + public static const int STATE_SELECTED = 0x00000002; + public static const int STATE_SELECTABLE = 0x00200000; + public static const int STATE_MULTISELECTABLE = 0x1000000; + public static const int STATE_FOCUSED = 0x00000004; + public static const int STATE_FOCUSABLE = 0x00100000; + public static const int STATE_PRESSED = 0x8; + public static const int STATE_CHECKED = 0x10; + public static const int STATE_EXPANDED = 0x200; + public static const int STATE_COLLAPSED = 0x400; + public static const int STATE_HOTTRACKED = 0x80; + public static const int STATE_BUSY = 0x800; + public static const int STATE_READONLY = 0x40; + public static const int STATE_INVISIBLE = 0x8000; + public static const int STATE_OFFSCREEN = 0x10000; + public static const int STATE_SIZEABLE = 0x20000; + public static const int STATE_LINKED = 0x400000; - public static const int ROLE_CLIENT_AREA = 0xa; - public static const int ROLE_WINDOW = 0x9; - public static const int ROLE_MENUBAR = 0x2; - public static const int ROLE_MENU = 0xb; - public static const int ROLE_MENUITEM = 0xc; - public static const int ROLE_SEPARATOR = 0x15; - public static const int ROLE_TOOLTIP = 0xd; - public static const int ROLE_SCROLLBAR = 0x3; - public static const int ROLE_DIALOG = 0x12; - public static const int ROLE_LABEL = 0x29; - public static const int ROLE_PUSHBUTTON = 0x2b; - public static const int ROLE_CHECKBUTTON = 0x2c; - public static const int ROLE_RADIOBUTTON = 0x2d; - public static const int ROLE_COMBOBOX = 0x2e; - public static const int ROLE_TEXT = 0x2a; - public static const int ROLE_TOOLBAR = 0x16; - public static const int ROLE_LIST = 0x21; - public static const int ROLE_LISTITEM = 0x22; - public static const int ROLE_TABLE = 0x18; - public static const int ROLE_TABLECELL = 0x1d; - public static const int ROLE_TABLECOLUMNHEADER = 0x19; - /** @deprecated use ROLE_TABLECOLUMNHEADER */ - public static const int ROLE_TABLECOLUMN = ROLE_TABLECOLUMNHEADER; - public static const int ROLE_TABLEROWHEADER = 0x1a; - public static const int ROLE_TREE = 0x23; - public static const int ROLE_TREEITEM = 0x24; - public static const int ROLE_TABFOLDER = 0x3c; - public static const int ROLE_TABITEM = 0x25; - public static const int ROLE_PROGRESSBAR = 0x30; - public static const int ROLE_SLIDER = 0x33; - public static const int ROLE_LINK = 0x1e; + public static const int ROLE_CLIENT_AREA = 0xa; + public static const int ROLE_WINDOW = 0x9; + public static const int ROLE_MENUBAR = 0x2; + public static const int ROLE_MENU = 0xb; + public static const int ROLE_MENUITEM = 0xc; + public static const int ROLE_SEPARATOR = 0x15; + public static const int ROLE_TOOLTIP = 0xd; + public static const int ROLE_SCROLLBAR = 0x3; + public static const int ROLE_DIALOG = 0x12; + public static const int ROLE_LABEL = 0x29; + public static const int ROLE_PUSHBUTTON = 0x2b; + public static const int ROLE_CHECKBUTTON = 0x2c; + public static const int ROLE_RADIOBUTTON = 0x2d; + public static const int ROLE_COMBOBOX = 0x2e; + public static const int ROLE_TEXT = 0x2a; + public static const int ROLE_TOOLBAR = 0x16; + public static const int ROLE_LIST = 0x21; + public static const int ROLE_LISTITEM = 0x22; + public static const int ROLE_TABLE = 0x18; + public static const int ROLE_TABLECELL = 0x1d; + public static const int ROLE_TABLECOLUMNHEADER = 0x19; + /** @deprecated use ROLE_TABLECOLUMNHEADER */ + public static const int ROLE_TABLECOLUMN = ROLE_TABLECOLUMNHEADER; + public static const int ROLE_TABLEROWHEADER = 0x1a; + public static const int ROLE_TREE = 0x23; + public static const int ROLE_TREEITEM = 0x24; + public static const int ROLE_TABFOLDER = 0x3c; + public static const int ROLE_TABITEM = 0x25; + public static const int ROLE_PROGRESSBAR = 0x30; + public static const int ROLE_SLIDER = 0x33; + public static const int ROLE_LINK = 0x1e; - public static const int CHILDID_SELF = -1; - public static const int CHILDID_NONE = -2; - public static const int CHILDID_MULTIPLE = -3; + public static const int CHILDID_SELF = -1; + public static const int CHILDID_NONE = -2; + public static const int CHILDID_MULTIPLE = -3; - public static const int TEXT_INSERT = 0; - public static const int TEXT_DELETE = 1; + public static const int TEXT_INSERT = 0; + public static const int TEXT_DELETE = 1; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/Accessible.d --- a/dwt/accessibility/Accessible.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/Accessible.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -47,346 +47,346 @@ * @since 2.0 */ public class Accessible { - AccessibleListener[] accessibleListeners; - AccessibleControlListener[] controlListeners; - AccessibleTextListener[] textListeners; - AccessibleObject accessibleObject; - Control control; + AccessibleListener[] accessibleListeners; + AccessibleControlListener[] controlListeners; + AccessibleTextListener[] textListeners; + AccessibleObject accessibleObject; + Control control; - this (Control control) { - this.control = control; - AccessibleFactory.registerAccessible (this); - control.addDisposeListener (new class () DisposeListener { - public void widgetDisposed (DisposeEvent e) { - release (); - } - }); - } + this (Control control) { + this.control = control; + AccessibleFactory.registerAccessible (this); + control.addDisposeListener (new class () DisposeListener { + public void widgetDisposed (DisposeEvent e) { + release (); + } + }); + } - /** - * Adds the listener to the collection of listeners who will - * be notified when an accessible client asks for certain strings, - * such as name, description, help, or keyboard shortcut. The - * listener is notified by sending it one of the messages defined - * in the AccessibleListener interface. - * - * @param listener the listener that should be notified when the receiver - * is asked for a name, description, help, or keyboard shortcut string - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleListener - * @see #removeAccessibleListener - */ - public void addAccessibleListener (AccessibleListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - accessibleListeners ~= listener; - } + /** + * Adds the listener to the collection of listeners who will + * be notified when an accessible client asks for certain strings, + * such as name, description, help, or keyboard shortcut. The + * listener is notified by sending it one of the messages defined + * in the AccessibleListener interface. + * + * @param listener the listener that should be notified when the receiver + * is asked for a name, description, help, or keyboard shortcut string + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleListener + * @see #removeAccessibleListener + */ + public void addAccessibleListener (AccessibleListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + accessibleListeners ~= listener; + } - /** - * Adds the listener to the collection of listeners who will - * be notified when an accessible client asks for custom control - * specific information. The listener is notified by sending it - * one of the messages defined in the AccessibleControlListener - * interface. - * - * @param listener the listener that should be notified when the receiver - * is asked for custom control specific information - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleControlListener - * @see #removeAccessibleControlListener - */ - public void addAccessibleControlListener (AccessibleControlListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - controlListeners ~= listener; - } + /** + * Adds the listener to the collection of listeners who will + * be notified when an accessible client asks for custom control + * specific information. The listener is notified by sending it + * one of the messages defined in the AccessibleControlListener + * interface. + * + * @param listener the listener that should be notified when the receiver + * is asked for custom control specific information + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleControlListener + * @see #removeAccessibleControlListener + */ + public void addAccessibleControlListener (AccessibleControlListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + controlListeners ~= listener; + } - /** - * Adds the listener to the collection of listeners who will - * be notified when an accessible client asks for custom text control - * specific information. The listener is notified by sending it - * one of the messages defined in the AccessibleTextListener - * interface. - * - * @param listener the listener that should be notified when the receiver - * is asked for custom text control specific information - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleTextListener - * @see #removeAccessibleTextListener - * - * @since 3.0 - */ - public void addAccessibleTextListener (AccessibleTextListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - textListeners ~= listener; - } + /** + * Adds the listener to the collection of listeners who will + * be notified when an accessible client asks for custom text control + * specific information. The listener is notified by sending it + * one of the messages defined in the AccessibleTextListener + * interface. + * + * @param listener the listener that should be notified when the receiver + * is asked for custom text control specific information + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleTextListener + * @see #removeAccessibleTextListener + * + * @since 3.0 + */ + public void addAccessibleTextListener (AccessibleTextListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + textListeners ~= listener; + } - /** - * Returns the control for this Accessible object. - * - * @return the receiver's control - * @since 3.0 - */ - public Control getControl() { - return control; - } + /** + * Returns the control for this Accessible object. + * + * @return the receiver's control + * @since 3.0 + */ + public Control getControl() { + return control; + } - /* checkWidget was copied from Widget, and rewritten to work in this package */ - void checkWidget () { - if (!isValidThread ()) SWT.error (SWT.ERROR_THREAD_INVALID_ACCESS); - if (control.isDisposed ()) SWT.error (SWT.ERROR_WIDGET_DISPOSED); - } + /* checkWidget was copied from Widget, and rewritten to work in this package */ + void checkWidget () { + if (!isValidThread ()) SWT.error (SWT.ERROR_THREAD_INVALID_ACCESS); + if (control.isDisposed ()) SWT.error (SWT.ERROR_WIDGET_DISPOSED); + } - AccessibleListener[] getAccessibleListeners () { - if (accessibleListeners.length is 0 ) return null; - return accessibleListeners.dup; - } + AccessibleListener[] getAccessibleListeners () { + if (accessibleListeners.length is 0 ) return null; + return accessibleListeners.dup; + } - GtkWidget* getControlHandle () { - return control.handle; - } + GtkWidget* getControlHandle () { + return control.handle; + } - AccessibleControlListener[] getControlListeners () { - if (controlListeners.length is 0) return null; - return controlListeners.dup; - } + AccessibleControlListener[] getControlListeners () { + if (controlListeners.length is 0) return null; + return controlListeners.dup; + } - AccessibleTextListener[] getTextListeners () { - if (textListeners.length is 0) return null; - return textListeners.dup; - } + AccessibleTextListener[] getTextListeners () { + if (textListeners.length is 0) return null; + return textListeners.dup; + } - /** - * Invokes platform specific functionality to allocate a new accessible object. - *

- * IMPORTANT: This method is not part of the public - * API for Accessible. 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. - *

- * - * @param control the control to get the accessible object for - * @return the platform specific accessible object - */ - public static Accessible internal_new_Accessible (Control control) { - return new Accessible (control); - } + /** + * Invokes platform specific functionality to allocate a new accessible object. + *

+ * IMPORTANT: This method is not part of the public + * API for Accessible. 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. + *

+ * + * @param control the control to get the accessible object for + * @return the platform specific accessible object + */ + public static Accessible internal_new_Accessible (Control control) { + return new Accessible (control); + } - /* isValidThread was copied from Widget, and rewritten to work in this package */ - bool isValidThread () { - return control.getDisplay ().getThread () is Thread.getThis (); - } + /* isValidThread was copied from Widget, and rewritten to work in this package */ + bool isValidThread () { + return control.getDisplay ().getThread () is Thread.getThis (); + } - void release () { - AccessibleFactory.unregisterAccessible (/*Accessible.*/this); - if (accessibleObject !is null) { - accessibleObject.release (); - accessibleObject = null; - } - accessibleListeners = null; - controlListeners = null; - textListeners = null; - } - /** - * Removes the listener from the collection of listeners who will - * be notified when an accessible client asks for custom control - * specific information. - * - * @param listener the listener that should no longer be notified when the receiver - * is asked for custom control specific information - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleControlListener - * @see #addAccessibleControlListener - */ - public void removeAccessibleControlListener (AccessibleControlListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - remove( controlListeners, listener, delegate bool(AccessibleControlListener a1, AccessibleControlListener a2 ){ return a1 is a2; }); - } + void release () { + AccessibleFactory.unregisterAccessible (/*Accessible.*/this); + if (accessibleObject !is null) { + accessibleObject.release (); + accessibleObject = null; + } + accessibleListeners = null; + controlListeners = null; + textListeners = null; + } + /** + * Removes the listener from the collection of listeners who will + * be notified when an accessible client asks for custom control + * specific information. + * + * @param listener the listener that should no longer be notified when the receiver + * is asked for custom control specific information + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleControlListener + * @see #addAccessibleControlListener + */ + public void removeAccessibleControlListener (AccessibleControlListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + remove( controlListeners, listener, delegate bool(AccessibleControlListener a1, AccessibleControlListener a2 ){ return a1 is a2; }); + } - /** - * Removes the listener from the collection of listeners who will - * be notified when an accessible client asks for certain strings, - * such as name, description, help, or keyboard shortcut. - * - * @param listener the listener that should no longer be notified when the receiver - * is asked for a name, description, help, or keyboard shortcut string - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleListener - * @see #addAccessibleListener - */ - public void removeAccessibleListener (AccessibleListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - remove( accessibleListeners, listener, delegate bool( AccessibleListener a1, AccessibleListener a2 ){ return a1 is a2; }); - } + /** + * Removes the listener from the collection of listeners who will + * be notified when an accessible client asks for certain strings, + * such as name, description, help, or keyboard shortcut. + * + * @param listener the listener that should no longer be notified when the receiver + * is asked for a name, description, help, or keyboard shortcut string + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleListener + * @see #addAccessibleListener + */ + public void removeAccessibleListener (AccessibleListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + remove( accessibleListeners, listener, delegate bool( AccessibleListener a1, AccessibleListener a2 ){ return a1 is a2; }); + } - /** - * Removes the listener from the collection of listeners who will - * be notified when an accessible client asks for custom text control - * specific information. - * - * @param listener the listener that should no longer be notified when the receiver - * is asked for custom text control specific information - * - * @exception IllegalArgumentException - * @exception SWTException - * - * @see AccessibleTextListener - * @see #addAccessibleTextListener - * - * @since 3.0 - */ - public void removeAccessibleTextListener (AccessibleTextListener listener) { - checkWidget (); - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - remove( textListeners, listener, delegate bool(AccessibleTextListener a1, AccessibleTextListener a2 ){ return a1 is a2; }); - } + /** + * Removes the listener from the collection of listeners who will + * be notified when an accessible client asks for custom text control + * specific information. + * + * @param listener the listener that should no longer be notified when the receiver + * is asked for custom text control specific information + * + * @exception IllegalArgumentException + * @exception SWTException + * + * @see AccessibleTextListener + * @see #addAccessibleTextListener + * + * @since 3.0 + */ + public void removeAccessibleTextListener (AccessibleTextListener listener) { + checkWidget (); + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + remove( textListeners, listener, delegate bool(AccessibleTextListener a1, AccessibleTextListener a2 ){ return a1 is a2; }); + } - /** - * Sends a message to accessible clients that the child selection - * within a custom container control has changed. - * - * @exception SWTException - * - * @since 3.0 - */ - public void selectionChanged () { - checkWidget (); - if (accessibleObject !is null) { - accessibleObject.selectionChanged (); - } - } + /** + * Sends a message to accessible clients that the child selection + * within a custom container control has changed. + * + * @exception SWTException + * + * @since 3.0 + */ + public void selectionChanged () { + checkWidget (); + if (accessibleObject !is null) { + accessibleObject.selectionChanged (); + } + } - /** - * Sends a message to accessible clients indicating that the focus - * has changed within a custom control. - * - * @param childID an identifier specifying a child of the control - * - * @exception SWTException - */ - public void setFocus (int childID) { - checkWidget (); - if (accessibleObject !is null) { - accessibleObject.setFocus (childID); - } - } + /** + * Sends a message to accessible clients indicating that the focus + * has changed within a custom control. + * + * @param childID an identifier specifying a child of the control + * + * @exception SWTException + */ + public void setFocus (int childID) { + checkWidget (); + if (accessibleObject !is null) { + accessibleObject.setFocus (childID); + } + } - /** - * Sends a message to accessible clients that the text - * caret has moved within a custom control. - * - * @param index the new caret index within the control - * - * @exception SWTException - * - * @since 3.0 - */ - public void textCaretMoved (int index) { - checkWidget (); - if (accessibleObject !is null) { - accessibleObject.textCaretMoved (index); - } - } + /** + * Sends a message to accessible clients that the text + * caret has moved within a custom control. + * + * @param index the new caret index within the control + * + * @exception SWTException + * + * @since 3.0 + */ + public void textCaretMoved (int index) { + checkWidget (); + if (accessibleObject !is null) { + accessibleObject.textCaretMoved (index); + } + } - /** - * Sends a message to accessible clients that the text - * within a custom control has changed. - * - * @param type the type of change, one of ACC.NOTIFY_TEXT_INSERT - * or ACC.NOTIFY_TEXT_DELETE - * @param startIndex the text index within the control where the insertion or deletion begins - * @param length the non-negative length in characters of the insertion or deletion - * - * @exception SWTException - * - * @see ACC#TEXT_INSERT - * @see ACC#TEXT_DELETE - * - * @since 3.0 - */ - public void textChanged (int type, int startIndex, int length) { - checkWidget (); - if (accessibleObject !is null) { - accessibleObject.textChanged (type, startIndex, length); - } - } + /** + * Sends a message to accessible clients that the text + * within a custom control has changed. + * + * @param type the type of change, one of ACC.NOTIFY_TEXT_INSERT + * or ACC.NOTIFY_TEXT_DELETE + * @param startIndex the text index within the control where the insertion or deletion begins + * @param length the non-negative length in characters of the insertion or deletion + * + * @exception SWTException + * + * @see ACC#TEXT_INSERT + * @see ACC#TEXT_DELETE + * + * @since 3.0 + */ + public void textChanged (int type, int startIndex, int length) { + checkWidget (); + if (accessibleObject !is null) { + accessibleObject.textChanged (type, startIndex, length); + } + } - /** - * Sends a message to accessible clients that the text - * selection has changed within a custom control. - * - * @exception SWTException - * - * @since 3.0 - */ - public void textSelectionChanged () { - checkWidget (); - if (accessibleObject !is null) { - accessibleObject.textSelectionChanged (); - } - } + /** + * Sends a message to accessible clients that the text + * selection has changed within a custom control. + * + * @exception SWTException + * + * @since 3.0 + */ + public void textSelectionChanged () { + checkWidget (); + if (accessibleObject !is null) { + accessibleObject.textSelectionChanged (); + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleAdapter.d --- a/dwt/accessibility/AccessibleAdapter.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleAdapter.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -34,97 +34,97 @@ */ public abstract class AccessibleAdapter : AccessibleListener { - /** - * Sent when an accessibility client requests the name - * of the control, or the name of a child of the control. - * The default behavior is to do nothing. - *

- * Return the name of the control or specified child in the - * result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a name, and returning null tells the client - * to use the platform name. - *

- * - * @param e an event object containing the following fields: - */ - public void getName(AccessibleEvent e) { - } + /** + * Sent when an accessibility client requests the name + * of the control, or the name of a child of the control. + * The default behavior is to do nothing. + *

+ * Return the name of the control or specified child in the + * result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a name, and returning null tells the client + * to use the platform name. + *

+ * + * @param e an event object containing the following fields: + */ + public void getName(AccessibleEvent e) { + } - /** - * Sent when an accessibility client requests the help string - * of the control, or the help string of a child of the control. - * The default behavior is to do nothing. - *

- * The information in this property should be similar to the help - * provided by toolTipText. It describes what the control or child - * does or how to use it, as opposed to getDescription, which - * describes appearance. - *

- * Return the help string of the control or specified child in - * the result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a help string, and returning null tells the - * client to use the platform help string. - *

- * - * @param e an event object containing the following fields: - */ - public void getHelp(AccessibleEvent e) { - } + /** + * Sent when an accessibility client requests the help string + * of the control, or the help string of a child of the control. + * The default behavior is to do nothing. + *

+ * The information in this property should be similar to the help + * provided by toolTipText. It describes what the control or child + * does or how to use it, as opposed to getDescription, which + * describes appearance. + *

+ * Return the help string of the control or specified child in + * the result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a help string, and returning null tells the + * client to use the platform help string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getHelp(AccessibleEvent e) { + } - /** - * Sent when an accessibility client requests the keyboard shortcut - * of the control, or the keyboard shortcut of a child of the control. - * The default behavior is to do nothing. - *

- * A keyboard shortcut can either be a mnemonic, or an accelerator. - * As a general rule, if the control or child can receive keyboard focus, - * then you should expose its mnemonic, and if it cannot receive keyboard - * focus, then you should expose its accelerator. - *

- * Return the keyboard shortcut string of the control or specified child - * in the result field of the event object. Returning an - * empty string tells the client that the control or child does not - * have a keyboard shortcut string, and returning null tells the client - * to use the platform keyboard shortcut string. - *

- * - * @param e an event object containing the following fields: - */ - public void getKeyboardShortcut(AccessibleEvent e) { - } + /** + * Sent when an accessibility client requests the keyboard shortcut + * of the control, or the keyboard shortcut of a child of the control. + * The default behavior is to do nothing. + *

+ * A keyboard shortcut can either be a mnemonic, or an accelerator. + * As a general rule, if the control or child can receive keyboard focus, + * then you should expose its mnemonic, and if it cannot receive keyboard + * focus, then you should expose its accelerator. + *

+ * Return the keyboard shortcut string of the control or specified child + * in the result field of the event object. Returning an + * empty string tells the client that the control or child does not + * have a keyboard shortcut string, and returning null tells the client + * to use the platform keyboard shortcut string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getKeyboardShortcut(AccessibleEvent e) { + } - /** - * Sent when an accessibility client requests a description - * of the control, or a description of a child of the control. - * The default behavior is to do nothing. - *

- * This is a textual description of the control or child's visual - * appearance, which is typically only necessary if it cannot be - * determined from other properties such as role. - *

- * Return the description of the control or specified child in - * the result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a description, and returning null tells the - * client to use the platform description. - *

- * - * @param e an event object containing the following fields: - */ - public void getDescription(AccessibleEvent e) { - } + /** + * Sent when an accessibility client requests a description + * of the control, or a description of a child of the control. + * The default behavior is to do nothing. + *

+ * This is a textual description of the control or child's visual + * appearance, which is typically only necessary if it cannot be + * determined from other properties such as role. + *

+ * Return the description of the control or specified child in + * the result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a description, and returning null tells the + * client to use the platform description. + *

+ * + * @param e an event object containing the following fields: + */ + public void getDescription(AccessibleEvent e) { + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleControlAdapter.d --- a/dwt/accessibility/AccessibleControlAdapter.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleControlAdapter.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -40,214 +40,214 @@ */ public abstract class AccessibleControlAdapter : AccessibleControlListener { - /** - * Sent when an accessibility client requests the identifier - * of the control child at the specified display coordinates. - * The default behavior is to do nothing. - *

- * Return the identifier of the child at display point (x, y) - * in the childID field of the event object. - * Return CHILDID_SELF if point (x, y) is in the control itself - * and not in any child. Return CHILDID_NONE if point (x, y) - * is not contained in either the control or any of its children. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildAtPoint(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the identifier + * of the control child at the specified display coordinates. + * The default behavior is to do nothing. + *

+ * Return the identifier of the child at display point (x, y) + * in the childID field of the event object. + * Return CHILDID_SELF if point (x, y) is in the control itself + * and not in any child. Return CHILDID_NONE if point (x, y) + * is not contained in either the control or any of its children. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildAtPoint(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the location - * of the control, or the location of a child of the control. - * The default behavior is to do nothing. - *

- * Return a rectangle describing the location of the specified - * control or child in the x, y, width, and height - * fields of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getLocation(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the location + * of the control, or the location of a child of the control. + * The default behavior is to do nothing. + *

+ * Return a rectangle describing the location of the specified + * control or child in the x, y, width, and height + * fields of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getLocation(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the accessible object - * for a child of the control. - * The default behavior is to do nothing. - *

- * Return an Accessible for the specified control or - * child in the accessible field of the event object. - * Return null if the specified child does not have its own - * Accessible. - *

- * - * @param e an event object containing the following fields: - */ - public void getChild(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the accessible object + * for a child of the control. + * The default behavior is to do nothing. + *

+ * Return an Accessible for the specified control or + * child in the accessible field of the event object. + * Return null if the specified child does not have its own + * Accessible. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChild(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the number of - * children in the control. - * The default behavior is to do nothing. - *

- * Return the number of child items in the detail - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildCount(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the number of + * children in the control. + * The default behavior is to do nothing. + *

+ * Return the number of child items in the detail + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildCount(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the default action - * of the control, or the default action of a child of the control. - * The default behavior is to do nothing. - *

- * This string is typically a verb describing what the user does to it. - * For example, a Push Button's default action is "Press", a Check Button's - * is "Check" or "UnCheck", and List items have the default action "Double Click". - *

- * Return a string describing the default action of the specified - * control or child in the result field of the event object. - * Returning null tells the client to use the platform default action string. - *

- * - * @param e an event object containing the following fields: - */ - public void getDefaultAction(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the default action + * of the control, or the default action of a child of the control. + * The default behavior is to do nothing. + *

+ * This string is typically a verb describing what the user does to it. + * For example, a Push Button's default action is "Press", a Check Button's + * is "Check" or "UnCheck", and List items have the default action "Double Click". + *

+ * Return a string describing the default action of the specified + * control or child in the result field of the event object. + * Returning null tells the client to use the platform default action string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getDefaultAction(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the identity of - * the child or control that has keyboard focus. - * The default behavior is to do nothing. - *

- * Return the identifier of the child that has focus in the - * childID field of the event object. - * Return CHILDID_SELF if the control itself has keyboard focus. - * Return CHILDID_NONE if neither the control nor any of its children has focus. - *

- * - * @param e an event object containing the following fields: - */ - public void getFocus(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the identity of + * the child or control that has keyboard focus. + * The default behavior is to do nothing. + *

+ * Return the identifier of the child that has focus in the + * childID field of the event object. + * Return CHILDID_SELF if the control itself has keyboard focus. + * Return CHILDID_NONE if neither the control nor any of its children has focus. + *

+ * + * @param e an event object containing the following fields: + */ + public void getFocus(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the role - * of the control, or the role of a child of the control. - * The default behavior is to do nothing. - *

- * Return a role constant (constant defined in ACC beginning with ROLE_) - * that describes the role of the specified control or child in the - * detail field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getRole(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the role + * of the control, or the role of a child of the control. + * The default behavior is to do nothing. + *

+ * Return a role constant (constant defined in ACC beginning with ROLE_) + * that describes the role of the specified control or child in the + * detail field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getRole(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the identity of - * the child or control that is currently selected. - * The default behavior is to do nothing. - *

- * Return the identifier of the selected child in the - * childID field of the event object. - * Return CHILDID_SELF if the control itself is selected. - * Return CHILDID_MULTIPLE if multiple children are selected, and return an array of childIDs in the children field. - * Return CHILDID_NONE if neither the control nor any of its children are selected. - *

- * - * @param e an event object containing the following fields: - */ - public void getSelection(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the identity of + * the child or control that is currently selected. + * The default behavior is to do nothing. + *

+ * Return the identifier of the selected child in the + * childID field of the event object. + * Return CHILDID_SELF if the control itself is selected. + * Return CHILDID_MULTIPLE if multiple children are selected, and return an array of childIDs in the children field. + * Return CHILDID_NONE if neither the control nor any of its children are selected. + *

+ * + * @param e an event object containing the following fields: + */ + public void getSelection(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the state - * of the control, or the state of a child of the control. - * The default behavior is to do nothing. - *

- * Return a state mask (mask bit constants defined in ACC beginning with STATE_) - * that describes the current state of the specified control or child in the - * detail field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getState(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the state + * of the control, or the state of a child of the control. + * The default behavior is to do nothing. + *

+ * Return a state mask (mask bit constants defined in ACC beginning with STATE_) + * that describes the current state of the specified control or child in the + * detail field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getState(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the value - * of the control, or the value of a child of the control. - * The default behavior is to do nothing. - *

- * Many controls do not return a value. Examples of controls - * that do are: Combo returns the text string, Text returns - * its contents, ProgressBar returns a string representing a - * percentage, and Tree items return a string representing - * their level in the tree. - *

- * Return a string describing the value of the specified control - * or child in the result field of the event object. - * Returning null tells the client to use the platform value string. - *

- * - * @param e an event object containing the following fields: - */ - public void getValue(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the value + * of the control, or the value of a child of the control. + * The default behavior is to do nothing. + *

+ * Many controls do not return a value. Examples of controls + * that do are: Combo returns the text string, Text returns + * its contents, ProgressBar returns a string representing a + * percentage, and Tree items return a string representing + * their level in the tree. + *

+ * Return a string describing the value of the specified control + * or child in the result field of the event object. + * Returning null tells the client to use the platform value string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getValue(AccessibleControlEvent e) { + } - /** - * Sent when an accessibility client requests the children of the control. - * The default behavior is to do nothing. - *

- * Return the children as an array of childIDs in the children - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildren(AccessibleControlEvent e) { - } + /** + * Sent when an accessibility client requests the children of the control. + * The default behavior is to do nothing. + *

+ * Return the children as an array of childIDs in the children + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildren(AccessibleControlEvent e) { + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleControlEvent.d --- a/dwt/accessibility/AccessibleControlEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleControlEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -32,15 +32,15 @@ * @since 2.0 */ public class AccessibleControlEvent : SWTEventObject { - public int childID; // IN/OUT - public Accessible accessible; // OUT - public int x, y; // IN/OUT - public int width, height; // OUT - public int detail; // IN/OUT - public char[] result; // OUT - public Object children[]; // [OUT] + public int childID; // IN/OUT + public Accessible accessible; // OUT + public int x, y; // IN/OUT + public int width, height; // OUT + public int detail; // IN/OUT + public char[] result; // OUT + public Object children[]; // [OUT] - //static final long serialVersionUID = 3257281444169529141L; + //static final long serialVersionUID = 3257281444169529141L; /** * Constructs a new instance of this class. @@ -48,7 +48,7 @@ * @param source the object that fired the event */ public this(Object source) { - super(source); + super(source); } /** @@ -58,7 +58,7 @@ * @return a string representation of the event */ public char[] toString () { - return Format( "AccessibleControlEvent {childID={} accessible={} x={} y={} width={} heigth={} detail={} result={}", + return Format( "AccessibleControlEvent {childID={} accessible={} x={} y={} width={} heigth={} detail={} result={}", childID, accessible, x, y, width, height, detail, result); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleControlListener.d --- a/dwt/accessibility/AccessibleControlListener.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleControlListener.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -42,192 +42,192 @@ */ public interface AccessibleControlListener : SWTEventListener { - /** - * Sent when an accessibility client requests the identifier - * of the control child at the specified display coordinates. - *

- * Return the identifier of the child at display point (x, y) - * in the childID field of the event object. - * Return CHILDID_SELF if point (x, y) is in the control itself - * and not in any child. Return CHILDID_NONE if point (x, y) - * is not contained in either the control or any of its children. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildAtPoint(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the identifier + * of the control child at the specified display coordinates. + *

+ * Return the identifier of the child at display point (x, y) + * in the childID field of the event object. + * Return CHILDID_SELF if point (x, y) is in the control itself + * and not in any child. Return CHILDID_NONE if point (x, y) + * is not contained in either the control or any of its children. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildAtPoint(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the location - * of the control, or the location of a child of the control. - *

- * Return a rectangle describing the location of the specified - * control or child in the x, y, width, and height - * fields of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getLocation(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the location + * of the control, or the location of a child of the control. + *

+ * Return a rectangle describing the location of the specified + * control or child in the x, y, width, and height + * fields of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getLocation(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the accessible object - * for a child of the control. - *

- * Return an Accessible for the specified control or - * child in the accessible field of the event object. - * Return null if the specified child does not have its own - * Accessible. - *

- * - * @param e an event object containing the following fields: - */ - public void getChild(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the accessible object + * for a child of the control. + *

+ * Return an Accessible for the specified control or + * child in the accessible field of the event object. + * Return null if the specified child does not have its own + * Accessible. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChild(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the number of - * children in the control. - *

- * Return the number of child items in the detail - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildCount(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the number of + * children in the control. + *

+ * Return the number of child items in the detail + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildCount(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the default action - * of the control, or the default action of a child of the control. - *

- * This string is typically a verb describing what the user does to it. - * For example, a Push Button's default action is "Press", a Check Button's - * is "Check" or "UnCheck", and List items have the default action "Double Click". - *

- * Return a string describing the default action of the specified - * control or child in the result field of the event object. - * Returning null tells the client to use the platform default action string. - *

- * - * @param e an event object containing the following fields: - */ - public void getDefaultAction(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the default action + * of the control, or the default action of a child of the control. + *

+ * This string is typically a verb describing what the user does to it. + * For example, a Push Button's default action is "Press", a Check Button's + * is "Check" or "UnCheck", and List items have the default action "Double Click". + *

+ * Return a string describing the default action of the specified + * control or child in the result field of the event object. + * Returning null tells the client to use the platform default action string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getDefaultAction(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the identity of - * the child or control that has keyboard focus. - *

- * Return the identifier of the child that has focus in the - * childID field of the event object. - * Return CHILDID_SELF if the control itself has keyboard focus. - * Return CHILDID_NONE if neither the control nor any of its children has focus. - *

- * - * @param e an event object containing the following fields: - */ - public void getFocus(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the identity of + * the child or control that has keyboard focus. + *

+ * Return the identifier of the child that has focus in the + * childID field of the event object. + * Return CHILDID_SELF if the control itself has keyboard focus. + * Return CHILDID_NONE if neither the control nor any of its children has focus. + *

+ * + * @param e an event object containing the following fields: + */ + public void getFocus(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the role - * of the control, or the role of a child of the control. - *

- * Return a role constant (constant defined in ACC beginning with ROLE_) - * that describes the role of the specified control or child in the - * detail field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getRole(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the role + * of the control, or the role of a child of the control. + *

+ * Return a role constant (constant defined in ACC beginning with ROLE_) + * that describes the role of the specified control or child in the + * detail field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getRole(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the identity of - * the child or control that is currently selected. - *

- * Return the identifier of the selected child in the - * childID field of the event object. - * Return CHILDID_SELF if the control itself is selected. - * Return CHILDID_MULTIPLE if multiple children are selected, and return an array of childIDs in the children field. - * Return CHILDID_NONE if neither the control nor any of its children are selected. - *

- * - * @param e an event object containing the following fields: - */ - public void getSelection(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the identity of + * the child or control that is currently selected. + *

+ * Return the identifier of the selected child in the + * childID field of the event object. + * Return CHILDID_SELF if the control itself is selected. + * Return CHILDID_MULTIPLE if multiple children are selected, and return an array of childIDs in the children field. + * Return CHILDID_NONE if neither the control nor any of its children are selected. + *

+ * + * @param e an event object containing the following fields: + */ + public void getSelection(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the state - * of the control, or the state of a child of the control. - *

- * Return a state mask (mask bit constants defined in ACC beginning with STATE_) - * that describes the current state of the specified control or child in the - * detail field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getState(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the state + * of the control, or the state of a child of the control. + *

+ * Return a state mask (mask bit constants defined in ACC beginning with STATE_) + * that describes the current state of the specified control or child in the + * detail field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getState(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the value - * of the control, or the value of a child of the control. - *

- * Many controls do not return a value. Examples of controls - * that do are: Combo returns the text string, Text returns - * its contents, ProgressBar returns a string representing a - * percentage, and Tree items return a string representing - * their level in the tree. - *

- * Return a string describing the value of the specified control - * or child in the result field of the event object. - * Returning null tells the client to use the platform value string. - *

- * - * @param e an event object containing the following fields: - */ - public void getValue(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the value + * of the control, or the value of a child of the control. + *

+ * Many controls do not return a value. Examples of controls + * that do are: Combo returns the text string, Text returns + * its contents, ProgressBar returns a string representing a + * percentage, and Tree items return a string representing + * their level in the tree. + *

+ * Return a string describing the value of the specified control + * or child in the result field of the event object. + * Returning null tells the client to use the platform value string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getValue(AccessibleControlEvent e); - /** - * Sent when an accessibility client requests the children of the control. - *

- * Return the children as an array of childIDs in the children - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getChildren(AccessibleControlEvent e); + /** + * Sent when an accessibility client requests the children of the control. + *

+ * Return the children as an array of childIDs in the children + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getChildren(AccessibleControlEvent e); } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleEvent.d --- a/dwt/accessibility/AccessibleEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -29,23 +29,23 @@ * @since 2.0 */ public class AccessibleEvent : SWTEventObject { - /** - * The value of this field is set by an accessibility client - * before the accessible listener method is called. - * ChildID can be CHILDID_SELF, representing the control itself, - * or a 0-based integer representing a specific child of the control. - */ - public int childID; + /** + * The value of this field is set by an accessibility client + * before the accessible listener method is called. + * ChildID can be CHILDID_SELF, representing the control itself, + * or a 0-based integer representing a specific child of the control. + */ + public int childID; - /** - * The value of this field must be set in the accessible listener - * method before returning. - * What to set it to depends on the listener method called, and - * the childID specified by the client. - */ - public char[] result; + /** + * The value of this field must be set in the accessible listener + * method before returning. + * What to set it to depends on the listener method called, and + * the childID specified by the client. + */ + public char[] result; - //static final long serialVersionUID = 3257567304224026934L; + //static final long serialVersionUID = 3257567304224026934L; /** * Constructs a new instance of this class. @@ -53,7 +53,7 @@ * @param source the object that fired the event */ public this(Object source) { - super(source); + super(source); } /** @@ -63,6 +63,6 @@ * @return a string representation of the event */ public char[] toString () { - return Format( "AccessibleEvent {childID={} result={}}", childID, result ); + return Format( "AccessibleEvent {childID={} result={}}", childID, result ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleFactory.d --- a/dwt/accessibility/AccessibleFactory.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleFactory.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -25,42 +25,42 @@ import tango.io.Stdout; class AccessibleFactory { - AtkObjectFactory * handle; - uint objectParentType; - char* widgetTypeName; + AtkObjectFactory * handle; + uint objectParentType; + char* widgetTypeName; - //Callback atkObjectFactoryCB_create_accessible; - //Callback gTypeInfo_base_init_factory; - Accessible[GtkWidget*] accessibles; + //Callback atkObjectFactoryCB_create_accessible; + //Callback gTypeInfo_base_init_factory; + Accessible[GtkWidget*] accessibles; - static long[char[]] Types; - static AccessibleFactory[long] Factories; + static long[char[]] Types; + static AccessibleFactory[long] Factories; static uint DefaultParentType; //$NON-NLS-1$ - static const char[] FACTORY_PARENTTYPENAME = "AtkObjectFactory"; - static const char[] SWT_TYPE_PREFIX = "SWT"; - static const char[] CHILD_TYPENAME = "Child"; - static const char[] FACTORY_TYPENAME = "SWTFactory"; - static const int[] actionRoles = [ - ACC.ROLE_CHECKBUTTON, ACC.ROLE_COMBOBOX, ACC.ROLE_LINK, - ACC.ROLE_MENUITEM, ACC.ROLE_PUSHBUTTON, ACC.ROLE_RADIOBUTTON, - ]; - static const int[] hypertextRoles = [ACC.ROLE_LINK]; - static const int[] selectionRoles = [ - ACC.ROLE_LIST, ACC.ROLE_TABFOLDER, ACC.ROLE_TABLE, ACC.ROLE_TREE, - ]; - static const int[] textRoles = [ - ACC.ROLE_COMBOBOX, ACC.ROLE_LINK, ACC.ROLE_LABEL, ACC.ROLE_TEXT, - ]; + static const char[] FACTORY_PARENTTYPENAME = "AtkObjectFactory"; + static const char[] SWT_TYPE_PREFIX = "SWT"; + static const char[] CHILD_TYPENAME = "Child"; + static const char[] FACTORY_TYPENAME = "SWTFactory"; + static const int[] actionRoles = [ + ACC.ROLE_CHECKBUTTON, ACC.ROLE_COMBOBOX, ACC.ROLE_LINK, + ACC.ROLE_MENUITEM, ACC.ROLE_PUSHBUTTON, ACC.ROLE_RADIOBUTTON, + ]; + static const int[] hypertextRoles = [ACC.ROLE_LINK]; + static const int[] selectionRoles = [ + ACC.ROLE_LIST, ACC.ROLE_TABFOLDER, ACC.ROLE_TABLE, ACC.ROLE_TREE, + ]; + static const int[] textRoles = [ + ACC.ROLE_COMBOBOX, ACC.ROLE_LINK, ACC.ROLE_LABEL, ACC.ROLE_TEXT, + ]; - /* AT callbacks*/ - /* interface definitions */ - static GTypeInfo* ObjectIfaceDefinition; - static GInterfaceInfo* ActionIfaceDefinition; - static GInterfaceInfo* ComponentIfaceDefinition; - static GInterfaceInfo* HypertextIfaceDefinition; - static GInterfaceInfo* SelectionIfaceDefinition; - static GInterfaceInfo* TextIfaceDefinition; + /* AT callbacks*/ + /* interface definitions */ + static GTypeInfo* ObjectIfaceDefinition; + static GInterfaceInfo* ActionIfaceDefinition; + static GInterfaceInfo* ComponentIfaceDefinition; + static GInterfaceInfo* HypertextIfaceDefinition; + static GInterfaceInfo* SelectionIfaceDefinition; + static GInterfaceInfo* TextIfaceDefinition; static synchronized void static_this(){ DefaultParentType = OS.g_type_from_name ("GtkAccessible"); //$NON-NLS-1$ @@ -81,33 +81,33 @@ TextIfaceDefinition.interface_init = &AccessibleFactory.initTextIfaceCB; } - private this (int /*long*/ widgetType) { - widgetTypeName = OS.g_type_name (widgetType); - char[] factoryName = FACTORY_TYPENAME ~ fromUtf8z( widgetTypeName ) ~ \0; - if (OS.g_type_from_name (factoryName.ptr) is 0) { - /* register the factory */ - auto registry = ATK.atk_get_default_registry (); - auto previousFactory = ATK.atk_registry_get_factory (registry, widgetType); - objectParentType = ATK.atk_object_factory_get_accessible_type (previousFactory); - if (objectParentType is 0) objectParentType = DefaultParentType; - auto factoryParentType = OS.g_type_from_name (FACTORY_PARENTTYPENAME.ptr); + private this (int /*long*/ widgetType) { + widgetTypeName = OS.g_type_name (widgetType); + char[] factoryName = FACTORY_TYPENAME ~ fromUtf8z( widgetTypeName ) ~ \0; + if (OS.g_type_from_name (factoryName.ptr) is 0) { + /* register the factory */ + auto registry = ATK.atk_get_default_registry (); + auto previousFactory = ATK.atk_registry_get_factory (registry, widgetType); + objectParentType = ATK.atk_object_factory_get_accessible_type (previousFactory); + if (objectParentType is 0) objectParentType = DefaultParentType; + auto factoryParentType = OS.g_type_from_name (FACTORY_PARENTTYPENAME.ptr); auto typeInfo = cast(GTypeInfo*) OS.g_malloc (GTypeInfo.sizeof); typeInfo.base_init = &gTypeInfo_base_init_factory; - typeInfo.class_size = AtkObjectFactoryClass.sizeof; - typeInfo.instance_size = AtkObjectFactory.sizeof; - auto swtFactoryType = OS.g_type_register_static (factoryParentType, factoryName.ptr, typeInfo, 0); - ATK.atk_registry_set_factory_type (registry, widgetType, swtFactoryType); - handle = ATK.atk_registry_get_factory (registry, widgetType); - } - } + typeInfo.class_size = AtkObjectFactoryClass.sizeof; + typeInfo.instance_size = AtkObjectFactory.sizeof; + auto swtFactoryType = OS.g_type_register_static (factoryParentType, factoryName.ptr, typeInfo, 0); + ATK.atk_registry_set_factory_type (registry, widgetType, swtFactoryType); + handle = ATK.atk_registry_get_factory (registry, widgetType); + } + } - void addAccessible (Accessible accessible) { - auto controlHandle = accessible.getControlHandle (); - accessibles[controlHandle] = accessible; - ATK.atk_object_factory_create_accessible (handle, cast(GObject*)controlHandle); - } + void addAccessible (Accessible accessible) { + auto controlHandle = accessible.getControlHandle (); + accessibles[controlHandle] = accessible; + ATK.atk_object_factory_create_accessible (handle, cast(GObject*)controlHandle); + } - private static extern(C) AtkObject* atkObjectFactory_create_accessible (GObject* widget) { + private static extern(C) AtkObject* atkObjectFactory_create_accessible (GObject* widget) { auto widgetType = OS.G_OBJECT_TYPE ( cast(GTypeInstance*)widget); if( auto factory = widgetType in Factories ){ with( *factory ){ @@ -135,167 +135,167 @@ else{ Stdout.formatln( "AccessibleFactory.atkObjectFactoryCB_create_accessible cannot find factory instance" ); } - } + } - static int /*long*/ getChildType (Accessible accessible, int childIndex) { - return getType (CHILD_TYPENAME, accessible, DefaultParentType, childIndex); - } + static int /*long*/ getChildType (Accessible accessible, int childIndex) { + return getType (CHILD_TYPENAME, accessible, DefaultParentType, childIndex); + } - static int /*long*/ getDefaultParentType () { - return DefaultParentType; - } + static int /*long*/ getDefaultParentType () { + return DefaultParentType; + } - static int /*long*/ getType (char[] widgetTypeName, Accessible accessible, int /*long*/ parentType, int childId) { - AccessibleControlEvent event = new AccessibleControlEvent (accessible); - event.childID = childId; - AccessibleControlListener[] listeners = accessible.getControlListeners (); - for (int i = 0; i < listeners.length; i++) { - listeners [i].getRole (event); - } - bool action = false, hypertext = false, selection = false, text = false; - if (event.detail !is 0) { /* a role was specified */ - for (int i = 0; i < actionRoles.length; i++) { - if (event.detail is actionRoles [i]) { - action = true; - break; - } - } - for (int i = 0; i < hypertextRoles.length; i++) { - if (event.detail is hypertextRoles [i]) { - hypertext = true; - break; - } - } - for (int i = 0; i < selectionRoles.length; i++) { - if (event.detail is selectionRoles [i]) { - selection = true; - break; - } - } - for (int i = 0; i < textRoles.length; i++) { - if (event.detail is textRoles [i]) { - text = true; - break; - } - } - } else { - action = hypertext = selection = text = true; - } - char[] swtTypeName = SWT_TYPE_PREFIX.dup; - swtTypeName ~= widgetTypeName; - if (action) swtTypeName ~= "Action"; //$NON-NLS-1$ - if (hypertext) swtTypeName ~= "Hypertext"; //$NON-NLS-1$ - if (selection) swtTypeName ~= "Selection"; //$NON-NLS-1$ - if (text) swtTypeName ~= "Text"; //$NON-NLS-1$ + static int /*long*/ getType (char[] widgetTypeName, Accessible accessible, int /*long*/ parentType, int childId) { + AccessibleControlEvent event = new AccessibleControlEvent (accessible); + event.childID = childId; + AccessibleControlListener[] listeners = accessible.getControlListeners (); + for (int i = 0; i < listeners.length; i++) { + listeners [i].getRole (event); + } + bool action = false, hypertext = false, selection = false, text = false; + if (event.detail !is 0) { /* a role was specified */ + for (int i = 0; i < actionRoles.length; i++) { + if (event.detail is actionRoles [i]) { + action = true; + break; + } + } + for (int i = 0; i < hypertextRoles.length; i++) { + if (event.detail is hypertextRoles [i]) { + hypertext = true; + break; + } + } + for (int i = 0; i < selectionRoles.length; i++) { + if (event.detail is selectionRoles [i]) { + selection = true; + break; + } + } + for (int i = 0; i < textRoles.length; i++) { + if (event.detail is textRoles [i]) { + text = true; + break; + } + } + } else { + action = hypertext = selection = text = true; + } + char[] swtTypeName = SWT_TYPE_PREFIX.dup; + swtTypeName ~= widgetTypeName; + if (action) swtTypeName ~= "Action"; //$NON-NLS-1$ + if (hypertext) swtTypeName ~= "Hypertext"; //$NON-NLS-1$ + if (selection) swtTypeName ~= "Selection"; //$NON-NLS-1$ + if (text) swtTypeName ~= "Text"; //$NON-NLS-1$ - int /*long*/ type = 0; + int /*long*/ type = 0; if (swtTypeName in Types ) { - type = Types[swtTypeName]; - } else { - /* define the type */ + type = Types[swtTypeName]; + } else { + /* define the type */ GTypeQuery* query = new GTypeQuery (); - OS.g_type_query (parentType, query); + OS.g_type_query (parentType, query); GTypeInfo* typeInfo = new GTypeInfo (); - typeInfo.base_init = &gTypeInfo_base_init_type; - typeInfo.class_size = query.class_size; - typeInfo.instance_size = query.instance_size; - ObjectIfaceDefinition = typeInfo; + typeInfo.base_init = &gTypeInfo_base_init_type; + typeInfo.class_size = query.class_size; + typeInfo.instance_size = query.instance_size; + ObjectIfaceDefinition = typeInfo; - type = OS.g_type_register_static (parentType, toStringz( swtTypeName ), ObjectIfaceDefinition, 0); - OS.g_type_add_interface_static (type, AccessibleObject.ATK_COMPONENT_TYPE, ComponentIfaceDefinition); - if (action) OS.g_type_add_interface_static (type, AccessibleObject.ATK_ACTION_TYPE, ActionIfaceDefinition); - if (hypertext) OS.g_type_add_interface_static (type, AccessibleObject.ATK_HYPERTEXT_TYPE, HypertextIfaceDefinition); - if (selection) OS.g_type_add_interface_static (type, AccessibleObject.ATK_SELECTION_TYPE, SelectionIfaceDefinition); - if (text) OS.g_type_add_interface_static (type, AccessibleObject.ATK_TEXT_TYPE, TextIfaceDefinition); - Types[swtTypeName] = type; - } - return type; - } + type = OS.g_type_register_static (parentType, toStringz( swtTypeName ), ObjectIfaceDefinition, 0); + OS.g_type_add_interface_static (type, AccessibleObject.ATK_COMPONENT_TYPE, ComponentIfaceDefinition); + if (action) OS.g_type_add_interface_static (type, AccessibleObject.ATK_ACTION_TYPE, ActionIfaceDefinition); + if (hypertext) OS.g_type_add_interface_static (type, AccessibleObject.ATK_HYPERTEXT_TYPE, HypertextIfaceDefinition); + if (selection) OS.g_type_add_interface_static (type, AccessibleObject.ATK_SELECTION_TYPE, SelectionIfaceDefinition); + if (text) OS.g_type_add_interface_static (type, AccessibleObject.ATK_TEXT_TYPE, TextIfaceDefinition); + Types[swtTypeName] = type; + } + return type; + } - private static extern(C) void gTypeInfo_base_init_factory (void* klass) { - auto atkObjectFactoryClass = ATK.ATK_OBJECT_FACTORY_CLASS (klass); - atkObjectFactoryClass.create_accessible = &atkObjectFactory_create_accessible; - } + private static extern(C) void gTypeInfo_base_init_factory (void* klass) { + auto atkObjectFactoryClass = ATK.ATK_OBJECT_FACTORY_CLASS (klass); + atkObjectFactoryClass.create_accessible = &atkObjectFactory_create_accessible; + } - private static extern(C) void gTypeInfo_base_init_type (void* klass) { - auto objectClass = cast(AtkObjectClass*)klass; + private static extern(C) void gTypeInfo_base_init_type (void* klass) { + auto objectClass = cast(AtkObjectClass*)klass; objectClass.get_name = &AccessibleObject.atkObject_get_name; - objectClass.get_description = &AccessibleObject.atkObject_get_description; - objectClass.get_n_children = &AccessibleObject.atkObject_get_n_children; - objectClass.get_role = &AccessibleObject.atkObject_get_role; - objectClass.get_parent = &AccessibleObject.atkObject_get_parent; - objectClass.ref_state_set = &AccessibleObject.atkObject_ref_state_set; - objectClass.get_index_in_parent = &AccessibleObject.atkObject_get_index_in_parent; - objectClass.ref_child = &AccessibleObject.atkObject_ref_child; + objectClass.get_description = &AccessibleObject.atkObject_get_description; + objectClass.get_n_children = &AccessibleObject.atkObject_get_n_children; + objectClass.get_role = &AccessibleObject.atkObject_get_role; + objectClass.get_parent = &AccessibleObject.atkObject_get_parent; + objectClass.ref_state_set = &AccessibleObject.atkObject_ref_state_set; + objectClass.get_index_in_parent = &AccessibleObject.atkObject_get_index_in_parent; + objectClass.ref_child = &AccessibleObject.atkObject_ref_child; GObjectClass* gObjectClass = OS.G_OBJECT_CLASS ( cast(GTypeClass*)klass); - gObjectClass.finalize = &AccessibleObject.gObjectClass_finalize; - } + gObjectClass.finalize = &AccessibleObject.gObjectClass_finalize; + } - private static extern(C) void initActionIfaceCB ( void* g_iface, void* iface_data ) { + private static extern(C) void initActionIfaceCB ( void* g_iface, void* iface_data ) { auto iface = cast(AtkActionIface*)g_iface; - iface.get_keybinding = &AccessibleObject.atkAction_get_keybinding; - iface.get_name = &AccessibleObject.atkAction_get_name; - } + iface.get_keybinding = &AccessibleObject.atkAction_get_keybinding; + iface.get_name = &AccessibleObject.atkAction_get_name; + } - private static extern(C) void initComponentIfaceCB ( void* g_iface, void* iface_data ) { + private static extern(C) void initComponentIfaceCB ( void* g_iface, void* iface_data ) { auto iface = cast(AtkComponentIface*)g_iface; - iface.get_extents = &AccessibleObject.atkComponent_get_extents; - iface.get_position = &AccessibleObject.atkComponent_get_position; - iface.get_size = &AccessibleObject.atkComponent_get_size; - iface.ref_accessible_at_point = &AccessibleObject.atkComponent_ref_accessible_at_point; - } + iface.get_extents = &AccessibleObject.atkComponent_get_extents; + iface.get_position = &AccessibleObject.atkComponent_get_position; + iface.get_size = &AccessibleObject.atkComponent_get_size; + iface.ref_accessible_at_point = &AccessibleObject.atkComponent_ref_accessible_at_point; + } - private static extern(C) void initHypertextIfaceCB ( void* g_iface, void* iface_data ) { + private static extern(C) void initHypertextIfaceCB ( void* g_iface, void* iface_data ) { auto iface = cast(AtkHypertextIface*)g_iface; - iface.get_link = &AccessibleObject.atkHypertext_get_link; - iface.get_link_index = &AccessibleObject.atkHypertext_get_link_index; - iface.get_n_links = &AccessibleObject.atkHypertext_get_n_links; - } + iface.get_link = &AccessibleObject.atkHypertext_get_link; + iface.get_link_index = &AccessibleObject.atkHypertext_get_link_index; + iface.get_n_links = &AccessibleObject.atkHypertext_get_n_links; + } - private static extern(C) void initSelectionIfaceCB ( void* g_iface, void* iface_data ) { + private static extern(C) void initSelectionIfaceCB ( void* g_iface, void* iface_data ) { auto iface = cast(AtkSelectionIface*)g_iface; - iface.is_child_selected = &AccessibleObject.atkSelection_is_child_selected; - iface.ref_selection = &AccessibleObject.atkSelection_ref_selection; - } + iface.is_child_selected = &AccessibleObject.atkSelection_is_child_selected; + iface.ref_selection = &AccessibleObject.atkSelection_ref_selection; + } - private static extern(C) void initTextIfaceCB ( void* g_iface, void* iface_data ) { + private static extern(C) void initTextIfaceCB ( void* g_iface, void* iface_data ) { auto iface = cast(AtkTextIface*)g_iface; - iface.get_caret_offset = &AccessibleObject.atkText_get_caret_offset; - iface.get_character_at_offset = &AccessibleObject.atkText_get_character_at_offset; - iface.get_character_count = &AccessibleObject.atkText_get_character_count; - iface.get_n_selections = &AccessibleObject.atkText_get_n_selections; - iface.get_selection = &AccessibleObject.atkText_get_selection; - iface.get_text = &AccessibleObject.atkText_get_text; - iface.get_text_after_offset = &AccessibleObject.atkText_get_text_after_offset; - iface.get_text_at_offset = &AccessibleObject.atkText_get_text_at_offset; - iface.get_text_before_offset = &AccessibleObject.atkText_get_text_before_offset; - } + iface.get_caret_offset = &AccessibleObject.atkText_get_caret_offset; + iface.get_character_at_offset = &AccessibleObject.atkText_get_character_at_offset; + iface.get_character_count = &AccessibleObject.atkText_get_character_count; + iface.get_n_selections = &AccessibleObject.atkText_get_n_selections; + iface.get_selection = &AccessibleObject.atkText_get_selection; + iface.get_text = &AccessibleObject.atkText_get_text; + iface.get_text_after_offset = &AccessibleObject.atkText_get_text_after_offset; + iface.get_text_at_offset = &AccessibleObject.atkText_get_text_at_offset; + iface.get_text_before_offset = &AccessibleObject.atkText_get_text_before_offset; + } - static void registerAccessible (Accessible accessible) { - /* If DefaultParentType is 0 then OS accessibility is not active */ - if (DefaultParentType is 0) return; - auto controlHandle = accessible.getControlHandle (); - auto widgetType = OS.G_OBJECT_TYPE ( cast(GTypeInstance*)controlHandle); - AccessibleFactory factory = Factories[widgetType]; - if (factory is null) { - factory = new AccessibleFactory (widgetType); - Factories[widgetType] = factory; - } - factory.addAccessible (accessible); - } + static void registerAccessible (Accessible accessible) { + /* If DefaultParentType is 0 then OS accessibility is not active */ + if (DefaultParentType is 0) return; + auto controlHandle = accessible.getControlHandle (); + auto widgetType = OS.G_OBJECT_TYPE ( cast(GTypeInstance*)controlHandle); + AccessibleFactory factory = Factories[widgetType]; + if (factory is null) { + factory = new AccessibleFactory (widgetType); + Factories[widgetType] = factory; + } + factory.addAccessible (accessible); + } - void removeAccessible (Accessible accessible) { - accessibles.remove (accessible.getControlHandle ()); - } + void removeAccessible (Accessible accessible) { + accessibles.remove (accessible.getControlHandle ()); + } - static void unregisterAccessible (Accessible accessible) { - auto controlHandle = accessible.getControlHandle (); - auto widgetType = OS.G_OBJECT_TYPE (cast(GTypeInstance*)controlHandle); - AccessibleFactory factory = Factories[widgetType]; - if (factory !is null) { - factory.removeAccessible (accessible); - } - } + static void unregisterAccessible (Accessible accessible) { + auto controlHandle = accessible.getControlHandle (); + auto widgetType = OS.G_OBJECT_TYPE (cast(GTypeInstance*)controlHandle); + AccessibleFactory factory = Factories[widgetType]; + if (factory !is null) { + factory.removeAccessible (accessible); + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleListener.d --- a/dwt/accessibility/AccessibleListener.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleListener.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -39,89 +39,89 @@ */ public interface AccessibleListener : SWTEventListener { - /** - * Sent when an accessibility client requests the name - * of the control, or the name of a child of the control. - *

- * Return the name of the control or specified child in the - * result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a name, and returning null tells the client - * to use the platform name. - *

- * - * @param e an event object containing the following fields: - */ - public void getName(AccessibleEvent e); + /** + * Sent when an accessibility client requests the name + * of the control, or the name of a child of the control. + *

+ * Return the name of the control or specified child in the + * result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a name, and returning null tells the client + * to use the platform name. + *

+ * + * @param e an event object containing the following fields: + */ + public void getName(AccessibleEvent e); - /** - * Sent when an accessibility client requests the help string - * of the control, or the help string of a child of the control. - *

- * The information in this property should be similar to the help - * provided by toolTipText. It describes what the control or child - * does or how to use it, as opposed to getDescription, which - * describes appearance. - *

- * Return the help string of the control or specified child in - * the result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a help string, and returning null tells the - * client to use the platform help string. - *

- * - * @param e an event object containing the following fields: - */ - public void getHelp(AccessibleEvent e); + /** + * Sent when an accessibility client requests the help string + * of the control, or the help string of a child of the control. + *

+ * The information in this property should be similar to the help + * provided by toolTipText. It describes what the control or child + * does or how to use it, as opposed to getDescription, which + * describes appearance. + *

+ * Return the help string of the control or specified child in + * the result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a help string, and returning null tells the + * client to use the platform help string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getHelp(AccessibleEvent e); - /** - * Sent when an accessibility client requests the keyboard shortcut - * of the control, or the keyboard shortcut of a child of the control. - *

- * A keyboard shortcut can either be a mnemonic, or an accelerator. - * As a general rule, if the control or child can receive keyboard focus, - * then you should expose its mnemonic, and if it cannot receive keyboard - * focus, then you should expose its accelerator. - *

- * Return the keyboard shortcut string of the control or specified child - * in the result field of the event object. Returning an - * empty string tells the client that the control or child does not - * have a keyboard shortcut string, and returning null tells the client - * to use the platform keyboard shortcut string. - *

- * - * @param e an event object containing the following fields: - */ - public void getKeyboardShortcut(AccessibleEvent e); + /** + * Sent when an accessibility client requests the keyboard shortcut + * of the control, or the keyboard shortcut of a child of the control. + *

+ * A keyboard shortcut can either be a mnemonic, or an accelerator. + * As a general rule, if the control or child can receive keyboard focus, + * then you should expose its mnemonic, and if it cannot receive keyboard + * focus, then you should expose its accelerator. + *

+ * Return the keyboard shortcut string of the control or specified child + * in the result field of the event object. Returning an + * empty string tells the client that the control or child does not + * have a keyboard shortcut string, and returning null tells the client + * to use the platform keyboard shortcut string. + *

+ * + * @param e an event object containing the following fields: + */ + public void getKeyboardShortcut(AccessibleEvent e); - /** - * Sent when an accessibility client requests a description - * of the control, or a description of a child of the control. - *

- * This is a textual description of the control or child's visual - * appearance, which is typically only necessary if it cannot be - * determined from other properties such as role. - *

- * Return the description of the control or specified child in - * the result field of the event object. Returning - * an empty string tells the client that the control or child - * does not have a description, and returning null tells the - * client to use the platform description. - *

- * - * @param e an event object containing the following fields: - */ - public void getDescription(AccessibleEvent e); + /** + * Sent when an accessibility client requests a description + * of the control, or a description of a child of the control. + *

+ * This is a textual description of the control or child's visual + * appearance, which is typically only necessary if it cannot be + * determined from other properties such as role. + *

+ * Return the description of the control or specified child in + * the result field of the event object. Returning + * an empty string tells the client that the control or child + * does not have a description, and returning null tells the + * client to use the platform description. + *

+ * + * @param e an event object containing the following fields: + */ + public void getDescription(AccessibleEvent e); } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleObject.d --- a/dwt/accessibility/AccessibleObject.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleObject.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -29,29 +29,29 @@ import Math = tango.math.Math; class AccessibleObject { - AtkObject* handle; - int /*long*/ parentType; - int index = -1, id = ACC.CHILDID_SELF; - Accessible accessible; - AccessibleObject parent; + AtkObject* handle; + int /*long*/ parentType; + int index = -1, id = ACC.CHILDID_SELF; + Accessible accessible; + AccessibleObject parent; AccessibleObject[AtkObject*] children; - /* - * a lightweight object does not correspond to a concrete gtk widget, but - * to a logical child of a widget (eg.- a CTabItem, which is simply drawn) - */ - bool isLightweight = false; + /* + * a lightweight object does not correspond to a concrete gtk widget, but + * to a logical child of a widget (eg.- a CTabItem, which is simply drawn) + */ + bool isLightweight = false; - static char[] actionNamePtr; - static char[] descriptionPtr; - static char[] keybindingPtr; - static char[] namePtr; + static char[] actionNamePtr; + static char[] descriptionPtr; + static char[] keybindingPtr; + static char[] namePtr; static AccessibleObject[AtkObject*] AccessibleObjects; - static /*const*/ uint ATK_ACTION_TYPE; - static /*const*/ uint ATK_COMPONENT_TYPE; - static /*const*/ uint ATK_HYPERTEXT_TYPE; - static /*const*/ uint ATK_SELECTION_TYPE; - static /*const*/ uint ATK_TEXT_TYPE; - static /*const*/ bool DEBUG; + static /*const*/ uint ATK_ACTION_TYPE; + static /*const*/ uint ATK_COMPONENT_TYPE; + static /*const*/ uint ATK_HYPERTEXT_TYPE; + static /*const*/ uint ATK_SELECTION_TYPE; + static /*const*/ uint ATK_TEXT_TYPE; + static /*const*/ bool DEBUG; public static void static_this() { DEBUG = Display.DEBUG; @@ -62,1320 +62,1320 @@ ATK_TEXT_TYPE = ATK.g_type_from_name ("AtkText"); } - this (int /*long*/ type, GtkWidget* widget, Accessible accessible, int /*long*/ parentType, bool isLightweight) { - handle = cast(AtkObject*)ATK.g_object_new (type, null); - this.parentType = parentType; - ATK.atk_object_initialize (handle, widget); - this.accessible = accessible; - this.isLightweight = isLightweight; - AccessibleObjects[handle] = this; - if (DEBUG) Stdout.formatln("new AccessibleObject: {}", handle); - } - - void addChild (AccessibleObject child) { - children[child.handle] = child; - child.setParent (this); - } + this (int /*long*/ type, GtkWidget* widget, Accessible accessible, int /*long*/ parentType, bool isLightweight) { + handle = cast(AtkObject*)ATK.g_object_new (type, null); + this.parentType = parentType; + ATK.atk_object_initialize (handle, widget); + this.accessible = accessible; + this.isLightweight = isLightweight; + AccessibleObjects[handle] = this; + if (DEBUG) Stdout.formatln("new AccessibleObject: {}", handle); + } - package static extern(C) char* atkAction_get_keybinding (void* obj, int index) { - auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkAction_get_keybinding"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - char* parentResult; - if (ATK.g_type_is_a (object.parentType, ATK_ACTION_TYPE)) { - auto superType = cast(AtkActionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_ACTION_GET_IFACE (object.handle)); - AtkActionIface* actionIface = superType; - if (actionIface.get_keybinding !is null) { - parentResult = actionIface.get_keybinding( object.handle, index ); - } - } - AccessibleListener[] listeners = object.getAccessibleListeners (); - if (listeners.length is 0) return parentResult; + void addChild (AccessibleObject child) { + children[child.handle] = child; + child.setParent (this); + } - AccessibleEvent event = new AccessibleEvent (object); - event.childID = object.id; - if (parentResult !is null) { - char[] res = fromUtf8z( parentResult ); - event.result = res.dup; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getKeyboardShortcut (event); - } - if (event.result is null) return parentResult; - if (keybindingPtr !is null ) OS.g_free (keybindingPtr.ptr); - char[] name = event.result.dup ~ \0; - char* p = cast(char*) OS.g_malloc (name.length); - keybindingPtr = p ? p[ 0 .. name.length ] : null; - return keybindingPtr.ptr; - } + package static extern(C) char* atkAction_get_keybinding (void* obj, int index) { + auto atkObject = cast(AtkObject*)obj; + if (DEBUG) Stdout.formatln ("-->atkAction_get_keybinding"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + char* parentResult; + if (ATK.g_type_is_a (object.parentType, ATK_ACTION_TYPE)) { + auto superType = cast(AtkActionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_ACTION_GET_IFACE (object.handle)); + AtkActionIface* actionIface = superType; + if (actionIface.get_keybinding !is null) { + parentResult = actionIface.get_keybinding( object.handle, index ); + } + } + AccessibleListener[] listeners = object.getAccessibleListeners (); + if (listeners.length is 0) return parentResult; - package static extern(C) char* atkAction_get_name (void* obj, int index) { - auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkAction_get_name"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - char* parentResult; - if (ATK.g_type_is_a (object.parentType, ATK_ACTION_TYPE)) { - auto actionIface = cast(AtkActionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_ACTION_GET_IFACE (object.handle)); - if (actionIface.get_name !is null) { - parentResult = actionIface.get_name( object.handle, index); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; - - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - if (parentResult !is null) { + AccessibleEvent event = new AccessibleEvent (object); + event.childID = object.id; + if (parentResult !is null) { char[] res = fromUtf8z( parentResult ); event.result = res.dup; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getDefaultAction (event); - } - if (event.result is null) return parentResult; - if (actionNamePtr !is null) OS.g_free (actionNamePtr.ptr); + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getKeyboardShortcut (event); + } + if (event.result is null) return parentResult; + if (keybindingPtr !is null ) OS.g_free (keybindingPtr.ptr); + char[] name = event.result.dup ~ \0; + char* p = cast(char*) OS.g_malloc (name.length); + keybindingPtr = p ? p[ 0 .. name.length ] : null; + return keybindingPtr.ptr; + } + + package static extern(C) char* atkAction_get_name (void* obj, int index) { + auto atkObject = cast(AtkObject*)obj; + if (DEBUG) Stdout.formatln ("-->atkAction_get_name"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + char* parentResult; + if (ATK.g_type_is_a (object.parentType, ATK_ACTION_TYPE)) { + auto actionIface = cast(AtkActionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_ACTION_GET_IFACE (object.handle)); + if (actionIface.get_name !is null) { + parentResult = actionIface.get_name( object.handle, index); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; + + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + if (parentResult !is null) { + char[] res = fromUtf8z( parentResult ); + event.result = res.dup; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getDefaultAction (event); + } + if (event.result is null) return parentResult; + if (actionNamePtr !is null) OS.g_free (actionNamePtr.ptr); char[] name = event.result.dup ~ \0; auto p = cast(char*)OS.g_malloc (name.length); actionNamePtr = p ? p[ 0 .. name.length ] : null; return actionNamePtr.ptr; - } + } - package static extern(C) void atkComponent_get_extents (void* obj, int* x, int* y, int* width, int* height, int coord_type) { + package static extern(C) void atkComponent_get_extents (void* obj, int* x, int* y, int* width, int* height, int coord_type) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkComponent_get_extents"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; + if (DEBUG) Stdout.formatln ("-->atkComponent_get_extents"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; *x = 0; *y = 0; *width = 0; *height = 0; - if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { - auto componentIface = cast(AtkComponentIface*) ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); - if (componentIface.get_extents !is null) { - componentIface.get_extents( object.handle, x, y, width, height, coord_type); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return 0; + if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { + auto componentIface = cast(AtkComponentIface*) ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); + if (componentIface.get_extents !is null) { + componentIface.get_extents( object.handle, x, y, width, height, coord_type); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return 0; - int parentX = *x, parentY = *y; - int parentWidth = *width, parentHeight = *height; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.x = parentX; event.y = parentY; - event.width = parentWidth; event.height = parentHeight; - if (coord_type is ATK.ATK_XY_WINDOW) { - /* translate control -> display, for filling in event to be dispatched */ - auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); - auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); - auto window = OS.GTK_WIDGET_WINDOW (topLevel); - int topWindowX, topWindowY; - OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); - event.x += topWindowX; - event.y += topWindowY; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getLocation (event); - } - if (coord_type is ATK.ATK_XY_WINDOW) { - /* translate display -> control, for answering to the OS */ - auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); - auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); - auto window = OS.GTK_WIDGET_WINDOW (topLevel); - int topWindowX, topWindowY; - OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); - event.x -= topWindowX; - event.y -= topWindowY; - } - *x = event.x; - *y = event.y; - *width = event.width; - *height = event.height; - //return 0; - } + int parentX = *x, parentY = *y; + int parentWidth = *width, parentHeight = *height; + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.x = parentX; event.y = parentY; + event.width = parentWidth; event.height = parentHeight; + if (coord_type is ATK.ATK_XY_WINDOW) { + /* translate control -> display, for filling in event to be dispatched */ + auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); + auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); + auto window = OS.GTK_WIDGET_WINDOW (topLevel); + int topWindowX, topWindowY; + OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); + event.x += topWindowX; + event.y += topWindowY; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getLocation (event); + } + if (coord_type is ATK.ATK_XY_WINDOW) { + /* translate display -> control, for answering to the OS */ + auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); + auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); + auto window = OS.GTK_WIDGET_WINDOW (topLevel); + int topWindowX, topWindowY; + OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); + event.x -= topWindowX; + event.y -= topWindowY; + } + *x = event.x; + *y = event.y; + *width = event.width; + *height = event.height; + //return 0; + } - package static extern(C) void atkComponent_get_position (void* obj, int* x, int* y, int coord_type) { + package static extern(C) void atkComponent_get_position (void* obj, int* x, int* y, int coord_type) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkComponent_get_position, object: {} x:{} y:{} coord:{}", atkObject, x, y, coord_type); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - *x=0; - *y=0; - if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { - auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); - if (componentIface.get_extents !is null) { - componentIface.get_position( object.handle, x, y, coord_type); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return 0; + if (DEBUG) Stdout.formatln ("-->atkComponent_get_position, object: {} x:{} y:{} coord:{}", atkObject, x, y, coord_type); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + *x=0; + *y=0; + if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { + auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); + if (componentIface.get_extents !is null) { + componentIface.get_position( object.handle, x, y, coord_type); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return 0; - int parentX, parentY; - parentX = *x; - parentY = *y; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.x = parentX; event.y = parentY; - if (coord_type is ATK.ATK_XY_WINDOW) { - /* translate control -> display, for filling in event to be dispatched */ - auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); - auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); - auto window = OS.GTK_WIDGET_WINDOW (topLevel); - int topWindowX, topWindowY; - OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); - event.x += topWindowX; - event.y += topWindowY; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getLocation (event); - } - if (coord_type is ATK.ATK_XY_WINDOW) { - /* translate display -> control, for answering to the OS */ - auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); - auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); - auto window = OS.GTK_WIDGET_WINDOW (topLevel); + int parentX, parentY; + parentX = *x; + parentY = *y; + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.x = parentX; event.y = parentY; + if (coord_type is ATK.ATK_XY_WINDOW) { + /* translate control -> display, for filling in event to be dispatched */ + auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); + auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); + auto window = OS.GTK_WIDGET_WINDOW (topLevel); int topWindowX, topWindowY; - OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); - event.x -= topWindowX; - event.y -= topWindowY; - } - *x=event.x; - *y=event.y; - //return 0; - } + OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); + event.x += topWindowX; + event.y += topWindowY; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getLocation (event); + } + if (coord_type is ATK.ATK_XY_WINDOW) { + /* translate display -> control, for answering to the OS */ + auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); + auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); + auto window = OS.GTK_WIDGET_WINDOW (topLevel); + int topWindowX, topWindowY; + OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); + event.x -= topWindowX; + event.y -= topWindowY; + } + *x=event.x; + *y=event.y; + //return 0; + } //PORTING_FIXME: what about the coord_type? componentIface.get_size( object.handle, width, height, coord_type); //package static extern(C) void atkComponent_get_size (void* obj, int* width, int* height, int coord_type) { package static extern(C) void atkComponent_get_size (void* obj, int* width, int* height) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkComponent_get_size"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - *width=0; - *height=0; - if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { - auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); - if (componentIface.get_extents !is null) { + if (DEBUG) Stdout.formatln ("-->atkComponent_get_size"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + *width=0; + *height=0; + if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { + auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); + if (componentIface.get_extents !is null) { //PORTING_FIXME: what about the coord_type? componentIface.get_size( object.handle, width, height, coord_type); componentIface.get_size( object.handle, width, height); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return 0; + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return 0; - int parentWidth, parentHeight; - parentWidth= *width; - parentHeight= *height; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.width = parentWidth; event.height = parentHeight; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getLocation (event); - } - *width=event.width; - *height=event.height; - //return 0; - } + int parentWidth, parentHeight; + parentWidth= *width; + parentHeight= *height; + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.width = parentWidth; event.height = parentHeight; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getLocation (event); + } + *width=event.width; + *height=event.height; + //return 0; + } - package static extern(C) AtkObject* atkComponent_ref_accessible_at_point (void* obj, int x, int y, int coord_type) { + package static extern(C) AtkObject* atkComponent_ref_accessible_at_point (void* obj, int x, int y, int coord_type) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkComponent_ref_accessible_at_point"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - AtkObject* parentResult; - if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { - auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); - if (componentIface.ref_accessible_at_point !is null) { - parentResult = componentIface.ref_accessible_at_point( object.handle, x, y, coord_type); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; + if (DEBUG) Stdout.formatln ("-->atkComponent_ref_accessible_at_point"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + AtkObject* parentResult; + if (ATK.g_type_is_a (object.parentType, ATK_COMPONENT_TYPE)) { + auto componentIface = cast(AtkComponentIface*)ATK.g_type_interface_peek_parent (ATK.ATK_COMPONENT_GET_IFACE (object.handle)); + if (componentIface.ref_accessible_at_point !is null) { + parentResult = componentIface.ref_accessible_at_point( object.handle, x, y, coord_type); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.x = x; event.y = y; - if (coord_type is ATK.ATK_XY_WINDOW) { - /* translate control -> display, for filling in the event to be dispatched */ - auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); - auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); - auto window = OS.GTK_WIDGET_WINDOW (topLevel); - int topWindowX, topWindowY; - OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); - event.x += topWindowX; - event.y += topWindowY; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getChildAtPoint (event); - } - if (event.childID is object.id) event.childID = ACC.CHILDID_SELF; - AccessibleObject accObj = object.getChildByID (event.childID); - if (accObj !is null) { - if (parentResult !is null) OS.g_object_unref (parentResult); - OS.g_object_ref (accObj.handle); - return accObj.handle; - } - return parentResult; - } + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.x = x; event.y = y; + if (coord_type is ATK.ATK_XY_WINDOW) { + /* translate control -> display, for filling in the event to be dispatched */ + auto gtkAccessible = ATK.GTK_ACCESSIBLE (object.handle); + auto topLevel = ATK.gtk_widget_get_toplevel (gtkAccessible.widget); + auto window = OS.GTK_WIDGET_WINDOW (topLevel); + int topWindowX, topWindowY; + OS.gdk_window_get_origin (window, &topWindowX, &topWindowY); + event.x += topWindowX; + event.y += topWindowY; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getChildAtPoint (event); + } + if (event.childID is object.id) event.childID = ACC.CHILDID_SELF; + AccessibleObject accObj = object.getChildByID (event.childID); + if (accObj !is null) { + if (parentResult !is null) OS.g_object_unref (parentResult); + OS.g_object_ref (accObj.handle); + return accObj.handle; + } + return parentResult; + } - package static extern(C) AtkHyperlink* atkHypertext_get_link (void* obj, int link_index) { + package static extern(C) AtkHyperlink* atkHypertext_get_link (void* obj, int link_index) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkHypertext_get_link"); - return null; - } + if (DEBUG) Stdout.formatln ("-->atkHypertext_get_link"); + return null; + } - package static extern(C) int atkHypertext_get_n_links (void* obj) { + package static extern(C) int atkHypertext_get_n_links (void* obj) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkHypertext_get_n_links"); - return 0; /* read hyperlink's name */ - } + if (DEBUG) Stdout.formatln ("-->atkHypertext_get_n_links"); + return 0; /* read hyperlink's name */ + } - package static extern(C) int atkHypertext_get_link_index (void* obj, int char_index) { + package static extern(C) int atkHypertext_get_link_index (void* obj, int char_index) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkHypertext_get_link_index"); - return 0; - } + if (DEBUG) Stdout.formatln ("-->atkHypertext_get_link_index"); + return 0; + } - package static extern(C) char* atkObject_get_description (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_get_description"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - char* parentResult; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_description !is null) { - parentResult = objectClass.get_description(object.handle); - } - AccessibleListener[] listeners = object.getAccessibleListeners (); - if (listeners.length is 0) return parentResult; + package static extern(C) char* atkObject_get_description (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_get_description"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + char* parentResult; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_description !is null) { + parentResult = objectClass.get_description(object.handle); + } + AccessibleListener[] listeners = object.getAccessibleListeners (); + if (listeners.length is 0) return parentResult; - AccessibleEvent event = new AccessibleEvent (object); - event.childID = object.id; - if (parentResult !is null) { - event.result = fromUtf8z( parentResult ).dup; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getDescription (event); - } - if (event.result is null) return parentResult; - if (descriptionPtr !is null) OS.g_free (descriptionPtr.ptr); + AccessibleEvent event = new AccessibleEvent (object); + event.childID = object.id; + if (parentResult !is null) { + event.result = fromUtf8z( parentResult ).dup; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getDescription (event); + } + if (event.result is null) return parentResult; + if (descriptionPtr !is null) OS.g_free (descriptionPtr.ptr); char[] name = event.result.dup ~ \0; char* p = cast(char*)OS.g_malloc (name.length); descriptionPtr = p ? p[ 0 .. name.length ] : null; - return descriptionPtr.ptr; } + return descriptionPtr.ptr; } - package static extern(C) char* atkObject_get_name (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_get_name: {}", atkObject); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - char* parentResult; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_name !is null) { - parentResult = objectClass.get_name( object.handle); - } - AccessibleListener[] listeners = object.getAccessibleListeners (); - if (listeners.length is 0) return parentResult; + package static extern(C) char* atkObject_get_name (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_get_name: {}", atkObject); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + char* parentResult; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_name !is null) { + parentResult = objectClass.get_name( object.handle); + } + AccessibleListener[] listeners = object.getAccessibleListeners (); + if (listeners.length is 0) return parentResult; - AccessibleEvent event = new AccessibleEvent (object); - event.childID = object.id; - if (parentResult !is null) { - event.result = fromUtf8z( parentResult ).dup; - } - for (int i = 0; i < listeners.length; i++) { - listeners [i].getName (event); - } - if (event.result is null) return parentResult; - if (namePtr !is null) OS.g_free (namePtr.ptr); + AccessibleEvent event = new AccessibleEvent (object); + event.childID = object.id; + if (parentResult !is null) { + event.result = fromUtf8z( parentResult ).dup; + } + for (int i = 0; i < listeners.length; i++) { + listeners [i].getName (event); + } + if (event.result is null) return parentResult; + if (namePtr !is null) OS.g_free (namePtr.ptr); char[] name = event.result.dup ~ \0; char* p = cast(char*)OS.g_malloc (name.length); namePtr = p ? p[ 0 .. name.length ] : null; return namePtr.ptr; - } + } - package static extern(C) int atkObject_get_n_children (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_get_n_children: {}", atkObject); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - int /*long*/ parentResult = 0; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_n_children !is null) { - parentResult = objectClass.get_n_children( object.handle); - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; + package static extern(C) int atkObject_get_n_children (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_get_n_children: {}", atkObject); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + int /*long*/ parentResult = 0; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_n_children !is null) { + parentResult = objectClass.get_n_children( object.handle); + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.detail = cast(int)/*64*/parentResult; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getChildCount (event); - } - return event.detail; - } + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.detail = cast(int)/*64*/parentResult; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getChildCount (event); + } + return event.detail; + } - package static extern(C) int atkObject_get_index_in_parent (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObjectCB_get_index_in_parent. "); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - if (object.index !is -1) return object.index; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_index_in_parent is null) return 0; - return objectClass.get_index_in_parent(object. handle); - } + package static extern(C) int atkObject_get_index_in_parent (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObjectCB_get_index_in_parent. "); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + if (object.index !is -1) return object.index; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_index_in_parent is null) return 0; + return objectClass.get_index_in_parent(object. handle); + } - package static extern(C) AtkObject* atkObject_get_parent (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_get_parent: {}", atkObject); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - if (object.parent !is null) return object.parent.handle; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_parent is null) return null; - return objectClass.get_parent( object.handle); - } + package static extern(C) AtkObject* atkObject_get_parent (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_get_parent: {}", atkObject); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + if (object.parent !is null) return object.parent.handle; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_parent is null) return null; + return objectClass.get_parent( object.handle); + } - package static extern(C) int atkObject_get_role (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_get_role: {}", atkObject); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - if (object.getAccessibleListeners ().length !is 0) { - AccessibleControlListener[] listeners = object.getControlListeners (); - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.detail = -1; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getRole (event); - } - if (event.detail !is -1) { - switch (event.detail) { - /* Convert from win32 role values to atk role values */ - case ACC.ROLE_CHECKBUTTON: return ATK.ATK_ROLE_CHECK_BOX; - case ACC.ROLE_CLIENT_AREA: return ATK.ATK_ROLE_DRAWING_AREA; - case ACC.ROLE_COMBOBOX: return ATK.ATK_ROLE_COMBO_BOX; - case ACC.ROLE_DIALOG: return ATK.ATK_ROLE_DIALOG; - case ACC.ROLE_LABEL: return ATK.ATK_ROLE_LABEL; - case ACC.ROLE_LINK: return ATK.ATK_ROLE_TEXT; - case ACC.ROLE_LIST: return ATK.ATK_ROLE_LIST; - case ACC.ROLE_LISTITEM: return ATK.ATK_ROLE_LIST_ITEM; - case ACC.ROLE_MENU: return ATK.ATK_ROLE_MENU; - case ACC.ROLE_MENUBAR: return ATK.ATK_ROLE_MENU_BAR; - case ACC.ROLE_MENUITEM: return ATK.ATK_ROLE_MENU_ITEM; - case ACC.ROLE_PROGRESSBAR: return ATK.ATK_ROLE_PROGRESS_BAR; - case ACC.ROLE_PUSHBUTTON: return ATK.ATK_ROLE_PUSH_BUTTON; - case ACC.ROLE_SCROLLBAR: return ATK.ATK_ROLE_SCROLL_BAR; - case ACC.ROLE_SEPARATOR: return ATK.ATK_ROLE_SEPARATOR; - case ACC.ROLE_SLIDER: return ATK.ATK_ROLE_SLIDER; - case ACC.ROLE_TABLE: return ATK.ATK_ROLE_TABLE; - case ACC.ROLE_TABLECELL: return ATK.ATK_ROLE_TABLE_CELL; - case ACC.ROLE_TABLECOLUMNHEADER: return ATK.ATK_ROLE_TABLE_COLUMN_HEADER; - case ACC.ROLE_TABLEROWHEADER: return ATK.ATK_ROLE_TABLE_ROW_HEADER; - case ACC.ROLE_TABFOLDER: return ATK.ATK_ROLE_PAGE_TAB_LIST; - case ACC.ROLE_TABITEM: return ATK.ATK_ROLE_PAGE_TAB; - case ACC.ROLE_TEXT: return ATK.ATK_ROLE_TEXT; - case ACC.ROLE_TOOLBAR: return ATK.ATK_ROLE_TOOL_BAR; - case ACC.ROLE_TOOLTIP: return ATK.ATK_ROLE_TOOL_TIP; - case ACC.ROLE_TREE: return ATK.ATK_ROLE_TREE; - case ACC.ROLE_TREEITEM: return ATK.ATK_ROLE_LIST_ITEM; - case ACC.ROLE_RADIOBUTTON: return ATK.ATK_ROLE_RADIO_BUTTON; - case ACC.ROLE_WINDOW: return ATK.ATK_ROLE_WINDOW; + package static extern(C) int atkObject_get_role (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_get_role: {}", atkObject); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + if (object.getAccessibleListeners ().length !is 0) { + AccessibleControlListener[] listeners = object.getControlListeners (); + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.detail = -1; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getRole (event); + } + if (event.detail !is -1) { + switch (event.detail) { + /* Convert from win32 role values to atk role values */ + case ACC.ROLE_CHECKBUTTON: return ATK.ATK_ROLE_CHECK_BOX; + case ACC.ROLE_CLIENT_AREA: return ATK.ATK_ROLE_DRAWING_AREA; + case ACC.ROLE_COMBOBOX: return ATK.ATK_ROLE_COMBO_BOX; + case ACC.ROLE_DIALOG: return ATK.ATK_ROLE_DIALOG; + case ACC.ROLE_LABEL: return ATK.ATK_ROLE_LABEL; + case ACC.ROLE_LINK: return ATK.ATK_ROLE_TEXT; + case ACC.ROLE_LIST: return ATK.ATK_ROLE_LIST; + case ACC.ROLE_LISTITEM: return ATK.ATK_ROLE_LIST_ITEM; + case ACC.ROLE_MENU: return ATK.ATK_ROLE_MENU; + case ACC.ROLE_MENUBAR: return ATK.ATK_ROLE_MENU_BAR; + case ACC.ROLE_MENUITEM: return ATK.ATK_ROLE_MENU_ITEM; + case ACC.ROLE_PROGRESSBAR: return ATK.ATK_ROLE_PROGRESS_BAR; + case ACC.ROLE_PUSHBUTTON: return ATK.ATK_ROLE_PUSH_BUTTON; + case ACC.ROLE_SCROLLBAR: return ATK.ATK_ROLE_SCROLL_BAR; + case ACC.ROLE_SEPARATOR: return ATK.ATK_ROLE_SEPARATOR; + case ACC.ROLE_SLIDER: return ATK.ATK_ROLE_SLIDER; + case ACC.ROLE_TABLE: return ATK.ATK_ROLE_TABLE; + case ACC.ROLE_TABLECELL: return ATK.ATK_ROLE_TABLE_CELL; + case ACC.ROLE_TABLECOLUMNHEADER: return ATK.ATK_ROLE_TABLE_COLUMN_HEADER; + case ACC.ROLE_TABLEROWHEADER: return ATK.ATK_ROLE_TABLE_ROW_HEADER; + case ACC.ROLE_TABFOLDER: return ATK.ATK_ROLE_PAGE_TAB_LIST; + case ACC.ROLE_TABITEM: return ATK.ATK_ROLE_PAGE_TAB; + case ACC.ROLE_TEXT: return ATK.ATK_ROLE_TEXT; + case ACC.ROLE_TOOLBAR: return ATK.ATK_ROLE_TOOL_BAR; + case ACC.ROLE_TOOLTIP: return ATK.ATK_ROLE_TOOL_TIP; + case ACC.ROLE_TREE: return ATK.ATK_ROLE_TREE; + case ACC.ROLE_TREEITEM: return ATK.ATK_ROLE_LIST_ITEM; + case ACC.ROLE_RADIOBUTTON: return ATK.ATK_ROLE_RADIO_BUTTON; + case ACC.ROLE_WINDOW: return ATK.ATK_ROLE_WINDOW; default: - } - } - } - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.get_role is null) return 0; - return objectClass.get_role( object.handle); - } + } + } + } + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.get_role is null) return 0; + return objectClass.get_role( object.handle); + } - package static extern(C) AtkObject* atkObject_ref_child (AtkObject* atkObject, int /*long*/ index) { - if (DEBUG) Stdout.formatln ("-->atkObject_ref_child: {} of: {}", index, atkObject); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - object.updateChildren (); - AccessibleObject accObject = object.getChildByIndex (cast(int)/*64*/index); - if (accObject !is null) { - OS.g_object_ref (accObject.handle); - return accObject.handle; - } - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.ref_child is null) return null; - return objectClass.ref_child( object.handle, index); - } + package static extern(C) AtkObject* atkObject_ref_child (AtkObject* atkObject, int /*long*/ index) { + if (DEBUG) Stdout.formatln ("-->atkObject_ref_child: {} of: {}", index, atkObject); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + object.updateChildren (); + AccessibleObject accObject = object.getChildByIndex (cast(int)/*64*/index); + if (accObject !is null) { + OS.g_object_ref (accObject.handle); + return accObject.handle; + } + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.ref_child is null) return null; + return objectClass.ref_child( object.handle, index); + } - package static extern(C) AtkStateSet * atkObject_ref_state_set (AtkObject* atkObject) { - if (DEBUG) Stdout.formatln ("-->atkObject_ref_state_set"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - AtkStateSet* parentResult; - auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); - if (objectClass.ref_state_set !is null) { - parentResult = objectClass.ref_state_set( object.handle); - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; + package static extern(C) AtkStateSet * atkObject_ref_state_set (AtkObject* atkObject) { + if (DEBUG) Stdout.formatln ("-->atkObject_ref_state_set"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + AtkStateSet* parentResult; + auto objectClass = cast(AtkObjectClass*)ATK.g_type_class_peek (object.parentType); + if (objectClass.ref_state_set !is null) { + parentResult = objectClass.ref_state_set( object.handle); + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; - auto set = parentResult; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - event.detail = -1; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getState (event); - } - if (event.detail !is -1) { - /* Convert from win32 state values to atk state values */ - int state = event.detail; - if ((state & ACC.STATE_BUSY) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_BUSY); - if ((state & ACC.STATE_CHECKED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_CHECKED); - if ((state & ACC.STATE_EXPANDED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_EXPANDED); - if ((state & ACC.STATE_FOCUSABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_FOCUSABLE); - if ((state & ACC.STATE_FOCUSED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_FOCUSED); - if ((state & ACC.STATE_HOTTRACKED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_ARMED); - if ((state & ACC.STATE_INVISIBLE) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_VISIBLE); - if ((state & ACC.STATE_MULTISELECTABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_MULTISELECTABLE); - if ((state & ACC.STATE_OFFSCREEN) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SHOWING); - if ((state & ACC.STATE_PRESSED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_PRESSED); - if ((state & ACC.STATE_READONLY) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_EDITABLE); - if ((state & ACC.STATE_SELECTABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SELECTABLE); - if ((state & ACC.STATE_SELECTED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SELECTED); - if ((state & ACC.STATE_SIZEABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_RESIZABLE); - /* Note: STATE_COLLAPSED, STATE_LINKED and STATE_NORMAL have no ATK equivalents */ - } - return set; - } + auto set = parentResult; + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + event.detail = -1; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getState (event); + } + if (event.detail !is -1) { + /* Convert from win32 state values to atk state values */ + int state = event.detail; + if ((state & ACC.STATE_BUSY) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_BUSY); + if ((state & ACC.STATE_CHECKED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_CHECKED); + if ((state & ACC.STATE_EXPANDED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_EXPANDED); + if ((state & ACC.STATE_FOCUSABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_FOCUSABLE); + if ((state & ACC.STATE_FOCUSED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_FOCUSED); + if ((state & ACC.STATE_HOTTRACKED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_ARMED); + if ((state & ACC.STATE_INVISIBLE) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_VISIBLE); + if ((state & ACC.STATE_MULTISELECTABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_MULTISELECTABLE); + if ((state & ACC.STATE_OFFSCREEN) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SHOWING); + if ((state & ACC.STATE_PRESSED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_PRESSED); + if ((state & ACC.STATE_READONLY) is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_EDITABLE); + if ((state & ACC.STATE_SELECTABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SELECTABLE); + if ((state & ACC.STATE_SELECTED) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_SELECTED); + if ((state & ACC.STATE_SIZEABLE) !is 0) ATK.atk_state_set_add_state (set, ATK.ATK_STATE_RESIZABLE); + /* Note: STATE_COLLAPSED, STATE_LINKED and STATE_NORMAL have no ATK equivalents */ + } + return set; + } - package static extern(C) int atkSelection_is_child_selected (void* obj, int index) { + package static extern(C) int atkSelection_is_child_selected (void* obj, int index) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkSelection_is_child_selected"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - int /*long*/ parentResult = 0; - if (ATK.g_type_is_a (object.parentType, ATK_SELECTION_TYPE)) { - auto selectionIface = cast(AtkSelectionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_SELECTION_GET_IFACE (object.handle)); - if (selectionIface.is_child_selected !is null) { - parentResult = selectionIface.is_child_selected( object.handle, index); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; + if (DEBUG) Stdout.formatln ("-->atkSelection_is_child_selected"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + int /*long*/ parentResult = 0; + if (ATK.g_type_is_a (object.parentType, ATK_SELECTION_TYPE)) { + auto selectionIface = cast(AtkSelectionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_SELECTION_GET_IFACE (object.handle)); + if (selectionIface.is_child_selected !is null) { + parentResult = selectionIface.is_child_selected( object.handle, index); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getSelection (event); - } - AccessibleObject accessibleObject = object.getChildByID (event.childID); - if (accessibleObject !is null) { - return accessibleObject.index is index ? 1 : 0; - } - return parentResult; - } + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getSelection (event); + } + AccessibleObject accessibleObject = object.getChildByID (event.childID); + if (accessibleObject !is null) { + return accessibleObject.index is index ? 1 : 0; + } + return parentResult; + } - package static extern(C) AtkObject* atkSelection_ref_selection (void* obj, int index) { + package static extern(C) AtkObject* atkSelection_ref_selection (void* obj, int index) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkSelection_ref_selection"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - AtkObject* parentResult; - if (ATK.g_type_is_a (object.parentType, ATK_SELECTION_TYPE)) { - auto selectionIface = cast(AtkSelectionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_SELECTION_GET_IFACE (object.handle)); - if (selectionIface.ref_selection !is null) { - parentResult = selectionIface.ref_selection( object.handle, index); - } - } - AccessibleControlListener[] listeners = object.getControlListeners (); - if (listeners.length is 0) return parentResult; + if (DEBUG) Stdout.formatln ("-->atkSelection_ref_selection"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + AtkObject* parentResult; + if (ATK.g_type_is_a (object.parentType, ATK_SELECTION_TYPE)) { + auto selectionIface = cast(AtkSelectionIface*)ATK.g_type_interface_peek_parent (ATK.ATK_SELECTION_GET_IFACE (object.handle)); + if (selectionIface.ref_selection !is null) { + parentResult = selectionIface.ref_selection( object.handle, index); + } + } + AccessibleControlListener[] listeners = object.getControlListeners (); + if (listeners.length is 0) return parentResult; - AccessibleControlEvent event = new AccessibleControlEvent (object); - event.childID = object.id; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getSelection (event); - } - AccessibleObject accObj = object.getChildByID (event.childID); - if (accObj !is null) { - if (parentResult !is null) OS.g_object_unref (parentResult); - OS.g_object_ref (accObj.handle); - return accObj.handle; - } - return parentResult; - } + AccessibleControlEvent event = new AccessibleControlEvent (object); + event.childID = object.id; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getSelection (event); + } + AccessibleObject accObj = object.getChildByID (event.childID); + if (accObj !is null) { + if (parentResult !is null) OS.g_object_unref (parentResult); + OS.g_object_ref (accObj.handle); + return accObj.handle; + } + return parentResult; + } - package static extern(C) int atkText_get_caret_offset (void* obj) { + package static extern(C) int atkText_get_caret_offset (void* obj) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_caret_offset"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - int /*long*/ parentResult = 0; - if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); - if (textIface.get_caret_offset !is null) { - parentResult = textIface.get_caret_offset( object.handle); - } - } - AccessibleTextListener[] listeners = object.getTextListeners (); - if (listeners.length is 0) return parentResult; + if (DEBUG) Stdout.formatln ("-->atkText_get_caret_offset"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + int /*long*/ parentResult = 0; + if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); + if (textIface.get_caret_offset !is null) { + parentResult = textIface.get_caret_offset( object.handle); + } + } + AccessibleTextListener[] listeners = object.getTextListeners (); + if (listeners.length is 0) return parentResult; - AccessibleTextEvent event = new AccessibleTextEvent (object); - event.childID = object.id; - event.offset = cast(int)/*64*/parentResult; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getCaretOffset (event); - } - return event.offset; - } + AccessibleTextEvent event = new AccessibleTextEvent (object); + event.childID = object.id; + event.offset = cast(int)/*64*/parentResult; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getCaretOffset (event); + } + return event.offset; + } - package static extern(C) uint atkText_get_character_at_offset (void* obj, int offset) { + package static extern(C) uint atkText_get_character_at_offset (void* obj, int offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_character_at_offset"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - char[] text = object.getText (); - if (text !is null) return text[cast(int)/*64*/offset ]; // TODO - if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_class_peek (object.parentType); - if (textIface.get_character_at_offset !is null) { - return textIface.get_character_at_offset( object.handle, offset); - } - } - return 0; - } + if (DEBUG) Stdout.formatln ("-->atkText_get_character_at_offset"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + char[] text = object.getText (); + if (text !is null) return text[cast(int)/*64*/offset ]; // TODO + if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_class_peek (object.parentType); + if (textIface.get_character_at_offset !is null) { + return textIface.get_character_at_offset( object.handle, offset); + } + } + return 0; + } - package static extern(C) int atkText_get_character_count (void* obj) { + package static extern(C) int atkText_get_character_count (void* obj) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_character_count"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - char[] text = object.getText (); - if (text !is null) return text.length; - if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_class_peek (object.parentType); - if (textIface.get_character_count !is null) { - return textIface.get_character_count( object.handle); - } - } - return 0; - } + if (DEBUG) Stdout.formatln ("-->atkText_get_character_count"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + char[] text = object.getText (); + if (text !is null) return text.length; + if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_class_peek (object.parentType); + if (textIface.get_character_count !is null) { + return textIface.get_character_count( object.handle); + } + } + return 0; + } - package static extern(C) int atkText_get_n_selections (void* obj) { + package static extern(C) int atkText_get_n_selections (void* obj) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln("-->atkText_get_n_selections"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return 0; - int /*long*/ parentResult = 0; - if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); - if (textIface.get_n_selections !is null) { - parentResult = textIface.get_n_selections( object.handle); - } - } - AccessibleTextListener[] listeners = object.getTextListeners (); - if (listeners.length is 0) return parentResult; + if (DEBUG) Stdout.formatln("-->atkText_get_n_selections"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return 0; + int /*long*/ parentResult = 0; + if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); + if (textIface.get_n_selections !is null) { + parentResult = textIface.get_n_selections( object.handle); + } + } + AccessibleTextListener[] listeners = object.getTextListeners (); + if (listeners.length is 0) return parentResult; - AccessibleTextEvent event = new AccessibleTextEvent (object); - event.childID = object.id; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getSelectionRange (event); - } - return event.length is 0 ? parentResult : 1; - } + AccessibleTextEvent event = new AccessibleTextEvent (object); + event.childID = object.id; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getSelectionRange (event); + } + return event.length is 0 ? parentResult : 1; + } - package static extern(C) char* atkText_get_selection (void* obj, int selection_num, int* start_offset, int* end_offset) { + package static extern(C) char* atkText_get_selection (void* obj, int selection_num, int* start_offset, int* end_offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_selection"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - *start_offset=0; - *end_offset=0; - if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); - if (textIface.get_selection !is null) { - textIface.get_selection( object.handle, selection_num, start_offset, end_offset ); - } - } - AccessibleTextListener[] listeners = object.getTextListeners (); - if (listeners.length is 0) return null; + if (DEBUG) Stdout.formatln ("-->atkText_get_selection"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + *start_offset=0; + *end_offset=0; + if (ATK.g_type_is_a (object.parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (object.handle)); + if (textIface.get_selection !is null) { + textIface.get_selection( object.handle, selection_num, start_offset, end_offset ); + } + } + AccessibleTextListener[] listeners = object.getTextListeners (); + if (listeners.length is 0) return null; - AccessibleTextEvent event = new AccessibleTextEvent (object); - event.childID = object.id; - int parentStart; - int parentEnd; - parentStart= *start_offset; - parentEnd= *end_offset; - event.offset = parentStart; - event.length = parentEnd - parentStart; - for (int i = 0; i < listeners.length; i++) { - listeners [i].getSelectionRange (event); - } - *start_offset = event.offset; - *end_offset = event.offset + event.length; - return null; - } + AccessibleTextEvent event = new AccessibleTextEvent (object); + event.childID = object.id; + int parentStart; + int parentEnd; + parentStart= *start_offset; + parentEnd= *end_offset; + event.offset = parentStart; + event.length = parentEnd - parentStart; + for (int i = 0; i < listeners.length; i++) { + listeners [i].getSelectionRange (event); + } + *start_offset = event.offset; + *end_offset = event.offset + event.length; + return null; + } - package static extern(C) char* atkText_get_text (void* obj, int start_offset, int end_offset) { + package static extern(C) char* atkText_get_text (void* obj, int start_offset, int end_offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_text: {},{}", start_offset, end_offset); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - char[] text = object.getText (); - if (text.length > 0) { - if (end_offset is -1) { - end_offset = text.length ; - } else { - end_offset = Math.min (end_offset, text.length ); - } - start_offset = Math.min (start_offset, end_offset); - text = text[ start_offset .. end_offset ]; - auto result = cast(char*)OS.g_malloc (text.length+1); + if (DEBUG) Stdout.formatln ("-->atkText_get_text: {},{}", start_offset, end_offset); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + char[] text = object.getText (); + if (text.length > 0) { + if (end_offset is -1) { + end_offset = text.length ; + } else { + end_offset = Math.min (end_offset, text.length ); + } + start_offset = Math.min (start_offset, end_offset); + text = text[ start_offset .. end_offset ]; + auto result = cast(char*)OS.g_malloc (text.length+1); result[ 0 .. text.length ] = text; result[ text.length ] = '\0'; - return result; - } - return null; - } + return result; + } + return null; + } - package static extern(C) char* atkText_get_text_after_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { + package static extern(C) char* atkText_get_text_after_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_text_after_offset"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - int offset = cast(int)/*64*/offset_value; - char[] text = object.getText (); - if (text.length > 0) { - int length = text.length ; - offset = Math.min (offset, length - 1); - int startBounds = offset; - int endBounds = offset; - switch (cast(int)/*64*/boundary_type) { - case ATK.ATK_TEXT_BOUNDARY_CHAR: { - if (length > offset) endBounds++; - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_START: { - int wordStart1 = nextIndexOfChar (text, " !?.\n", offset - 1); - if (wordStart1 is -1) { - startBounds = endBounds = length; - break; - } - wordStart1 = nextIndexOfNotChar (text, " !?.\n", wordStart1); - if (wordStart1 is length) { - startBounds = endBounds = length; - break; - } - startBounds = wordStart1; - int wordStart2 = nextIndexOfChar (text, " !?.\n", wordStart1); - if (wordStart2 is -1) { - endBounds = length; - break; - } - endBounds = nextIndexOfNotChar (text, " !?.\n", wordStart2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_END: { - int previousWordEnd = previousIndexOfNotChar (text, " \n", offset); - if (previousWordEnd is -1 || previousWordEnd !is offset - 1) { - offset = nextIndexOfNotChar (text, " \n", offset); - } - if (offset is -1) { - startBounds = endBounds = length; - break; - } - int wordEnd1 = nextIndexOfChar (text, " !?.\n", cast(int)/*64*/offset); - if (wordEnd1 is -1) { - startBounds = endBounds = length; - break; - } - wordEnd1 = nextIndexOfNotChar (text, "!?.", wordEnd1); - if (wordEnd1 is length) { - startBounds = endBounds = length; - break; - } - startBounds = wordEnd1; - int wordEnd2 = nextIndexOfNotChar (text, " \n", wordEnd1); - if (wordEnd2 is length) { - startBounds = endBounds = length; - break; - } - wordEnd2 = nextIndexOfChar (text, " !?.\n", wordEnd2); - if (wordEnd2 is -1) { - endBounds = length; - break; - } - endBounds = nextIndexOfNotChar (text, "!?.", wordEnd2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { - int previousSentenceEnd = previousIndexOfChar (text, "!?.", offset); - int previousText = previousIndexOfNotChar (text, " !?.\n", offset); - int sentenceStart1 = 0; - if (previousSentenceEnd >= previousText) { - sentenceStart1 = nextIndexOfNotChar (text, " !?.\n", offset); - } else { - sentenceStart1 = nextIndexOfChar (text, "!?.", offset); - if (sentenceStart1 is -1) { - startBounds = endBounds = length; - break; - } - sentenceStart1 = nextIndexOfNotChar (text, " !?.\n", sentenceStart1); - } - if (sentenceStart1 is length) { - startBounds = endBounds = length; - break; - } - startBounds = sentenceStart1; - int sentenceStart2 = nextIndexOfChar (text, "!?.", sentenceStart1); - if (sentenceStart2 is -1) { - endBounds = length; - break; - } - endBounds = nextIndexOfNotChar (text, " !?.\n", sentenceStart2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { - int sentenceEnd1 = nextIndexOfChar (text, "!?.", offset); - if (sentenceEnd1 is -1) { - startBounds = endBounds = length; - break; - } - sentenceEnd1 = nextIndexOfNotChar (text, "!?.", sentenceEnd1); - if (sentenceEnd1 is length) { - startBounds = endBounds = length; - break; - } - startBounds = sentenceEnd1; - int sentenceEnd2 = nextIndexOfNotChar (text, " \n", sentenceEnd1); - if (sentenceEnd2 is length) { - startBounds = endBounds = length; - break; - } - sentenceEnd2 = nextIndexOfChar (text, "!?.", sentenceEnd2); - if (sentenceEnd2 is -1) { - endBounds = length; - break; - } - endBounds = nextIndexOfNotChar (text, "!?.", sentenceEnd2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_START: { - int lineStart1 = locate( text, '\n' ); + if (DEBUG) Stdout.formatln ("-->atkText_get_text_after_offset"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + int offset = cast(int)/*64*/offset_value; + char[] text = object.getText (); + if (text.length > 0) { + int length = text.length ; + offset = Math.min (offset, length - 1); + int startBounds = offset; + int endBounds = offset; + switch (cast(int)/*64*/boundary_type) { + case ATK.ATK_TEXT_BOUNDARY_CHAR: { + if (length > offset) endBounds++; + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_START: { + int wordStart1 = nextIndexOfChar (text, " !?.\n", offset - 1); + if (wordStart1 is -1) { + startBounds = endBounds = length; + break; + } + wordStart1 = nextIndexOfNotChar (text, " !?.\n", wordStart1); + if (wordStart1 is length) { + startBounds = endBounds = length; + break; + } + startBounds = wordStart1; + int wordStart2 = nextIndexOfChar (text, " !?.\n", wordStart1); + if (wordStart2 is -1) { + endBounds = length; + break; + } + endBounds = nextIndexOfNotChar (text, " !?.\n", wordStart2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_END: { + int previousWordEnd = previousIndexOfNotChar (text, " \n", offset); + if (previousWordEnd is -1 || previousWordEnd !is offset - 1) { + offset = nextIndexOfNotChar (text, " \n", offset); + } + if (offset is -1) { + startBounds = endBounds = length; + break; + } + int wordEnd1 = nextIndexOfChar (text, " !?.\n", cast(int)/*64*/offset); + if (wordEnd1 is -1) { + startBounds = endBounds = length; + break; + } + wordEnd1 = nextIndexOfNotChar (text, "!?.", wordEnd1); + if (wordEnd1 is length) { + startBounds = endBounds = length; + break; + } + startBounds = wordEnd1; + int wordEnd2 = nextIndexOfNotChar (text, " \n", wordEnd1); + if (wordEnd2 is length) { + startBounds = endBounds = length; + break; + } + wordEnd2 = nextIndexOfChar (text, " !?.\n", wordEnd2); + if (wordEnd2 is -1) { + endBounds = length; + break; + } + endBounds = nextIndexOfNotChar (text, "!?.", wordEnd2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { + int previousSentenceEnd = previousIndexOfChar (text, "!?.", offset); + int previousText = previousIndexOfNotChar (text, " !?.\n", offset); + int sentenceStart1 = 0; + if (previousSentenceEnd >= previousText) { + sentenceStart1 = nextIndexOfNotChar (text, " !?.\n", offset); + } else { + sentenceStart1 = nextIndexOfChar (text, "!?.", offset); + if (sentenceStart1 is -1) { + startBounds = endBounds = length; + break; + } + sentenceStart1 = nextIndexOfNotChar (text, " !?.\n", sentenceStart1); + } + if (sentenceStart1 is length) { + startBounds = endBounds = length; + break; + } + startBounds = sentenceStart1; + int sentenceStart2 = nextIndexOfChar (text, "!?.", sentenceStart1); + if (sentenceStart2 is -1) { + endBounds = length; + break; + } + endBounds = nextIndexOfNotChar (text, " !?.\n", sentenceStart2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { + int sentenceEnd1 = nextIndexOfChar (text, "!?.", offset); + if (sentenceEnd1 is -1) { + startBounds = endBounds = length; + break; + } + sentenceEnd1 = nextIndexOfNotChar (text, "!?.", sentenceEnd1); + if (sentenceEnd1 is length) { + startBounds = endBounds = length; + break; + } + startBounds = sentenceEnd1; + int sentenceEnd2 = nextIndexOfNotChar (text, " \n", sentenceEnd1); + if (sentenceEnd2 is length) { + startBounds = endBounds = length; + break; + } + sentenceEnd2 = nextIndexOfChar (text, "!?.", sentenceEnd2); + if (sentenceEnd2 is -1) { + endBounds = length; + break; + } + endBounds = nextIndexOfNotChar (text, "!?.", sentenceEnd2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_START: { + int lineStart1 = locate( text, '\n' ); if( lineStart1 == text.length ) lineStart1 = -1; - if (lineStart1 is -1) { - startBounds = endBounds = length; - break; - } - lineStart1 = nextIndexOfNotChar (text, "\n", lineStart1); - if (lineStart1 is length) { - startBounds = endBounds = length; - break; - } - startBounds = lineStart1; - int lineStart2 = locate( text, '\n' ); + if (lineStart1 is -1) { + startBounds = endBounds = length; + break; + } + lineStart1 = nextIndexOfNotChar (text, "\n", lineStart1); + if (lineStart1 is length) { + startBounds = endBounds = length; + break; + } + startBounds = lineStart1; + int lineStart2 = locate( text, '\n' ); if( lineStart2 == text.length ) lineStart2 = -1; - if (lineStart2 is -1) { - endBounds = length; - break; - } - lineStart2 = nextIndexOfNotChar (text, "\n", lineStart2); - endBounds = lineStart2; - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_END: { - int lineEnd1 = nextIndexOfChar (text, "\n", offset); - if (lineEnd1 is -1) { - startBounds = endBounds = length; - break; - } - startBounds = lineEnd1; - if (startBounds is length) { - endBounds = length; - break; - } - int lineEnd2 = nextIndexOfChar (text, "\n", lineEnd1 + 1); - if (lineEnd2 is -1) { - endBounds = length; - break; - } - endBounds = lineEnd2; - break; - } + if (lineStart2 is -1) { + endBounds = length; + break; + } + lineStart2 = nextIndexOfNotChar (text, "\n", lineStart2); + endBounds = lineStart2; + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_END: { + int lineEnd1 = nextIndexOfChar (text, "\n", offset); + if (lineEnd1 is -1) { + startBounds = endBounds = length; + break; + } + startBounds = lineEnd1; + if (startBounds is length) { + endBounds = length; + break; + } + int lineEnd2 = nextIndexOfChar (text, "\n", lineEnd1 + 1); + if (lineEnd2 is -1) { + endBounds = length; + break; + } + endBounds = lineEnd2; + break; + } default: - } - *start_offset=startBounds; - *end_offset=endBounds; - text = text[startBounds .. endBounds ]; - auto result = cast(char*)OS.g_malloc (text.length+1); + } + *start_offset=startBounds; + *end_offset=endBounds; + text = text[startBounds .. endBounds ]; + auto result = cast(char*)OS.g_malloc (text.length+1); result[ 0 .. text.length ] = text; result[ text.length ] = '\0'; - return result; - } - return null; - } + return result; + } + return null; + } - package static extern(C) char* atkText_get_text_at_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { + package static extern(C) char* atkText_get_text_at_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_text_at_offset: {} start: {} end: {}", offset_value, start_offset, end_offset); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - int offset = offset_value; - char[] text = object.getText (); - if (text.length > 0) { - int length = text.length; - offset = Math.min (offset, length - 1); - int startBounds = offset; - int endBounds = offset; - switch (boundary_type) { - case ATK.ATK_TEXT_BOUNDARY_CHAR: { - if (length > offset) endBounds++; - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_START: { - int wordStart1 = previousIndexOfNotChar (text, " !?.\n", offset); - if (wordStart1 is -1) { - startBounds = endBounds = 0; - break; - } - wordStart1 = previousIndexOfChar (text, " !?.\n", wordStart1) + 1; - if (wordStart1 is -1) { - startBounds = 0; - break; - } - startBounds = wordStart1; - int wordStart2 = nextIndexOfChar (text, " !?.\n", wordStart1); - endBounds = nextIndexOfNotChar (text, " !?.\n", wordStart2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_END: { - int wordEnd1 = previousIndexOfNotChar (text, "!?.", offset + 1); - wordEnd1 = previousIndexOfChar (text, " !?.\n", wordEnd1); - wordEnd1 = previousIndexOfNotChar (text, " \n", wordEnd1 + 1); - if (wordEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - startBounds = wordEnd1 + 1; - int wordEnd2 = nextIndexOfNotChar (text, " \n", startBounds); - if (wordEnd2 is length) { - endBounds = startBounds; - break; - } - wordEnd2 = nextIndexOfChar (text, " !?.\n", wordEnd2); - if (wordEnd2 is -1) { - endBounds = startBounds; - break; - } - endBounds = nextIndexOfNotChar (text, "!?.", wordEnd2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { - int sentenceStart1 = previousIndexOfNotChar (text, " !?.\n", offset + 1); - if (sentenceStart1 is -1) { - startBounds = endBounds = 0; - break; - } - sentenceStart1 = previousIndexOfChar (text, "!?.", sentenceStart1) + 1; - startBounds = nextIndexOfNotChar (text, " \n", sentenceStart1); - int sentenceStart2 = nextIndexOfChar (text, "!?.", startBounds); - endBounds = nextIndexOfNotChar (text, " !?.\n", sentenceStart2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { - int sentenceEnd1 = previousIndexOfNotChar (text, "!?.", offset + 1); - sentenceEnd1 = previousIndexOfChar (text, "!?.", sentenceEnd1); - sentenceEnd1 = previousIndexOfNotChar (text, " \n", sentenceEnd1 + 1); - if (sentenceEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - startBounds = sentenceEnd1 + 1; - int sentenceEnd2 = nextIndexOfNotChar (text, " \n", startBounds); - if (sentenceEnd2 is length) { - endBounds = startBounds; - break; - } - sentenceEnd2 = nextIndexOfChar (text, "!?.", sentenceEnd2); - if (sentenceEnd2 is -1) { - endBounds = startBounds; - break; - } - endBounds = nextIndexOfNotChar (text, "!?.", sentenceEnd2); - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_START: { - startBounds = previousIndexOfChar (text, "\n", offset) + 1; - int lineEnd2 = nextIndexOfChar (text, "\n", startBounds); - if (lineEnd2 < length) lineEnd2++; - endBounds = lineEnd2; - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_END: { - int lineEnd1 = previousIndexOfChar (text, "\n", offset); - if (lineEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - startBounds = lineEnd1; - endBounds = nextIndexOfChar (text, "\n", lineEnd1 + 1); - } + if (DEBUG) Stdout.formatln ("-->atkText_get_text_at_offset: {} start: {} end: {}", offset_value, start_offset, end_offset); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + int offset = offset_value; + char[] text = object.getText (); + if (text.length > 0) { + int length = text.length; + offset = Math.min (offset, length - 1); + int startBounds = offset; + int endBounds = offset; + switch (boundary_type) { + case ATK.ATK_TEXT_BOUNDARY_CHAR: { + if (length > offset) endBounds++; + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_START: { + int wordStart1 = previousIndexOfNotChar (text, " !?.\n", offset); + if (wordStart1 is -1) { + startBounds = endBounds = 0; + break; + } + wordStart1 = previousIndexOfChar (text, " !?.\n", wordStart1) + 1; + if (wordStart1 is -1) { + startBounds = 0; + break; + } + startBounds = wordStart1; + int wordStart2 = nextIndexOfChar (text, " !?.\n", wordStart1); + endBounds = nextIndexOfNotChar (text, " !?.\n", wordStart2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_END: { + int wordEnd1 = previousIndexOfNotChar (text, "!?.", offset + 1); + wordEnd1 = previousIndexOfChar (text, " !?.\n", wordEnd1); + wordEnd1 = previousIndexOfNotChar (text, " \n", wordEnd1 + 1); + if (wordEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + startBounds = wordEnd1 + 1; + int wordEnd2 = nextIndexOfNotChar (text, " \n", startBounds); + if (wordEnd2 is length) { + endBounds = startBounds; + break; + } + wordEnd2 = nextIndexOfChar (text, " !?.\n", wordEnd2); + if (wordEnd2 is -1) { + endBounds = startBounds; + break; + } + endBounds = nextIndexOfNotChar (text, "!?.", wordEnd2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { + int sentenceStart1 = previousIndexOfNotChar (text, " !?.\n", offset + 1); + if (sentenceStart1 is -1) { + startBounds = endBounds = 0; + break; + } + sentenceStart1 = previousIndexOfChar (text, "!?.", sentenceStart1) + 1; + startBounds = nextIndexOfNotChar (text, " \n", sentenceStart1); + int sentenceStart2 = nextIndexOfChar (text, "!?.", startBounds); + endBounds = nextIndexOfNotChar (text, " !?.\n", sentenceStart2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { + int sentenceEnd1 = previousIndexOfNotChar (text, "!?.", offset + 1); + sentenceEnd1 = previousIndexOfChar (text, "!?.", sentenceEnd1); + sentenceEnd1 = previousIndexOfNotChar (text, " \n", sentenceEnd1 + 1); + if (sentenceEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + startBounds = sentenceEnd1 + 1; + int sentenceEnd2 = nextIndexOfNotChar (text, " \n", startBounds); + if (sentenceEnd2 is length) { + endBounds = startBounds; + break; + } + sentenceEnd2 = nextIndexOfChar (text, "!?.", sentenceEnd2); + if (sentenceEnd2 is -1) { + endBounds = startBounds; + break; + } + endBounds = nextIndexOfNotChar (text, "!?.", sentenceEnd2); + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_START: { + startBounds = previousIndexOfChar (text, "\n", offset) + 1; + int lineEnd2 = nextIndexOfChar (text, "\n", startBounds); + if (lineEnd2 < length) lineEnd2++; + endBounds = lineEnd2; + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_END: { + int lineEnd1 = previousIndexOfChar (text, "\n", offset); + if (lineEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + startBounds = lineEnd1; + endBounds = nextIndexOfChar (text, "\n", lineEnd1 + 1); + } default: - } - *start_offset=startBounds; - *end_offset=endBounds; - text = text[startBounds .. endBounds]; - auto result = cast(char*) OS.g_malloc (text.length+1); + } + *start_offset=startBounds; + *end_offset=endBounds; + text = text[startBounds .. endBounds]; + auto result = cast(char*) OS.g_malloc (text.length+1); result[ 0 .. text.length ] = text; result[ text.length ] = '\0'; - return result; - } - return null; - } + return result; + } + return null; + } - package static extern(C) char* atkText_get_text_before_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { + package static extern(C) char* atkText_get_text_before_offset (void* obj, int offset_value, int boundary_type, int* start_offset, int* end_offset) { auto atkObject = cast(AtkObject*)obj; - if (DEBUG) Stdout.formatln ("-->atkText_get_text_before_offset"); - AccessibleObject object = getAccessibleObject (atkObject); - if (object is null) return null; - int offset = offset_value; - char[] text = object.getText (); - if (text.length > 0) { - int length = text.length; - offset = Math.min (offset, length - 1); - int startBounds = offset; - int endBounds = offset; - switch (boundary_type) { - case ATK.ATK_TEXT_BOUNDARY_CHAR: { - if (length >= offset && offset > 0) startBounds--; - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_START: { - int wordStart1 = previousIndexOfChar (text, " !?.\n", offset - 1); - if (wordStart1 is -1) { - startBounds = endBounds = 0; - break; - } - int wordStart2 = previousIndexOfNotChar (text, " !?.\n", wordStart1); - if (wordStart2 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = wordStart1 + 1; - startBounds = previousIndexOfChar (text, " !?.\n", wordStart2) + 1; - break; - } - case ATK.ATK_TEXT_BOUNDARY_WORD_END: { - int wordEnd1 =previousIndexOfChar (text, " !?.\n", offset); - if (wordEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - wordEnd1 = previousIndexOfNotChar (text, " \n", wordEnd1 + 1); - if (wordEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = wordEnd1 + 1; - int wordEnd2 = previousIndexOfNotChar (text, " !?.\n", endBounds); - wordEnd2 = previousIndexOfChar (text, " !?.\n", wordEnd2); - if (wordEnd2 is -1) { - startBounds = 0; - break; - } - startBounds = previousIndexOfNotChar (text, " \n", wordEnd2 + 1) + 1; - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { - int sentenceStart1 = previousIndexOfChar (text, "!?.", offset); - if (sentenceStart1 is -1) { - startBounds = endBounds = 0; - break; - } - int sentenceStart2 = previousIndexOfNotChar (text, "!?.", sentenceStart1); - if (sentenceStart2 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = sentenceStart1 + 1; - startBounds = previousIndexOfChar (text, "!?.", sentenceStart2) + 1; - break; - } - case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { - int sentenceEnd1 = previousIndexOfChar (text, "!?.", offset); - if (sentenceEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - sentenceEnd1 = previousIndexOfNotChar (text, " \n", sentenceEnd1 + 1); - if (sentenceEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = sentenceEnd1 + 1; - int sentenceEnd2 = previousIndexOfNotChar (text, "!?.", endBounds); - sentenceEnd2 = previousIndexOfChar (text, "!?.", sentenceEnd2); - if (sentenceEnd2 is -1) { - startBounds = 0; - break; - } - startBounds = previousIndexOfNotChar (text, " \n", sentenceEnd2 + 1) + 1; - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_START: { - int lineStart1 = previousIndexOfChar (text, "\n", offset); - if (lineStart1 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = lineStart1 + 1; - startBounds = previousIndexOfChar (text, "\n", lineStart1) + 1; - break; - } - case ATK.ATK_TEXT_BOUNDARY_LINE_END: { - int lineEnd1 = previousIndexOfChar (text, "\n", offset); - if (lineEnd1 is -1) { - startBounds = endBounds = 0; - break; - } - endBounds = lineEnd1; - startBounds = previousIndexOfChar (text, "\n", lineEnd1); - if (startBounds is -1) startBounds = 0; - break; - } + if (DEBUG) Stdout.formatln ("-->atkText_get_text_before_offset"); + AccessibleObject object = getAccessibleObject (atkObject); + if (object is null) return null; + int offset = offset_value; + char[] text = object.getText (); + if (text.length > 0) { + int length = text.length; + offset = Math.min (offset, length - 1); + int startBounds = offset; + int endBounds = offset; + switch (boundary_type) { + case ATK.ATK_TEXT_BOUNDARY_CHAR: { + if (length >= offset && offset > 0) startBounds--; + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_START: { + int wordStart1 = previousIndexOfChar (text, " !?.\n", offset - 1); + if (wordStart1 is -1) { + startBounds = endBounds = 0; + break; + } + int wordStart2 = previousIndexOfNotChar (text, " !?.\n", wordStart1); + if (wordStart2 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = wordStart1 + 1; + startBounds = previousIndexOfChar (text, " !?.\n", wordStart2) + 1; + break; + } + case ATK.ATK_TEXT_BOUNDARY_WORD_END: { + int wordEnd1 =previousIndexOfChar (text, " !?.\n", offset); + if (wordEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + wordEnd1 = previousIndexOfNotChar (text, " \n", wordEnd1 + 1); + if (wordEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = wordEnd1 + 1; + int wordEnd2 = previousIndexOfNotChar (text, " !?.\n", endBounds); + wordEnd2 = previousIndexOfChar (text, " !?.\n", wordEnd2); + if (wordEnd2 is -1) { + startBounds = 0; + break; + } + startBounds = previousIndexOfNotChar (text, " \n", wordEnd2 + 1) + 1; + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_START: { + int sentenceStart1 = previousIndexOfChar (text, "!?.", offset); + if (sentenceStart1 is -1) { + startBounds = endBounds = 0; + break; + } + int sentenceStart2 = previousIndexOfNotChar (text, "!?.", sentenceStart1); + if (sentenceStart2 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = sentenceStart1 + 1; + startBounds = previousIndexOfChar (text, "!?.", sentenceStart2) + 1; + break; + } + case ATK.ATK_TEXT_BOUNDARY_SENTENCE_END: { + int sentenceEnd1 = previousIndexOfChar (text, "!?.", offset); + if (sentenceEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + sentenceEnd1 = previousIndexOfNotChar (text, " \n", sentenceEnd1 + 1); + if (sentenceEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = sentenceEnd1 + 1; + int sentenceEnd2 = previousIndexOfNotChar (text, "!?.", endBounds); + sentenceEnd2 = previousIndexOfChar (text, "!?.", sentenceEnd2); + if (sentenceEnd2 is -1) { + startBounds = 0; + break; + } + startBounds = previousIndexOfNotChar (text, " \n", sentenceEnd2 + 1) + 1; + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_START: { + int lineStart1 = previousIndexOfChar (text, "\n", offset); + if (lineStart1 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = lineStart1 + 1; + startBounds = previousIndexOfChar (text, "\n", lineStart1) + 1; + break; + } + case ATK.ATK_TEXT_BOUNDARY_LINE_END: { + int lineEnd1 = previousIndexOfChar (text, "\n", offset); + if (lineEnd1 is -1) { + startBounds = endBounds = 0; + break; + } + endBounds = lineEnd1; + startBounds = previousIndexOfChar (text, "\n", lineEnd1); + if (startBounds is -1) startBounds = 0; + break; + } default: - } - *start_offset=startBounds; - *end_offset=endBounds; - text = text[startBounds .. endBounds]; - auto result = cast(char*)OS.g_malloc (text.length+1); + } + *start_offset=startBounds; + *end_offset=endBounds; + text = text[startBounds .. endBounds]; + auto result = cast(char*)OS.g_malloc (text.length+1); result[ 0 .. text.length ] = text; result[ text.length ] = '\0'; - return result; - } - return null; - } + return result; + } + return null; + } - AccessibleListener[] getAccessibleListeners () { - if (accessible is null) return new AccessibleListener [0]; - AccessibleListener[] result = accessible.getAccessibleListeners (); - return result !is null ? result : new AccessibleListener [0]; - } + AccessibleListener[] getAccessibleListeners () { + if (accessible is null) return new AccessibleListener [0]; + AccessibleListener[] result = accessible.getAccessibleListeners (); + return result !is null ? result : new AccessibleListener [0]; + } - static AccessibleObject getAccessibleObject (AtkObject* atkObject) { - return AccessibleObjects[atkObject]; - } + static AccessibleObject getAccessibleObject (AtkObject* atkObject) { + return AccessibleObjects[atkObject]; + } - AccessibleObject getChildByHandle (AtkObject* handle) { - return children[handle]; - } + AccessibleObject getChildByHandle (AtkObject* handle) { + return children[handle]; + } - AccessibleObject getChildByID (int childId) { - if (childId is ACC.CHILDID_SELF) return this; - foreach( object; children ){ - if (object.id is childId) return object; - } - return null; - } + AccessibleObject getChildByID (int childId) { + if (childId is ACC.CHILDID_SELF) return this; + foreach( object; children ){ + if (object.id is childId) return object; + } + return null; + } - AccessibleObject getChildByIndex (int childIndex) { + AccessibleObject getChildByIndex (int childIndex) { foreach( object; children ){ - if (object.index is childIndex) return object; - } - return null; - } + if (object.index is childIndex) return object; + } + return null; + } - AccessibleControlListener[] getControlListeners () { - if (accessible is null) return new AccessibleControlListener [0]; - AccessibleControlListener[] result = accessible.getControlListeners (); - return result !is null ? result : new AccessibleControlListener [0]; - } + AccessibleControlListener[] getControlListeners () { + if (accessible is null) return new AccessibleControlListener [0]; + AccessibleControlListener[] result = accessible.getControlListeners (); + return result !is null ? result : new AccessibleControlListener [0]; + } - char[] getText () { - char* parentResult; - char[] parentText = ""; //$NON-NLS-1$ - if (ATK.g_type_is_a (parentType, ATK_TEXT_TYPE)) { - auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (handle)); - int /*long*/ characterCount = 0; - if (textIface.get_character_count !is null) { - characterCount = textIface.get_character_count( handle); - } - if (characterCount > 0 && textIface.get_text !is null) { - parentResult = textIface.get_text( handle, 0, characterCount); - if (parentResult !is null) { - parentText = fromUtf8z( parentResult ).dup; - } - } - } - AccessibleControlListener[] controlListeners = getControlListeners (); - if (controlListeners.length is 0) return parentText; - AccessibleControlEvent event = new AccessibleControlEvent (this); - event.childID = id; - event.result = parentText; - for (int i = 0; i < controlListeners.length; i++) { - controlListeners [i].getValue (event); - } - return event.result; - } + char[] getText () { + char* parentResult; + char[] parentText = ""; //$NON-NLS-1$ + if (ATK.g_type_is_a (parentType, ATK_TEXT_TYPE)) { + auto textIface = cast(AtkTextIface*)ATK.g_type_interface_peek_parent (ATK.ATK_TEXT_GET_IFACE (handle)); + int /*long*/ characterCount = 0; + if (textIface.get_character_count !is null) { + characterCount = textIface.get_character_count( handle); + } + if (characterCount > 0 && textIface.get_text !is null) { + parentResult = textIface.get_text( handle, 0, characterCount); + if (parentResult !is null) { + parentText = fromUtf8z( parentResult ).dup; + } + } + } + AccessibleControlListener[] controlListeners = getControlListeners (); + if (controlListeners.length is 0) return parentText; + AccessibleControlEvent event = new AccessibleControlEvent (this); + event.childID = id; + event.result = parentText; + for (int i = 0; i < controlListeners.length; i++) { + controlListeners [i].getValue (event); + } + return event.result; + } - AccessibleTextListener[] getTextListeners () { - if (accessible is null) return new AccessibleTextListener [0]; - AccessibleTextListener[] result = accessible.getTextListeners (); - return result !is null ? result : new AccessibleTextListener [0]; - } + AccessibleTextListener[] getTextListeners () { + if (accessible is null) return new AccessibleTextListener [0]; + AccessibleTextListener[] result = accessible.getTextListeners (); + return result !is null ? result : new AccessibleTextListener [0]; + } - private static extern(C) void gObjectClass_finalize (GObject* atkObject) { - auto superType = ATK.g_type_class_peek_parent (ATK.G_OBJECT_GET_CLASS (cast(GTypeInstance*)atkObject)); - auto objectClassStruct = cast(GObjectClass*)ATK.G_OBJECT_CLASS (cast(GTypeClass*)superType); - objectClassStruct.finalize(atkObject); - AccessibleObject object = getAccessibleObject (cast(AtkObject*)atkObject); - if (object !is null) { - AccessibleObjects.remove (cast(AtkObject*)atkObject); - object.release (); - } - } + private static extern(C) void gObjectClass_finalize (GObject* atkObject) { + auto superType = ATK.g_type_class_peek_parent (ATK.G_OBJECT_GET_CLASS (cast(GTypeInstance*)atkObject)); + auto objectClassStruct = cast(GObjectClass*)ATK.G_OBJECT_CLASS (cast(GTypeClass*)superType); + objectClassStruct.finalize(atkObject); + AccessibleObject object = getAccessibleObject (cast(AtkObject*)atkObject); + if (object !is null) { + AccessibleObjects.remove (cast(AtkObject*)atkObject); + object.release (); + } + } - static int nextIndexOfChar (char[] string, char[] searchChars, int startIndex) { - int result = string.length; - for (int i = 0; i < searchChars.length; i++) { - char current = searchChars[i]; - int index = locate( string, current, startIndex ); - if (index !is string.length ) result = Math.min (result, index); - } - return result; - } + static int nextIndexOfChar (char[] string, char[] searchChars, int startIndex) { + int result = string.length; + for (int i = 0; i < searchChars.length; i++) { + char current = searchChars[i]; + int index = locate( string, current, startIndex ); + if (index !is string.length ) result = Math.min (result, index); + } + return result; + } - static int nextIndexOfNotChar (char[] string, char[] searchChars, int startIndex) { - int length = string.length; - int index = startIndex; - while (index < length) { - char current = string[index]; - if ( !contains( searchChars, current)) break; - index++; - } - return index; - } + static int nextIndexOfNotChar (char[] string, char[] searchChars, int startIndex) { + int length = string.length; + int index = startIndex; + while (index < length) { + char current = string[index]; + if ( !contains( searchChars, current)) break; + index++; + } + return index; + } - static int previousIndexOfChar (char[] string, char[] searchChars, int startIndex) { - int result = -1; - if (startIndex < 0) return result; - string = string[0 .. startIndex]; - for (int i = 0; i < searchChars.length ; i++) { - char current = searchChars[i]; - int index = locatePrior( string, current); - if (index !is string.length ) result = Math.max (result, index); - } - return result; - } + static int previousIndexOfChar (char[] string, char[] searchChars, int startIndex) { + int result = -1; + if (startIndex < 0) return result; + string = string[0 .. startIndex]; + for (int i = 0; i < searchChars.length ; i++) { + char current = searchChars[i]; + int index = locatePrior( string, current); + if (index !is string.length ) result = Math.max (result, index); + } + return result; + } - static int previousIndexOfNotChar (char[] string, char[] searchChars, int startIndex) { - if (startIndex < 0) return -1; - int index = startIndex - 1; - while (index >= 0) { - char current = string[index]; - if ( !contains(searchChars, current)) break; - index--; - } - return index; - } + static int previousIndexOfNotChar (char[] string, char[] searchChars, int startIndex) { + if (startIndex < 0) return -1; + int index = startIndex - 1; + while (index >= 0) { + char current = string[index]; + if ( !contains(searchChars, current)) break; + index--; + } + return index; + } - void release () { - if (DEBUG) Stdout.formatln("AccessibleObject.release: {}", handle); - accessible = null; + void release () { + if (DEBUG) Stdout.formatln("AccessibleObject.release: {}", handle); + accessible = null; foreach( child; children ){ - if (child.isLightweight) OS.g_object_unref (child.handle); - } - if (parent !is null) parent.removeChild (this, false); - } + if (child.isLightweight) OS.g_object_unref (child.handle); + } + if (parent !is null) parent.removeChild (this, false); + } - void removeChild (AccessibleObject child, bool unref) { - children.remove (child.handle); - if (unref && child.isLightweight) OS.g_object_unref (child.handle); - } + void removeChild (AccessibleObject child, bool unref) { + children.remove (child.handle); + if (unref && child.isLightweight) OS.g_object_unref (child.handle); + } - void selectionChanged () { - OS.g_signal_emit_by_name0 (handle, ATK.selection_changed.ptr); - } + void selectionChanged () { + OS.g_signal_emit_by_name0 (handle, ATK.selection_changed.ptr); + } - void setFocus (int childID) { - updateChildren (); - AccessibleObject accObject = getChildByID (childID); - if (accObject !is null) { - ATK.atk_focus_tracker_notify (accObject.handle); - } - } + void setFocus (int childID) { + updateChildren (); + AccessibleObject accObject = getChildByID (childID); + if (accObject !is null) { + ATK.atk_focus_tracker_notify (accObject.handle); + } + } - void setParent (AccessibleObject parent) { - this.parent = parent; - } + void setParent (AccessibleObject parent) { + this.parent = parent; + } - void textCaretMoved(int index) { - OS.g_signal_emit_by_name1 (handle, ATK.text_caret_moved.ptr, index); - } + void textCaretMoved(int index) { + OS.g_signal_emit_by_name1 (handle, ATK.text_caret_moved.ptr, index); + } - void textChanged(int type, int startIndex, int length) { - if (type is ACC.TEXT_DELETE) { - OS.g_signal_emit_by_name2 (handle, ATK.text_changed_delete.ptr, startIndex, length); - } else { - OS.g_signal_emit_by_name2 (handle, ATK.text_changed_insert.ptr, startIndex, length); - } - } + void textChanged(int type, int startIndex, int length) { + if (type is ACC.TEXT_DELETE) { + OS.g_signal_emit_by_name2 (handle, ATK.text_changed_delete.ptr, startIndex, length); + } else { + OS.g_signal_emit_by_name2 (handle, ATK.text_changed_insert.ptr, startIndex, length); + } + } - void textSelectionChanged() { - OS.g_signal_emit_by_name0 (handle, ATK.text_selection_changed.ptr); - } + void textSelectionChanged() { + OS.g_signal_emit_by_name0 (handle, ATK.text_selection_changed.ptr); + } - void updateChildren () { - if (isLightweight) return; - AccessibleControlListener[] listeners = getControlListeners (); - if (listeners.length is 0) return; + void updateChildren () { + if (isLightweight) return; + AccessibleControlListener[] listeners = getControlListeners (); + if (listeners.length is 0) return; - AccessibleControlEvent event = new AccessibleControlEvent (this); - for (int i = 0; i < listeners.length; i++) { - listeners [i].getChildren (event); - } - if (event.children !is null && event.children.length > 0) { - AtkObject*[] idsToKeep = new AtkObject*[]( children.length ); + AccessibleControlEvent event = new AccessibleControlEvent (this); + for (int i = 0; i < listeners.length; i++) { + listeners [i].getChildren (event); + } + if (event.children !is null && event.children.length > 0) { + AtkObject*[] idsToKeep = new AtkObject*[]( children.length ); idsToKeep.length = 0; - if ( null !is (cast(Integer)event.children[0] )) { - /* an array of child id's (Integers) was answered */ - auto parentType = AccessibleFactory.getDefaultParentType (); - for (int i = 0; i < event.children.length; i++) { - AccessibleObject object = getChildByIndex (i); - if (object is null) { - auto childType = AccessibleFactory.getChildType (accessible, i); - object = new AccessibleObject (childType, null, accessible, parentType, true); - AccessibleObjects[object.handle] = object; - addChild (object); - object.index = i; - } + if ( null !is (cast(Integer)event.children[0] )) { + /* an array of child id's (Integers) was answered */ + auto parentType = AccessibleFactory.getDefaultParentType (); + for (int i = 0; i < event.children.length; i++) { + AccessibleObject object = getChildByIndex (i); + if (object is null) { + auto childType = AccessibleFactory.getChildType (accessible, i); + object = new AccessibleObject (childType, null, accessible, parentType, true); + AccessibleObjects[object.handle] = object; + addChild (object); + object.index = i; + } if( auto intChild = cast(Integer)event.children[i] ){ object.id = intChild.intValue (); } else { - /* a non-ID value was given so don't set the ID */ - } - idsToKeep ~= object.handle; - } - } else { - /* an array of Accessible children was answered */ - int childIndex = 0; - for (int i = 0; i < event.children.length; i++) { - AccessibleObject object = null; + /* a non-ID value was given so don't set the ID */ + } + idsToKeep ~= object.handle; + } + } else { + /* an array of Accessible children was answered */ + int childIndex = 0; + for (int i = 0; i < event.children.length; i++) { + AccessibleObject object = null; if( auto accChild = cast(Accessible)event.children[i] ){ - object = accChild.accessibleObject; - } else { - /* a non-Accessible value was given so nothing to do here */ - } - if (object !is null) { - object.index = childIndex++; + object = accChild.accessibleObject; + } else { + /* a non-Accessible value was given so nothing to do here */ + } + if (object !is null) { + object.index = childIndex++; idsToKeep ~= object.handle; - } - } - } - /* remove old children that were not provided as children anymore */ - foreach( id; children.keys ){ - if ( !tango.core.Array.contains( idsToKeep, id )) { - AccessibleObject object = cast(AccessibleObject) children[id]; - removeChild (object, true); - } - } - } - } + } + } + } + /* remove old children that were not provided as children anymore */ + foreach( id; children.keys ){ + if ( !tango.core.Array.contains( idsToKeep, id )) { + AccessibleObject object = cast(AccessibleObject) children[id]; + removeChild (object, true); + } + } + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleTextAdapter.d --- a/dwt/accessibility/AccessibleTextAdapter.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleTextAdapter.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -40,38 +40,38 @@ */ public abstract class AccessibleTextAdapter : AccessibleTextListener { - /** - * Sent when an accessibility client requests the current character offset - * of the text caret. - * The default behavior is to do nothing. - *

- * Return the caret offset in the offset - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getCaretOffset (AccessibleTextEvent e) { - } + /** + * Sent when an accessibility client requests the current character offset + * of the text caret. + * The default behavior is to do nothing. + *

+ * Return the caret offset in the offset + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getCaretOffset (AccessibleTextEvent e) { + } - /** - * Sent when an accessibility client requests the range of the current - * text selection. - * The default behavior is to do nothing. - *

- * Return the selection start offset and non-negative length in the - * offset and length fields of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getSelectionRange (AccessibleTextEvent e) { - } + /** + * Sent when an accessibility client requests the range of the current + * text selection. + * The default behavior is to do nothing. + *

+ * Return the selection start offset and non-negative length in the + * offset and length fields of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getSelectionRange (AccessibleTextEvent e) { + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleTextEvent.d --- a/dwt/accessibility/AccessibleTextEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleTextEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -31,10 +31,10 @@ * @since 3.0 */ public class AccessibleTextEvent : SWTEventObject { - public int childID; // IN - public int offset, length; // OUT + public int childID; // IN + public int offset, length; // OUT - //static final long serialVersionUID = 3977019530868308275L; + //static final long serialVersionUID = 3977019530868308275L; /** * Constructs a new instance of this class. @@ -42,7 +42,7 @@ * @param source the object that fired the event */ public this (Object source) { - super (source); + super (source); } /** @@ -52,9 +52,9 @@ * @return a string representation of the event */ public char[] toString () { - return Format( "AccessibleTextEvent {{childID={} offset={} length={}}", + return Format( "AccessibleTextEvent {{childID={} offset={} length={}}", childID, - offset, - length); + offset, + length); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/accessibility/AccessibleTextListener.d --- a/dwt/accessibility/AccessibleTextListener.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/accessibility/AccessibleTextListener.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -43,34 +43,34 @@ */ public interface AccessibleTextListener : SWTEventListener { - /** - * Sent when an accessibility client requests the current character offset - * of the text caret. - *

- * Return the caret offset in the offset - * field of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getCaretOffset (AccessibleTextEvent e); + /** + * Sent when an accessibility client requests the current character offset + * of the text caret. + *

+ * Return the caret offset in the offset + * field of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getCaretOffset (AccessibleTextEvent e); - /** - * Sent when an accessibility client requests the range of the current - * text selection. - *

- * Return the selection start offset and non-negative length in the - * offset and length fields of the event object. - *

- * - * @param e an event object containing the following fields: - */ - public void getSelectionRange (AccessibleTextEvent e); + /** + * Sent when an accessibility client requests the range of the current + * text selection. + *

+ * Return the selection start offset and non-negative length in the + * offset and length fields of the event object. + *

+ * + * @param e an event object containing the following fields: + */ + public void getSelectionRange (AccessibleTextEvent e); } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/ArmEvent.d --- a/dwt/events/ArmEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/ArmEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -22,7 +22,7 @@ public final class ArmEvent : TypedEvent { - //static final long serialVersionUID = 3258126964249212217L; + //static final long serialVersionUID = 3258126964249212217L; /** * Constructs a new instance of this class based on the @@ -31,7 +31,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/ControlEvent.d --- a/dwt/events/ControlEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/ControlEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class ControlEvent : TypedEvent { - //static final long serialVersionUID = 3258132436155119161L; + //static final long serialVersionUID = 3258132436155119161L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/DisposeEvent.d --- a/dwt/events/DisposeEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/DisposeEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class DisposeEvent : TypedEvent { - //static final long serialVersionUID = 3257566187633521206L; + //static final long serialVersionUID = 3257566187633521206L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/DragDetectEvent.d --- a/dwt/events/DragDetectEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/DragDetectEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -24,7 +24,7 @@ public final class DragDetectEvent : MouseEvent { - //private static final long serialVersionUID = -7229172519733647232L; + //private static final long serialVersionUID = -7229172519733647232L; /** * Constructs a new instance of this class based on the @@ -33,6 +33,6 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/ExpandEvent.d --- a/dwt/events/ExpandEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/ExpandEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -24,9 +24,9 @@ */ public class ExpandEvent : SelectionEvent { - - //static final long serialVersionUID = 3976735856884987356L; - + + //static final long serialVersionUID = 3976735856884987356L; + /** * Constructs a new instance of this class based on the * information in the given untyped event. @@ -34,7 +34,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/FocusEvent.d --- a/dwt/events/FocusEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/FocusEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class FocusEvent : TypedEvent { - //static final long serialVersionUID = 3258134643684227381L; + //static final long serialVersionUID = 3258134643684227381L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/HelpEvent.d --- a/dwt/events/HelpEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/HelpEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class HelpEvent : TypedEvent { - //static final long serialVersionUID = 3257001038606251315L; + //static final long serialVersionUID = 3257001038606251315L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/KeyEvent.d --- a/dwt/events/KeyEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/KeyEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -37,44 +37,44 @@ public class KeyEvent : TypedEvent { - /** - * the character represented by the key that was typed. - * This is the final character that results after all modifiers have been - * applied. For example, when the user types Ctrl+A, the character value - * is 0x01. It is important that applications do not attempt to modify the - * character value based on a stateMask (such as SWT.CTRL) or the resulting - * character will not be correct. - */ - public char character; + /** + * the character represented by the key that was typed. + * This is the final character that results after all modifiers have been + * applied. For example, when the user types Ctrl+A, the character value + * is 0x01. It is important that applications do not attempt to modify the + * character value based on a stateMask (such as SWT.CTRL) or the resulting + * character will not be correct. + */ + public char character; - /** - * the key code of the key that was typed, - * as defined by the key code constants in class SWT. - * When the character field of the event is ambiguous, this field - * contains the unicode value of the original character. For example, - * typing Ctrl+M or Return both result in the character '\r' but the - * keyCode field will also contain '\r' when Return was typed. - * - * @see dwt.SWT - */ - public int keyCode; + /** + * the key code of the key that was typed, + * as defined by the key code constants in class SWT. + * When the character field of the event is ambiguous, this field + * contains the unicode value of the original character. For example, + * typing Ctrl+M or Return both result in the character '\r' but the + * keyCode field will also contain '\r' when Return was typed. + * + * @see dwt.SWT + */ + public int keyCode; - /** - * the state of the keyboard modifier keys at the time - * the event was generated, as defined by the key code - * constants in class SWT. - * - * @see dwt.SWT - */ - public int stateMask; + /** + * the state of the keyboard modifier keys at the time + * the event was generated, as defined by the key code + * constants in class SWT. + * + * @see dwt.SWT + */ + public int stateMask; - /** - * A flag indicating whether the operation should be allowed. - * Setting this field to false will cancel the operation. - */ - public bool doit; + /** + * A flag indicating whether the operation should be allowed. + * Setting this field to false will cancel the operation. + */ + public bool doit; - static final long serialVersionUID = 3256442491011412789L; + static final long serialVersionUID = 3256442491011412789L; /** * Constructs a new instance of this class based on the @@ -83,11 +83,11 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.character = e.character; - this.keyCode = e.keyCode; - this.stateMask = e.stateMask; - this.doit = e.doit; + super(e); + this.character = e.character; + this.keyCode = e.keyCode; + this.stateMask = e.stateMask; + this.doit = e.doit; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/MenuDetectEvent.d --- a/dwt/events/MenuDetectEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/MenuDetectEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -26,25 +26,25 @@ public final class MenuDetectEvent : TypedEvent { - /** - * the display-relative x coordinate of the pointer - * at the time the context menu trigger occurred - */ - public int x; + /** + * the display-relative x coordinate of the pointer + * at the time the context menu trigger occurred + */ + public int x; - /** - * the display-relative y coordinate of the pointer - * at the time the context menu trigger occurred - */ - public int y; + /** + * the display-relative y coordinate of the pointer + * at the time the context menu trigger occurred + */ + public int y; - /** - * A flag indicating whether the operation should be allowed. - * Setting this field to false will cancel the operation. - */ - public bool doit; + /** + * A flag indicating whether the operation should be allowed. + * Setting this field to false will cancel the operation. + */ + public bool doit; - //private static final long serialVersionUID = -3061660596590828941L; + //private static final long serialVersionUID = -3061660596590828941L; /** * Constructs a new instance of this class based on the @@ -53,10 +53,10 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.x = e.x; - this.y = e.y; - this.doit = e.doit; + super(e); + this.x = e.x; + this.y = e.y; + this.doit = e.doit; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/MenuEvent.d --- a/dwt/events/MenuEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/MenuEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class MenuEvent : TypedEvent { - //static final long serialVersionUID = 3258132440332383025L; + //static final long serialVersionUID = 3258132440332383025L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/ModifyEvent.d --- a/dwt/events/ModifyEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/ModifyEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class ModifyEvent : TypedEvent { - //static final long serialVersionUID = 3258129146227011891L; + //static final long serialVersionUID = 3258129146227011891L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/MouseEvent.d --- a/dwt/events/MouseEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/MouseEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -34,41 +34,41 @@ public class MouseEvent : TypedEvent { - /** - * the button that was pressed or released; 1 for the - * first button, 2 for the second button, and 3 for the - * third button, etc. - */ - public int button; + /** + * the button that was pressed or released; 1 for the + * first button, 2 for the second button, and 3 for the + * third button, etc. + */ + public int button; - /** - * the state of the keyboard modifier keys at the time - * the event was generated - */ - public int stateMask; + /** + * the state of the keyboard modifier keys at the time + * the event was generated + */ + public int stateMask; - /** - * the widget-relative, x coordinate of the pointer - * at the time the mouse button was pressed or released - */ - public int x; + /** + * the widget-relative, x coordinate of the pointer + * at the time the mouse button was pressed or released + */ + public int x; - /** - * the widget-relative, y coordinate of the pointer - * at the time the mouse button was pressed or released - */ - public int y; + /** + * the widget-relative, y coordinate of the pointer + * at the time the mouse button was pressed or released + */ + public int y; - /** - * the number times the mouse has been clicked, as defined - * by the operating system; 1 for the first click, 2 for the - * second click and so on. - * - * @since 3.3 - */ - public int count; + /** + * the number times the mouse has been clicked, as defined + * by the operating system; 1 for the first click, 2 for the + * second click and so on. + * + * @since 3.3 + */ + public int count; - //static final long serialVersionUID = 3257288037011566898L; + //static final long serialVersionUID = 3257288037011566898L; /** * Constructs a new instance of this class based on the @@ -77,12 +77,12 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.x = e.x; - this.y = e.y; - this.button = e.button; - this.stateMask = e.stateMask; - this.count = e.count; + super(e); + this.x = e.x; + this.y = e.y; + this.button = e.button; + this.stateMask = e.stateMask; + this.count = e.count; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/PaintEvent.d --- a/dwt/events/PaintEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/PaintEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -27,46 +27,46 @@ public final class PaintEvent : TypedEvent { - /** - * the graphics context to use when painting - * that is configured to use the colors, font and - * damaged region of the control. It is valid - * only during the paint and must not be disposed - */ - public GC gc; + /** + * the graphics context to use when painting + * that is configured to use the colors, font and + * damaged region of the control. It is valid + * only during the paint and must not be disposed + */ + public GC gc; - /** - * the x offset of the bounding rectangle of the - * region that requires painting - */ - public int x; + /** + * the x offset of the bounding rectangle of the + * region that requires painting + */ + public int x; - /** - * the y offset of the bounding rectangle of the - * region that requires painting - */ - public int y; + /** + * the y offset of the bounding rectangle of the + * region that requires painting + */ + public int y; - /** - * the width of the bounding rectangle of the - * region that requires painting - */ - public int width; + /** + * the width of the bounding rectangle of the + * region that requires painting + */ + public int width; - /** - * the height of the bounding rectangle of the - * region that requires painting - */ - public int height; + /** + * the height of the bounding rectangle of the + * region that requires painting + */ + public int height; - /** - * the number of following paint events which + /** + * the number of following paint events which * are pending which may always be zero on - * some platforms - */ - public int count; + * some platforms + */ + public int count; - //static final long serialVersionUID = 3256446919205992497L; + //static final long serialVersionUID = 3256446919205992497L; /** * Constructs a new instance of this class based on the @@ -75,13 +75,13 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.gc = e.gc; - this.x = e.x; - this.y = e.y; - this.width = e.width; - this.height = e.height; - this.count = e.count; + super(e); + this.gc = e.gc; + this.x = e.x; + this.y = e.y; + this.width = e.width; + this.height = e.height; + this.count = e.count; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/SelectionEvent.d --- a/dwt/events/SelectionEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/SelectionEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -28,78 +28,78 @@ public class SelectionEvent : TypedEvent { - /** - * The item that was selected. - */ - public Widget item; + /** + * The item that was selected. + */ + public Widget item; - /** - * Extra detail information about the selection, depending on the widget. - * - *

Sash

ScrollBar and Slider

Table and Tree

Text

CoolItem and ToolItem

- */ - public int detail; + /** + * Extra detail information about the selection, depending on the widget. + * + *

Sash

ScrollBar and Slider

Table and Tree

Text

CoolItem and ToolItem

+ */ + public int detail; - /** - * The x location of the selected area. - */ - public int x; + /** + * The x location of the selected area. + */ + public int x; - /** - * The y location of selected area. - */ - public int y; + /** + * The y location of selected area. + */ + public int y; - /** - * The width of selected area. - */ - public int width; + /** + * The width of selected area. + */ + public int width; - /** - * The height of selected area. - */ - public int height; + /** + * The height of selected area. + */ + public int height; - /** - * The state of the keyboard modifier keys at the time - * the event was generated. - */ - public int stateMask; + /** + * The state of the keyboard modifier keys at the time + * the event was generated. + */ + public int stateMask; - /** - * The text of the hyperlink that was selected. - * This will be either the text of the hyperlink or the value of its HREF, - * if one was specified. - * - * @see dwt.widgets.Link#setText(String) - * @since 3.1 - */ - public char[] text; + /** + * The text of the hyperlink that was selected. + * This will be either the text of the hyperlink or the value of its HREF, + * if one was specified. + * + * @see dwt.widgets.Link#setText(String) + * @since 3.1 + */ + public char[] text; - /** - * A flag indicating whether the operation should be allowed. - * Setting this field to false will cancel the - * operation, depending on the widget. - */ - public bool doit; + /** + * A flag indicating whether the operation should be allowed. + * Setting this field to false will cancel the + * operation, depending on the widget. + */ + public bool doit; - //static final long serialVersionUID = 3976735856884987953L; + //static final long serialVersionUID = 3976735856884987953L; /** * Constructs a new instance of this class based on the @@ -108,16 +108,16 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.item = e.item; - this.x = e.x; - this.y = e.y; - this.width = e.width; - this.height = e.height; - this.detail = e.detail; - this.stateMask = e.stateMask; - this.text = e.text; - this.doit = e.doit; + super(e); + this.item = e.item; + this.x = e.x; + this.y = e.y; + this.width = e.width; + this.height = e.height; + this.detail = e.detail; + this.stateMask = e.stateMask; + this.text = e.text; + this.doit = e.doit; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/ShellEvent.d --- a/dwt/events/ShellEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/ShellEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -25,13 +25,13 @@ public final class ShellEvent : TypedEvent { - /** - * A flag indicating whether the operation should be allowed. - * Setting this field to false will cancel the operation. - */ - public bool doit; + /** + * A flag indicating whether the operation should be allowed. + * Setting this field to false will cancel the operation. + */ + public bool doit; - //static final long serialVersionUID = 3257569490479888441L; + //static final long serialVersionUID = 3257569490479888441L; /** * Constructs a new instance of this class based on the @@ -40,8 +40,8 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.doit = e.doit; + super(e); + this.doit = e.doit; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/TraverseEvent.d --- a/dwt/events/TraverseEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/TraverseEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -81,36 +81,36 @@ public final class TraverseEvent : KeyEvent { - /** - * The traversal type. - *

- * - * Setting this field will change the type of traversal. - * For example, setting the detail to TRAVERSE_NONE - * causes no traversal action to be taken. - * - * When used in conjunction with the doit field, the - * traversal detail field can be useful when overriding the default - * traversal mechanism for a control. For example, setting the doit - * field to false will cancel the operation and allow - * the traversal key stroke to be delivered to the control. Setting - * the doit field to true indicates that the traversal - * described by the detail field is to be performed. - */ - public int detail; + /** + * The traversal type. + *

+ * + * Setting this field will change the type of traversal. + * For example, setting the detail to TRAVERSE_NONE + * causes no traversal action to be taken. + * + * When used in conjunction with the doit field, the + * traversal detail field can be useful when overriding the default + * traversal mechanism for a control. For example, setting the doit + * field to false will cancel the operation and allow + * the traversal key stroke to be delivered to the control. Setting + * the doit field to true indicates that the traversal + * described by the detail field is to be performed. + */ + public int detail; - //static final long serialVersionUID = 3257565105301239349L; + //static final long serialVersionUID = 3257565105301239349L; /** * Constructs a new instance of this class based on the @@ -119,8 +119,8 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.detail = e.detail; + super(e); + this.detail = e.detail; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/TreeEvent.d --- a/dwt/events/TreeEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/TreeEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -23,7 +23,7 @@ public final class TreeEvent : SelectionEvent { - //static final long serialVersionUID = 3257282548009677109L; + //static final long serialVersionUID = 3257282548009677109L; /** * Constructs a new instance of this class based on the @@ -32,7 +32,7 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); + super(e); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/TypedEvent.d --- a/dwt/events/TypedEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/TypedEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -28,33 +28,33 @@ */ public class TypedEvent : SWTEventObject { - /** - * the display where the event occurred - * - * @since 2.0 - */ - public Display display; + /** + * the display where the event occurred + * + * @since 2.0 + */ + public Display display; - /** - * the widget that issued the event - */ - public Widget widget; + /** + * the widget that issued the event + */ + public Widget widget; - /** - * the time that the event occurred. - * - * NOTE: This field is an unsigned integer and should - * be AND'ed with 0xFFFFFFFFL so that it can be treated - * as a signed long. - */ - public int time; + /** + * the time that the event occurred. + * + * NOTE: This field is an unsigned integer and should + * be AND'ed with 0xFFFFFFFFL so that it can be treated + * as a signed long. + */ + public int time; - /** - * a field for application use - */ - public Object data; + /** + * a field for application use + */ + public Object data; - //static final long serialVersionUID = 3257285846578377524L; + //static final long serialVersionUID = 3257285846578377524L; /** * Constructs a new instance of this class. @@ -62,7 +62,7 @@ * @param object the object that fired the event */ public this(Object object) { - super(object); + super(object); } /** @@ -72,11 +72,11 @@ * @param e the low level event to initialize the receiver with */ public this(Event e) { - super(e.widget); - this.display = e.display; - this.widget = e.widget; - this.time = e.time; - this.data = e.data; + super(e.widget); + this.display = e.display; + this.widget = e.widget; + this.time = e.time; + this.data = e.data; } /** @@ -86,7 +86,7 @@ * @return the name of the event */ char[] getName () { - char[] str = this.classinfo.name; + char[] str = this.classinfo.name; return split( str, "." )[$-1]; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/events/VerifyEvent.d --- a/dwt/events/VerifyEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/events/VerifyEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -24,20 +24,20 @@ public final class VerifyEvent : KeyEvent { - /** - * the range of text being modified. - * Setting these fields has no effect. - */ - public int start, end; + /** + * the range of text being modified. + * Setting these fields has no effect. + */ + public int start, end; - /** - * the new text that will be inserted. - * Setting this field will change the text that is about to - * be inserted or deleted. - */ - public char[] text; + /** + * the new text that will be inserted. + * Setting this field will change the text that is about to + * be inserted or deleted. + */ + public char[] text; - //static final long serialVersionUID = 3257003246269577014L; + //static final long serialVersionUID = 3257003246269577014L; /** * Constructs a new instance of this class based on the @@ -46,10 +46,10 @@ * @param e the untyped event containing the information */ public this(Event e) { - super(e); - this.start = e.start; - this.end = e.end; - this.text = e.text; + super(e); + this.start = e.start; + this.end = e.end; + this.text = e.text; } /** @@ -59,6 +59,6 @@ * @return a string representation of the event */ public char[] toString() { - return Format( "{} start={} end={} text={}}", super.toString[ 0 .. $-2 ], start, end, text ); + return Format( "{} start={} end={} text={}}", super.toString[ 0 .. $-2 ], start, end, text ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Color.d --- a/dwt/graphics/Color.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Color.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -35,17 +35,17 @@ * @see Device#getSystemColor */ public final class Color : Resource { - /** - * the handle to the OS color resource - * (Warning: This field is platform dependent) - *

- * IMPORTANT: This field is not 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. - *

- */ - public GdkColor* handle; + /** + * the handle to the OS color resource + * (Warning: This field is platform dependent) + *

+ * IMPORTANT: This field is not 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. + *

+ */ + public GdkColor* handle; this() { } @@ -75,10 +75,10 @@ * @see #dispose */ public this(Device device, int red, int green, int blue) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, red, green, blue); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, red, green, blue); + if (device.tracking) device.new_Object(this); } /** @@ -104,11 +104,11 @@ * @see #dispose */ public this(Device device, RGB rgb) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (rgb is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, rgb.red, rgb.green, rgb.blue); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (rgb is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, rgb.red, rgb.green, rgb.blue); + if (device.tracking) device.new_Object(this); } /** @@ -117,20 +117,20 @@ * they allocate. */ public void dispose() { - if (handle is null) return; - if (device.isDisposed()) return; - int pixel = handle.pixel; - if (device.colorRefCount !is null) { - /* If this was the last reference, remove the color from the list */ - if (--device.colorRefCount[pixel] == 0) { - device.gdkColors[pixel] = null; - } - } - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_colormap_free_colors(colormap, handle, 1); - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null) return; + if (device.isDisposed()) return; + int pixel = handle.pixel; + if (device.colorRefCount !is null) { + /* If this was the last reference, remove the color from the list */ + if (--device.colorRefCount[pixel] == 0) { + device.gdkColors[pixel] = null; + } + } + auto colormap = OS.gdk_colormap_get_system(); + OS.gdk_colormap_free_colors(colormap, handle, 1); + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -144,8 +144,8 @@ * @see #hashCode */ public override int opEquals(Object object) { - if (object is this) return true; - if ( auto color = cast(Color)object ){ + if (object is this) return true; + if ( auto color = cast(Color)object ){ GdkColor* gdkColor = color.handle; if (handle == gdkColor) return true; return device == color.device && handle.red == gdkColor.red && @@ -164,8 +164,8 @@ * */ public int getBlue() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return (handle.blue >> 8) & 0xFF; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.blue >> 8) & 0xFF; } /** @@ -178,8 +178,8 @@ * */ public int getGreen() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return (handle.green >> 8) & 0xFF; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.green >> 8) & 0xFF; } /** @@ -192,8 +192,8 @@ * */ public int getRed() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return (handle.red >> 8) & 0xFF; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return (handle.red >> 8) & 0xFF; } /** @@ -207,8 +207,8 @@ * @see #equals */ public override hash_t toHash() { - if (isDisposed()) return 0; - return handle.red ^ handle.green ^ handle.blue; + if (isDisposed()) return 0; + return handle.red ^ handle.green ^ handle.blue; } /** @@ -221,8 +221,8 @@ * */ public RGB getRGB () { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return new RGB(getRed(), getGreen(), getBlue()); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return new RGB(getRed(), getGreen(), getBlue()); } /** @@ -241,41 +241,41 @@ * @private */ public static Color gtk_new(Device device, GdkColor* gdkColor) { - if (device is null) device = Device.getDevice(); - Color color = new Color(); - color.handle = gdkColor; - color.device = device; - return color; + if (device is null) device = Device.getDevice(); + Color color = new Color(); + color.handle = gdkColor; + color.device = device; + return color; } void init(Device device, int red, int green, int blue) { - this.device = device; - if ((red > 255) || (red < 0) || - (green > 255) || (green < 0) || - (blue > 255) || (blue < 0)) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - GdkColor* gdkColor = new GdkColor(); - gdkColor.red = cast(short)((red & 0xFF) | ((red & 0xFF) << 8)); - gdkColor.green = cast(short)((green & 0xFF) | ((green & 0xFF) << 8)); - gdkColor.blue = cast(short)((blue & 0xFF) | ((blue & 0xFF) << 8)); - auto colormap = OS.gdk_colormap_get_system(); - if (!OS.gdk_colormap_alloc_color(colormap, gdkColor, true, true)) { - /* Allocate black. */ - gdkColor = new GdkColor(); - OS.gdk_colormap_alloc_color(colormap, gdkColor, true, true); - } - handle = gdkColor; - if (device.colorRefCount != null) { - /* Make a copy of the color to put in the colors array */ - GdkColor* colorCopy = new GdkColor(); - colorCopy.red = handle.red; - colorCopy.green = handle.green; - colorCopy.blue = handle.blue; - colorCopy.pixel = handle.pixel; - device.gdkColors[colorCopy.pixel] = colorCopy; - device.colorRefCount[colorCopy.pixel]++; - } + this.device = device; + if ((red > 255) || (red < 0) || + (green > 255) || (green < 0) || + (blue > 255) || (blue < 0)) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + GdkColor* gdkColor = new GdkColor(); + gdkColor.red = cast(short)((red & 0xFF) | ((red & 0xFF) << 8)); + gdkColor.green = cast(short)((green & 0xFF) | ((green & 0xFF) << 8)); + gdkColor.blue = cast(short)((blue & 0xFF) | ((blue & 0xFF) << 8)); + auto colormap = OS.gdk_colormap_get_system(); + if (!OS.gdk_colormap_alloc_color(colormap, gdkColor, true, true)) { + /* Allocate black. */ + gdkColor = new GdkColor(); + OS.gdk_colormap_alloc_color(colormap, gdkColor, true, true); + } + handle = gdkColor; + if (device.colorRefCount != null) { + /* Make a copy of the color to put in the colors array */ + GdkColor* colorCopy = new GdkColor(); + colorCopy.red = handle.red; + colorCopy.green = handle.green; + colorCopy.blue = handle.blue; + colorCopy.pixel = handle.pixel; + device.gdkColors[colorCopy.pixel] = colorCopy; + device.colorRefCount[colorCopy.pixel]++; + } } /** @@ -289,7 +289,7 @@ * @return true when the color is disposed and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -299,8 +299,8 @@ * @return a string representation of the receiver */ public override char[] toString () { - if (isDisposed()) return "Color {*DISPOSED*}"; - return Format( "Color {{{}, {}, {}}", getRed(), getGreen(), getBlue()); + if (isDisposed()) return "Color {*DISPOSED*}"; + return Format( "Color {{{}, {}, {}}", getRed(), getGreen(), getBlue()); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Cursor.d --- a/dwt/graphics/Cursor.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Cursor.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -48,43 +48,43 @@ *

*/ public final class Cursor : Resource { - /** - * the handle to the OS cursor resource - * (Warning: This field is platform dependent) - *

- * IMPORTANT: This field is not 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. - *

- */ - public GdkCursor* handle; + /** + * the handle to the OS cursor resource + * (Warning: This field is platform dependent) + *

+ * IMPORTANT: This field is not 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. + *

+ */ + public GdkCursor* handle; - static const byte[] APPSTARTING_SRC = [ cast(byte) - 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, cast(byte)0xfc, 0x00, 0x00, 0x00, cast(byte)0xfc, 0x01, 0x00, 0x00, - cast(byte)0xfc, 0x3b, 0x00, 0x00, 0x7c, 0x38, 0x00, 0x00, 0x6c, 0x54, 0x00, 0x00, - cast(byte)0xc4, cast(byte)0xdc, 0x00, 0x00, cast(byte)0xc0, 0x44, 0x00, 0x00, cast(byte)0x80, 0x39, 0x00, 0x00, - cast(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 const byte[] APPSTARTING_SRC = [ cast(byte) + 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, cast(byte)0xfc, 0x00, 0x00, 0x00, cast(byte)0xfc, 0x01, 0x00, 0x00, + cast(byte)0xfc, 0x3b, 0x00, 0x00, 0x7c, 0x38, 0x00, 0x00, 0x6c, 0x54, 0x00, 0x00, + cast(byte)0xc4, cast(byte)0xdc, 0x00, 0x00, cast(byte)0xc0, 0x44, 0x00, 0x00, cast(byte)0x80, 0x39, 0x00, 0x00, + cast(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 const byte[] APPSTARTING_MASK = [ cast(byte) - 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, - 0x1e, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, - cast(byte)0xfe, 0x00, 0x00, 0x00, cast(byte)0xfe, 0x01, 0x00, 0x00, cast(byte)0xfe, 0x3b, 0x00, 0x00, - cast(byte)0xfe, 0x7f, 0x00, 0x00, cast(byte)0xfe, 0x7f, 0x00, 0x00, cast(byte)0xfe, cast(byte)0xfe, 0x00, 0x00, - cast(byte)0xee, cast(byte)0xff, 0x01, 0x00, cast(byte)0xe4, cast(byte)0xff, 0x00, 0x00, cast(byte)0xc0, 0x7f, 0x00, 0x00, - cast(byte)0xc0, 0x7f, 0x00, 0x00, cast(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]; + static const byte[] APPSTARTING_MASK = [ cast(byte) + 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, + cast(byte)0xfe, 0x00, 0x00, 0x00, cast(byte)0xfe, 0x01, 0x00, 0x00, cast(byte)0xfe, 0x3b, 0x00, 0x00, + cast(byte)0xfe, 0x7f, 0x00, 0x00, cast(byte)0xfe, 0x7f, 0x00, 0x00, cast(byte)0xfe, cast(byte)0xfe, 0x00, 0x00, + cast(byte)0xee, cast(byte)0xff, 0x01, 0x00, cast(byte)0xe4, cast(byte)0xff, 0x00, 0x00, cast(byte)0xc0, 0x7f, 0x00, 0x00, + cast(byte)0xc0, 0x7f, 0x00, 0x00, cast(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]; this () { } @@ -131,43 +131,43 @@ * @see SWT#CURSOR_HAND */ public this(Device device, int style) { - if (device == null) device = Device.getDevice(); - if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - int shape = 0; - switch (style) { - case SWT.CURSOR_APPSTARTING: break; - case SWT.CURSOR_ARROW: shape = OS.GDK_LEFT_PTR; break; - case SWT.CURSOR_WAIT: shape = OS.GDK_WATCH; break; - case SWT.CURSOR_CROSS: shape = OS.GDK_CROSS; break; - case SWT.CURSOR_HAND: shape = OS.GDK_HAND2; break; - case SWT.CURSOR_HELP: shape = OS.GDK_QUESTION_ARROW; break; - case SWT.CURSOR_SIZEALL: shape = OS.GDK_FLEUR; break; - case SWT.CURSOR_SIZENESW: shape = OS.GDK_SIZING; break; - case SWT.CURSOR_SIZENS: shape = OS.GDK_DOUBLE_ARROW; break; - case SWT.CURSOR_SIZENWSE: shape = OS.GDK_SIZING; break; - case SWT.CURSOR_SIZEWE: shape = OS.GDK_SB_H_DOUBLE_ARROW; break; - case SWT.CURSOR_SIZEN: shape = OS.GDK_TOP_SIDE; break; - case SWT.CURSOR_SIZES: shape = OS.GDK_BOTTOM_SIDE; break; - case SWT.CURSOR_SIZEE: shape = OS.GDK_RIGHT_SIDE; break; - case SWT.CURSOR_SIZEW: shape = OS.GDK_LEFT_SIDE; break; - case SWT.CURSOR_SIZENE: shape = OS.GDK_TOP_RIGHT_CORNER; break; - case SWT.CURSOR_SIZESE: shape = OS.GDK_BOTTOM_RIGHT_CORNER; break; - case SWT.CURSOR_SIZESW: shape = OS.GDK_BOTTOM_LEFT_CORNER; break; - case SWT.CURSOR_SIZENW: shape = OS.GDK_TOP_LEFT_CORNER; break; - case SWT.CURSOR_UPARROW: shape = OS.GDK_SB_UP_ARROW; break; - case SWT.CURSOR_IBEAM: shape = OS.GDK_XTERM; break; - case SWT.CURSOR_NO: shape = OS.GDK_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.gdk_cursor_new(shape); - } - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - if (device.tracking) device.new_Object(this); + if (device == null) device = Device.getDevice(); + if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + int shape = 0; + switch (style) { + case SWT.CURSOR_APPSTARTING: break; + case SWT.CURSOR_ARROW: shape = OS.GDK_LEFT_PTR; break; + case SWT.CURSOR_WAIT: shape = OS.GDK_WATCH; break; + case SWT.CURSOR_CROSS: shape = OS.GDK_CROSS; break; + case SWT.CURSOR_HAND: shape = OS.GDK_HAND2; break; + case SWT.CURSOR_HELP: shape = OS.GDK_QUESTION_ARROW; break; + case SWT.CURSOR_SIZEALL: shape = OS.GDK_FLEUR; break; + case SWT.CURSOR_SIZENESW: shape = OS.GDK_SIZING; break; + case SWT.CURSOR_SIZENS: shape = OS.GDK_DOUBLE_ARROW; break; + case SWT.CURSOR_SIZENWSE: shape = OS.GDK_SIZING; break; + case SWT.CURSOR_SIZEWE: shape = OS.GDK_SB_H_DOUBLE_ARROW; break; + case SWT.CURSOR_SIZEN: shape = OS.GDK_TOP_SIDE; break; + case SWT.CURSOR_SIZES: shape = OS.GDK_BOTTOM_SIDE; break; + case SWT.CURSOR_SIZEE: shape = OS.GDK_RIGHT_SIDE; break; + case SWT.CURSOR_SIZEW: shape = OS.GDK_LEFT_SIDE; break; + case SWT.CURSOR_SIZENE: shape = OS.GDK_TOP_RIGHT_CORNER; break; + case SWT.CURSOR_SIZESE: shape = OS.GDK_BOTTOM_RIGHT_CORNER; break; + case SWT.CURSOR_SIZESW: shape = OS.GDK_BOTTOM_LEFT_CORNER; break; + case SWT.CURSOR_SIZENW: shape = OS.GDK_TOP_LEFT_CORNER; break; + case SWT.CURSOR_UPARROW: shape = OS.GDK_SB_UP_ARROW; break; + case SWT.CURSOR_IBEAM: shape = OS.GDK_XTERM; break; + case SWT.CURSOR_NO: shape = OS.GDK_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.gdk_cursor_new(shape); + } + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + if (device.tracking) device.new_Object(this); } /** @@ -202,61 +202,61 @@ * */ public this(Device device, ImageData source, ImageData mask, int hotspotX, int hotspotY) { - if (device == null) device = Device.getDevice(); - if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - if (source == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (mask == null) { - if (!(source.getTransparencyType() == SWT.TRANSPARENCY_MASK)) SWT.error(SWT.ERROR_NULL_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); + if (device == null) device = Device.getDevice(); + if (device == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + if (source == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (mask == null) { + if (!(source.getTransparencyType() == SWT.TRANSPARENCY_MASK)) SWT.error(SWT.ERROR_NULL_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); - /* 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] = cast(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] = cast(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] = cast(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] = cast(byte) ~maskData[i]; - } - maskData = ImageData.convertPad(maskData, mask.width, mask.height, mask.depth, mask.scanlinePad, 1); - handle = createCursor(maskData, sourceData, source.width, source.height, hotspotX, hotspotY, true); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - if (device.tracking) device.new_Object(this); + /* 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] = cast(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] = cast(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] = cast(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] = cast(byte) ~maskData[i]; + } + maskData = ImageData.convertPad(maskData, mask.width, mask.height, mask.depth, mask.scanlinePad, 1); + handle = createCursor(maskData, sourceData, source.width, source.height, hotspotX, hotspotY, true); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + if (device.tracking) device.new_Object(this); } /** @@ -278,7 +278,7 @@ *
  • ERROR_NULL_ARGUMENT - if device is null and there is no current device
  • *
  • ERROR_NULL_ARGUMENT - if the image is null
  • *
  • ERROR_INVALID_ARGUMENT - if the hotspot is outside the bounds of the - * image
  • + * image * * @exception SWTError */ protected void checkDevice () { - if (disposed) SWT.error(SWT.ERROR_DEVICE_DISPOSED); + if (disposed) SWT.error(SWT.ERROR_DEVICE_DISPOSED); } /** @@ -232,43 +232,43 @@ * @see #checkDevice */ public void dispose () { - if (isDisposed()) return; - checkDevice (); - release (); - destroy (); - deregister (this); - xDisplay = null; - disposed = true; - if (tracking) { - objects = null; - errors = null; - } + if (isDisposed()) return; + checkDevice (); + release (); + destroy (); + deregister (this); + xDisplay = null; + disposed = true; + if (tracking) { + objects = null; + errors = null; + } } void dispose_Object (Object object) { - for (int i=0; i */ public Rectangle getBounds () { - checkDevice (); - return new Rectangle(0, 0, 0, 0); + checkDevice (); + return new Rectangle(0, 0, 0, 0); } /** @@ -316,26 +316,26 @@ * @see DeviceData */ public DeviceData getDeviceData () { - checkDevice(); - DeviceData data = new DeviceData (); - data.debugging = debugging; - data.tracking = tracking; - int count = 0, length = 0; - if (tracking) length = objects.length; - for (int i=0; i */ public int getDepth () { - checkDevice (); - return 0; + checkDevice (); + return 0; } /** @@ -384,8 +384,8 @@ * */ public Point getDPI () { - checkDevice (); - return new Point (72, 72); + checkDevice (); + return new Point (72, 72); } /** @@ -402,47 +402,47 @@ * */ public FontData[] getFontList (char[] faceName, bool scalable) { - checkDevice (); - if (!scalable) return new FontData[0]; - PangoFontFamily* family; - PangoFontFace * face; - PangoFontFamily** families; - int n_families; - PangoFontFace ** faces; - int n_faces; - auto context = OS.gdk_pango_context_get(); - OS.pango_context_list_families(context, &families, &n_families); - int nFds = 0; - FontData[] fds = new FontData[faceName !is null ? 4 : n_families]; - for (int i=0; i */ public Font getSystemFont () { - checkDevice (); - return systemFont; + checkDevice (); + return systemFont; } /** @@ -527,8 +527,8 @@ * */ public bool getWarnings () { - checkDevice (); - return warningLevel is 0; + checkDevice (); + return warningLevel is 0; } /** @@ -544,69 +544,69 @@ * @see #create */ protected void init () { - if (xDisplay !is null) { - int event_basep, error_basep; - if (OS.XRenderQueryExtension (xDisplay, &event_basep, &error_basep)) { - int major_version, minor_version; - OS.XRenderQueryVersion (xDisplay, &major_version, &minor_version); - useXRender = major_version > 0 || (major_version is 0 && minor_version >= 8); - } - } + if (xDisplay !is null) { + int event_basep, error_basep; + if (OS.XRenderQueryExtension (xDisplay, &event_basep, &error_basep)) { + int major_version, minor_version; + OS.XRenderQueryVersion (xDisplay, &major_version, &minor_version); + useXRender = major_version > 0 || (major_version is 0 && minor_version >= 8); + } + } - if (debugging) { - if (xDisplay !is null) { - /* Create the warning and error callbacks */ - synchronized (CREATE_LOCK) { - int index = 0; - while (index < Devices.length) { - if (Devices [index] !is null) break; - index++; - } - if (index is Devices.length) { - OS.XSetErrorHandler ( & XErrorProcFunc ); - OS.XSetIOErrorHandler ( & XIOErrorProcFunc ); - } - } - OS.XSynchronize (xDisplay, true); - } - } + if (debugging) { + if (xDisplay !is null) { + /* Create the warning and error callbacks */ + synchronized (CREATE_LOCK) { + int index = 0; + while (index < Devices.length) { + if (Devices [index] !is null) break; + index++; + } + if (index is Devices.length) { + OS.XSetErrorHandler ( & XErrorProcFunc ); + OS.XSetIOErrorHandler ( & XIOErrorProcFunc ); + } + } + OS.XSynchronize (xDisplay, true); + } + } - /* Create GTK warnings and error callbacks */ - if (xDisplay !is null) { - /* Set GTK warning and error handlers */ - if (debugging) { - int flags = OS.G_LOG_LEVEL_MASK | OS.G_LOG_FLAG_FATAL | OS.G_LOG_FLAG_RECURSION; - for (int i=0; itrue when the device is disposed and false otherwise */ public bool isDisposed () { - return disposed; + return disposed; } /** @@ -670,32 +670,32 @@ * @since 3.3 */ public bool loadFont (char[] path) { - checkDevice(); - if (path is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - return cast(bool) OS.FcConfigAppFontAddFile (null, toStringz(path)); + checkDevice(); + if (path is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + return cast(bool) OS.FcConfigAppFontAddFile (null, toStringz(path)); } private static extern(C) void logFunction (char* log_domain, int log_level, char* message, void* user_data) { Device dev = cast(Device)user_data; - if (dev.warningLevel is 0) { - if (DEBUG || dev.debugging) { + if (dev.warningLevel is 0) { + if (DEBUG || dev.debugging) { foreach( msg; new TracedException ("") ){ Stderr.formatln( "trc {}", msg ); } - } - OS.g_log_default_handler (log_domain, log_level, message, user_data); - } - return 0; + } + OS.g_log_default_handler (log_domain, log_level, message, user_data); + } + return 0; } void new_Object (Object object) { - for (int i=0; i 0) { - OS.gdk_colormap_free_colors(colormap, color, 1); - --colorRefCount [i]; - } - } - } - } - gdkColors = null; - colorRefCount = null; - 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; + if (gdkColors !is null) { + auto colormap = OS.gdk_colormap_get_system(); + for (int i = 0; i < gdkColors.length; i++) { + GdkColor* color = gdkColors [i]; + if (color !is null) { + while (colorRefCount [i] > 0) { + OS.gdk_colormap_free_colors(colormap, color, 1); + --colorRefCount [i]; + } + } + } + } + gdkColors = null; + colorRefCount = null; + 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; - if (emptyTab !is null ) OS.pango_tab_array_free(emptyTab); - emptyTab = null; + if (emptyTab !is null ) OS.pango_tab_array_free(emptyTab); + emptyTab = null; - /* Free the GTK error and warning handler */ - if (xDisplay !is null) { - for (int i=0; i */ public void setWarnings (bool warnings) { - checkDevice (); - if (warnings) { - if (--warningLevel is 0) { - if (debugging) return; + checkDevice (); + if (warnings) { + if (--warningLevel is 0) { + if (debugging) return; for (int i=0; i - * IMPORTANT: These fields are not part of the SWT - * public API. They are marked public only so that they can be shared - * within the packages provided by SWT. They are not available on all - * platforms and should never be accessed from application code. - *

    - */ - public char[] display_name; - public char[] application_name; - public char[] application_class; + /* + * The following fields are platform dependent. + *

    + * IMPORTANT: These fields are not part of the SWT + * public API. They are marked public only so that they can be shared + * within the packages provided by SWT. They are not available on all + * platforms and should never be accessed from application code. + *

    + */ + public char[] display_name; + public char[] application_name; + public char[] application_class; - /* - * Debug fields - may not be honoured - * on some SWT platforms. - */ - public bool debugging; - public bool tracking; - public TracedException [] errors; - public Object [] objects; + /* + * Debug fields - may not be honoured + * on some SWT platforms. + */ + public bool debugging; + public bool tracking; + public TracedException [] errors; + public Object [] objects; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Font.d --- a/dwt/graphics/Font.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Font.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -35,17 +35,17 @@ * @see FontData */ public final class Font : Resource { - /** - * the handle to the OS font resource - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public PangoFontDescription* handle; + /** + * the handle to the OS font resource + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public PangoFontDescription* handle; this() { } @@ -69,11 +69,11 @@ * */ public this(Device device, FontData fd) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (fd is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, fd.getName(), fd.getHeightF(), fd.getStyle(), fd.str); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (fd is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, fd.getName(), fd.getHeightF(), fd.getStyle(), fd.str); + if (device.tracking) device.new_Object(this); } /** @@ -100,16 +100,16 @@ * @since 2.1 */ public this(Device device, FontData[] fds) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (fds is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (fds.length == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - for (int i=0; i */ public this(Device device, char[] name, int height, int style) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, name, height, style, null); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, name, height, style, null); + if (device.tracking) device.new_Object(this); } /*public*/ this(Device device, char[] name, float height, int style) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, name, height, style, null); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, name, height, style, null); + if (device.tracking) device.new_Object(this); } /** @@ -154,12 +154,12 @@ * they allocate. */ public void dispose() { - if (handle is null ) return; - if (device.isDisposed()) return; - OS.pango_font_description_free(handle); - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null ) return; + if (device.isDisposed()) return; + OS.pango_font_description_free(handle); + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -173,8 +173,8 @@ * @see #hashCode */ public int opEquals(Object object) { - if (object == this) return true; - if ( auto font = cast(Font)object ){ + if (object == this) return true; + if ( auto font = cast(Font)object ){ return handle is font.handle; } return false; @@ -194,23 +194,23 @@ * */ public FontData[] getFontData() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - auto family = OS.pango_font_description_get_family(handle); - char[] name = fromUtf8z( family ); - float height = cast(float)OS.pango_font_description_get_size(handle) / OS.PANGO_SCALE; - int pangoStyle = OS.pango_font_description_get_style(handle); - int pangoWeight = OS.pango_font_description_get_weight(handle); - int style = SWT.NORMAL; - if (pangoStyle == OS.PANGO_STYLE_ITALIC) style |= SWT.ITALIC; - if (pangoStyle == OS.PANGO_STYLE_OBLIQUE) style |= SWT.ROMAN; - if (pangoWeight >= OS.PANGO_WEIGHT_BOLD) style |= SWT.BOLD; - auto fontString = OS.pango_font_description_to_string (handle); + auto family = OS.pango_font_description_get_family(handle); + char[] name = fromUtf8z( family ); + float height = cast(float)OS.pango_font_description_get_size(handle) / OS.PANGO_SCALE; + int pangoStyle = OS.pango_font_description_get_style(handle); + int pangoWeight = OS.pango_font_description_get_weight(handle); + int style = SWT.NORMAL; + if (pangoStyle == OS.PANGO_STYLE_ITALIC) style |= SWT.ITALIC; + if (pangoStyle == OS.PANGO_STYLE_OBLIQUE) style |= SWT.ROMAN; + if (pangoWeight >= OS.PANGO_WEIGHT_BOLD) style |= SWT.BOLD; + auto fontString = OS.pango_font_description_to_string (handle); auto buffer = fromUtf8z( fontString ).dup; - FontData data = new FontData( buffer , height, style); + FontData data = new FontData( buffer , height, style); OS.g_free (fontString); - data.str = buffer; - return [data]; + data.str = buffer; + return [data]; } /** @@ -229,11 +229,11 @@ * @private */ public static Font gtk_new(Device device, PangoFontDescription* handle) { - if (device is null) device = Device.getDevice(); - Font font = new Font(); - font.handle = handle; - font.device = device; - return font; + if (device is null) device = Device.getDevice(); + Font font = new Font(); + font.handle = handle; + font.device = device; + return font; } /** @@ -247,31 +247,31 @@ * @see #equals */ public hash_t toHash() { - return cast(hash_t)/*64*/handle; + return cast(hash_t)/*64*/handle; } void init(Device device, char[] name, float height, int style, char[] fontString) { - if (name is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - this.device = device; - if (fontString !is null) { - handle = OS.pango_font_description_from_string (toStringz(fontString)); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - } else { - handle = OS.pango_font_description_new(); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - //byte[] buffer = Converter.wcsToMbcs(null, name, true); - OS.pango_font_description_set_family(handle, toStringz(name) ); - OS.pango_font_description_set_size(handle, cast(int)(0.5f + height * OS.PANGO_SCALE)); - OS.pango_font_description_set_stretch(handle, OS.PANGO_STRETCH_NORMAL); - int pangoStyle = OS.PANGO_STYLE_NORMAL; - int pangoWeight = OS.PANGO_WEIGHT_NORMAL; - if ((style & SWT.ITALIC) != 0) pangoStyle = OS.PANGO_STYLE_ITALIC; - if ((style & SWT.ROMAN) != 0) pangoStyle = OS.PANGO_STYLE_OBLIQUE; - if ((style & SWT.BOLD) != 0) pangoWeight = OS.PANGO_WEIGHT_BOLD; - OS.pango_font_description_set_style(handle, pangoStyle); - OS.pango_font_description_set_weight(handle, pangoWeight); - } + if (name is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.device = device; + if (fontString !is null) { + handle = OS.pango_font_description_from_string (toStringz(fontString)); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + } else { + handle = OS.pango_font_description_new(); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + //byte[] buffer = Converter.wcsToMbcs(null, name, true); + OS.pango_font_description_set_family(handle, toStringz(name) ); + OS.pango_font_description_set_size(handle, cast(int)(0.5f + height * OS.PANGO_SCALE)); + OS.pango_font_description_set_stretch(handle, OS.PANGO_STRETCH_NORMAL); + int pangoStyle = OS.PANGO_STYLE_NORMAL; + int pangoWeight = OS.PANGO_WEIGHT_NORMAL; + if ((style & SWT.ITALIC) != 0) pangoStyle = OS.PANGO_STYLE_ITALIC; + if ((style & SWT.ROMAN) != 0) pangoStyle = OS.PANGO_STYLE_OBLIQUE; + if ((style & SWT.BOLD) != 0) pangoWeight = OS.PANGO_WEIGHT_BOLD; + OS.pango_font_description_set_style(handle, pangoStyle); + OS.pango_font_description_set_weight(handle, pangoWeight); + } } /** @@ -285,7 +285,7 @@ * @return true when the font is disposed and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -295,8 +295,8 @@ * @return a string representation of the receiver */ public char[] toString () { - if (isDisposed()) return "Font {*DISPOSED*}"; - return Format( "Font {{{}}", handle ); + if (isDisposed()) return "Font {*DISPOSED*}"; + return Format( "Font {{{}}", handle ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/FontData.d --- a/dwt/graphics/FontData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/FontData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -42,64 +42,64 @@ * @see Font */ public final class FontData { - /** - * the font name - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public char[] name; + /** + * the font name + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public char[] name; - /** - * The height of the font data in points - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public float height; + /** + * The height of the font data in points + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public float height; - /** - * the font style - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public int style; + /** + * the font style + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public int style; - /** - * the Pango string - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public char[] str; + /** + * the Pango string + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public char[] str; - /** - * The locales of the font - */ - char[] lang, country, variant; + /** + * The locales of the font + */ + char[] lang, country, variant; /** * Constructs a new uninitialized font data. */ public this () { - this("", 12, SWT.NORMAL); + this("", 12, SWT.NORMAL); } /** @@ -122,58 +122,58 @@ * @see #toString */ public this(char[] str) { - if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - int start = 0; - int end = locate( str, '|' ); - if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - char[] version1 = str[ start .. end ]; - try { - if (to!(int)(version1) != 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } catch (ConversionException e) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } + if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int start = 0; + int end = locate( str, '|' ); + if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + char[] version1 = str[ start .. end ]; + try { + if (to!(int)(version1) != 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } catch (ConversionException e) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } - start = end + 1; - end = locate( str, '|', start ); - if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - char[] name = str[start .. end ]; + start = end + 1; + end = locate( str, '|', start ); + if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + char[] name = str[start .. end ]; - start = end + 1; + start = end + 1; end = locate( str, '|', start ); if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - float height = 0; - try { - height = to!(float)(str[start .. end]); - } catch (ConversionException e) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } + float height = 0; + try { + height = to!(float)(str[start .. end]); + } catch (ConversionException e) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } - start = end + 1; + start = end + 1; end = locate( str, '|', start ); if (end == str.length ) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - int style = 0; - try { - style = to!(int)( str[start .. end ]); - } catch (ConversionException e) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } + int style = 0; + try { + style = to!(int)( str[start .. end ]); + } catch (ConversionException e) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } - start = end + 1; + start = end + 1; end = locate( str, '|', start ); - setName(name); - setHeight(height); - setStyle(style); - if (end == str.length) return; - char[] platform = str[ start .. end ]; + setName(name); + setHeight(height); + setStyle(style); + if (end == str.length) return; + char[] platform = str[ start .. end ]; - start = end + 1; + start = end + 1; end = locate( str, '|', start ); - if (end == str.length) return; - char[] version2 = str[ start .. end ]; + if (end == str.length) return; + char[] version2 = str[ start .. end ]; - if (platform == "GTK" && version2 == "1" ) { - return; - } + if (platform == "GTK" && version2 == "1" ) { + return; + } } /** @@ -191,15 +191,15 @@ * */ public this(char[] name, int height, int style) { - setName(name); - setHeight(height); - setStyle(style); + setName(name); + setHeight(height); + setStyle(style); } /*public*/ this(char[] name, float height, int style) { - setName(name); - setHeight(height); - setStyle(style); + setName(name); + setHeight(height); + setStyle(style); } /** @@ -213,7 +213,7 @@ * @see #hashCode */ public override int opEquals (Object object) { - if (object is this) return true; + if (object is this) return true; if( auto data = cast(FontData)object ){ return name == data.name && height == data.height && style == data.style; } @@ -228,11 +228,11 @@ * @see #setHeight(int) */ public int getHeight() { - return cast(int)(0.5f + height); + return cast(int)(0.5f + height); } /*public*/ float getHeightF() { - return height; + return height; } /** @@ -254,25 +254,25 @@ */ public char[] getLocale () { char[] result; - const char sep = '_'; - if (lang != null) { - result ~= lang; - result ~= sep; - } - if (country != null) { - result ~= country; - result ~= sep; - } - if (variant != null) { - result ~= variant; - } + const char sep = '_'; + if (lang != null) { + result ~= lang; + result ~= sep; + } + if (country != null) { + result ~= country; + result ~= sep; + } + if (variant != null) { + result ~= variant; + } - if (result) { - if (result[$-1] == sep) { - result = result[0 .. $ - 1]; - } - } - return result; + if (result) { + if (result[$-1] == sep) { + result = result[0 .. $ - 1]; + } + } + return result; } /** @@ -285,7 +285,7 @@ * @see #setName */ public char[] getName() { - return name; + return name; } /** @@ -298,7 +298,7 @@ * @see #setStyle */ public int getStyle() { - return style; + return style; } /** @@ -312,7 +312,7 @@ * @see #equals */ public hash_t toHash () { - return typeid(char[]).getHash(&name) ^ getHeight() ^ style; + return typeid(char[]).getHash(&name) ^ getHeight() ^ style; } /** @@ -329,15 +329,15 @@ * @see #getHeight */ public void setHeight(int height) { - if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - this.height = height; - this.str = null; + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.height = height; + this.str = null; } /*public*/ void setHeight(float height) { - if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - this.height = height; - this.str = null; + if (height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.height = height; + this.str = null; } /** @@ -358,23 +358,23 @@ * @see java.util.Locale#toString */ public void setLocale(char[] locale) { - lang = country = variant = null; - if (locale !is null) { - char sep = '_'; - int length = locale.length; - int firstSep, secondSep; + lang = country = variant = null; + if (locale !is null) { + char sep = '_'; + int length = locale.length; + int firstSep, secondSep; - firstSep = locate( locale, sep ); - if (firstSep == locale.length) { - firstSep = secondSep = length; - } else { - secondSep = locate( locale, sep, firstSep + 1); - if (secondSep == locale.length) secondSep = length; - } - if (firstSep > 0) lang = locale[0 .. firstSep]; - if (secondSep > firstSep + 1) country = locale[firstSep + 1 .. secondSep ]; - if (length > secondSep + 1) variant = locale[secondSep + 1 .. $ ]; - } + firstSep = locate( locale, sep ); + if (firstSep == locale.length) { + firstSep = secondSep = length; + } else { + secondSep = locate( locale, sep, firstSep + 1); + if (secondSep == locale.length) secondSep = length; + } + if (firstSep > 0) lang = locale[0 .. firstSep]; + if (secondSep > firstSep + 1) country = locale[firstSep + 1 .. secondSep ]; + if (length > secondSep + 1) variant = locale[secondSep + 1 .. $ ]; + } } /** @@ -403,9 +403,9 @@ * @see #getName */ public void setName(char[] name) { - if (name is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.name = name; - this.str = null; + if (name is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.name = name; + this.str = null; } /** @@ -419,8 +419,8 @@ * @see #getStyle */ public void setStyle(int style) { - this.style = style; - this.str = null; + this.style = style; + this.str = null; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/FontMetrics.d --- a/dwt/graphics/FontMetrics.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/FontMetrics.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -21,7 +21,7 @@ * @see GC#getFontMetrics */ public final class FontMetrics { - int ascent, descent, averageCharWidth, leading, height; + int ascent, descent, averageCharWidth, leading, height; package this() { } @@ -37,13 +37,13 @@ * @see #hashCode */ public int opEquals (Object object) { - if (object is this) return true; + if (object is this) return true; if( auto metrics = cast(FontMetrics)object ){ return ascent == metrics.ascent && descent == metrics.descent && averageCharWidth == metrics.averageCharWidth && leading == metrics.leading && height == metrics.height; } - return false; + return false; } /** @@ -55,7 +55,7 @@ * @return the ascent of the font */ public int getAscent() { - return ascent; + return ascent; } /** @@ -65,7 +65,7 @@ * @return the average character width of the font */ public int getAverageCharWidth() { - return averageCharWidth; + return averageCharWidth; } /** @@ -77,7 +77,7 @@ * @return the descent of the font */ public int getDescent() { - return descent; + return descent; } /** @@ -92,7 +92,7 @@ * @see #getLeading */ public int getHeight() { - return height; + return height; } /** @@ -103,17 +103,17 @@ * @return the leading space of the font */ public int getLeading() { - return leading; + return leading; } public static FontMetrics gtk_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; + FontMetrics fontMetrics = new FontMetrics(); + fontMetrics.ascent = ascent; + fontMetrics.descent = descent; + fontMetrics.averageCharWidth = averageCharWidth; + fontMetrics.leading = leading; + fontMetrics.height = height; + return fontMetrics; } /** @@ -127,7 +127,7 @@ * @see #equals */ public hash_t toHash() { - return ascent ^ descent ^ averageCharWidth ^ leading ^ height; + return ascent ^ descent ^ averageCharWidth ^ leading ^ height; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/GC.d --- a/dwt/graphics/GC.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/GC.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -110,42 +110,42 @@ * @see dwt.events.PaintEvent */ public final class GC : Resource { - /** - * the handle to the OS device context - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public GdkGC* handle; + /** + * the handle to the OS device context + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public GdkGC* handle; - Drawable drawable; - GCData data; + Drawable drawable; + GCData data; - const static int FOREGROUND = 1 << 0; - const static int BACKGROUND = 1 << 1; - const static int FONT = 1 << 2; - const static int LINE_STYLE = 1 << 3; - const static int LINE_CAP = 1 << 4; - const static int LINE_JOIN = 1 << 5; - const static int LINE_WIDTH = 1 << 6; - const static int LINE_MITERLIMIT = 1 << 7; - const static int BACKGROUND_BG = 1 << 8; - const static int DRAW_OFFSET = 1 << 9; - const static int DRAW = FOREGROUND | LINE_WIDTH | LINE_STYLE | LINE_CAP | LINE_JOIN | LINE_MITERLIMIT | DRAW_OFFSET; - const static int FILL = BACKGROUND; + const static int FOREGROUND = 1 << 0; + const static int BACKGROUND = 1 << 1; + const static int FONT = 1 << 2; + const static int LINE_STYLE = 1 << 3; + const static int LINE_CAP = 1 << 4; + const static int LINE_JOIN = 1 << 5; + const static int LINE_WIDTH = 1 << 6; + const static int LINE_MITERLIMIT = 1 << 7; + const static int BACKGROUND_BG = 1 << 8; + const static int DRAW_OFFSET = 1 << 9; + const static int DRAW = FOREGROUND | LINE_WIDTH | LINE_STYLE | LINE_CAP | LINE_JOIN | LINE_MITERLIMIT | DRAW_OFFSET; + const static int FILL = BACKGROUND; - static const float[] LINE_DOT = [1, 1]; - static const float[] LINE_DASH = [3, 1]; - static const float[] LINE_DASHDOT = [3, 1, 1, 1]; - static const float[] LINE_DASHDOTDOT = [3, 1, 1, 1, 1, 1]; - static const float[] LINE_DOT_ZERO = [3, 3]; - static const float[] LINE_DASH_ZERO = [18, 6]; - static const float[] LINE_DASHDOT_ZERO = [9, 6, 3, 6]; - static const float[] LINE_DASHDOTDOT_ZERO = [9, 3, 3, 3, 3, 3]; + static const float[] LINE_DOT = [1, 1]; + static const float[] LINE_DASH = [3, 1]; + static const float[] LINE_DASHDOT = [3, 1, 1, 1]; + static const float[] LINE_DASHDOTDOT = [3, 1, 1, 1, 1, 1]; + static const float[] LINE_DOT_ZERO = [3, 3]; + static const float[] LINE_DASH_ZERO = [18, 6]; + static const float[] LINE_DASHDOT_ZERO = [9, 6, 3, 6]; + static const float[] LINE_DASHDOTDOT_ZERO = [9, 3, 3, 3, 3, 3]; this() { } @@ -173,7 +173,7 @@ * */ public this(Drawable drawable) { - this(drawable, 0); + this(drawable, 0); } /** @@ -204,260 +204,260 @@ * @since 2.1.2 */ public this(Drawable drawable, int style) { - if (drawable is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - GCData data = new GCData(); - data.style = checkStyle(style); - auto gdkGC = drawable.internal_new_GC(data); - Device device = data.device; - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = data.device = device; - init(drawable, data, gdkGC); - if (device.tracking) device.new_Object(this); + if (drawable is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + GCData data = new GCData(); + data.style = checkStyle(style); + auto gdkGC = drawable.internal_new_GC(data); + Device device = data.device; + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = data.device = device; + init(drawable, data, gdkGC); + if (device.tracking) device.new_Object(this); } static void addCairoString(cairo_t* cairo, char[] str, float x, float y, Font font) { - char[] buffer = str.dup; - if (OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - auto layout = OS.pango_cairo_create_layout(cairo); - if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.pango_layout_set_text(layout, buffer.ptr, -1); - OS.pango_layout_set_font_description(layout, font.handle); - Cairo.cairo_move_to(cairo, x, y); - OS.pango_cairo_layout_path(cairo, layout); - OS.g_object_unref(layout); - } else { - 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.ptr); - } + char[] buffer = str.dup; + if (OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + auto layout = OS.pango_cairo_create_layout(cairo); + if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.pango_layout_set_text(layout, buffer.ptr, -1); + OS.pango_layout_set_font_description(layout, font.handle); + Cairo.cairo_move_to(cairo, x, y); + OS.pango_cairo_layout_path(cairo, layout); + OS.g_object_unref(layout); + } else { + 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.ptr); + } } static int checkStyle (int style) { - if ((style & SWT.LEFT_TO_RIGHT) !is 0) style &= ~SWT.RIGHT_TO_LEFT; - return style & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); + if ((style & SWT.LEFT_TO_RIGHT) !is 0) style &= ~SWT.RIGHT_TO_LEFT; + return style & (SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); } public static GC gtk_new(Drawable drawable, GCData data) { - GC gc = new GC(); - auto gdkGC = drawable.internal_new_GC(data); - gc.device = data.device; - gc.init(drawable, data, gdkGC); - return gc; + GC gc = new GC(); + auto gdkGC = drawable.internal_new_GC(data); + gc.device = data.device; + gc.init(drawable, data, gdkGC); + return gc; } void checkGC (int mask) { - int state = data.state; - if ((state & mask) is mask) return; - state = (state ^ mask) & mask; - data.state |= mask; - auto cairo = data.cairo; - if (cairo !is null) { - if ((state & (BACKGROUND | FOREGROUND)) !is 0) { - GdkColor* color; - Pattern pattern; - if ((state & FOREGROUND) !is 0) { - color = data.foreground; - pattern = data.foregroundPattern; - data.state &= ~BACKGROUND; - } else { - color = data.background; - pattern = data.backgroundPattern; - data.state &= ~FOREGROUND; - } - if (pattern !is null) { - Cairo.cairo_set_source(cairo, pattern.handle); - } else { - Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / cast(float)0xFFFF, (color.green & 0xFFFF) / cast(float)0xFFFF, (color.blue & 0xFFFF) / cast(float)0xFFFF, data.alpha / cast(float)0xFF); - } - } - if ((state & FONT) !is 0) { - if (data.layout !is null) { - OS.pango_layout_set_font_description(data.layout, data.font); - } - if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { - setCairoFont(cairo, data.font); - } - } - if ((state & LINE_CAP) !is 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; + int state = data.state; + if ((state & mask) is mask) return; + state = (state ^ mask) & mask; + data.state |= mask; + auto cairo = data.cairo; + if (cairo !is null) { + if ((state & (BACKGROUND | FOREGROUND)) !is 0) { + GdkColor* color; + Pattern pattern; + if ((state & FOREGROUND) !is 0) { + color = data.foreground; + pattern = data.foregroundPattern; + data.state &= ~BACKGROUND; + } else { + color = data.background; + pattern = data.backgroundPattern; + data.state &= ~FOREGROUND; + } + if (pattern !is null) { + Cairo.cairo_set_source(cairo, pattern.handle); + } else { + Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / cast(float)0xFFFF, (color.green & 0xFFFF) / cast(float)0xFFFF, (color.blue & 0xFFFF) / cast(float)0xFFFF, data.alpha / cast(float)0xFF); + } + } + if ((state & FONT) !is 0) { + if (data.layout !is null) { + OS.pango_layout_set_font_description(data.layout, data.font); + } + if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { + setCairoFont(cairo, data.font); + } + } + if ((state & LINE_CAP) !is 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; default: - } - Cairo.cairo_set_line_cap(cairo, cap_style); - } - if ((state & LINE_JOIN) !is 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_cap(cairo, cap_style); + } + if ((state & LINE_JOIN) !is 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; default: - } - Cairo.cairo_set_line_join(cairo, join_style); - } - if ((state & LINE_WIDTH) !is 0) { - Cairo.cairo_set_line_width(cairo, data.lineWidth is 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; + } + Cairo.cairo_set_line_join(cairo, join_style); + } + if ((state & LINE_WIDTH) !is 0) { + Cairo.cairo_set_line_width(cairo, data.lineWidth is 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; default: - } - } - if ((state & LINE_STYLE) !is 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 !is 0 ? LINE_DASH : LINE_DASH_ZERO; break; - case SWT.LINE_DOT: dashes = width !is 0 ? LINE_DOT : LINE_DOT_ZERO; break; - case SWT.LINE_DASHDOT: dashes = width !is 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; - case SWT.LINE_DASHDOTDOT: dashes = width !is 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; - case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; + } + } + if ((state & LINE_STYLE) !is 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 !is 0 ? LINE_DASH : LINE_DASH_ZERO; break; + case SWT.LINE_DOT: dashes = width !is 0 ? LINE_DOT : LINE_DOT_ZERO; break; + case SWT.LINE_DASHDOT: dashes = width !is 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; + case SWT.LINE_DASHDOTDOT: dashes = width !is 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; + case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; default: - } - if (dashes !is null) { - dashesOffset = data.lineDashesOffset; - double[] cairoDashes = new double[dashes.length]; - for (int i = 0; i < cairoDashes.length; i++) { - cairoDashes[i] = width is 0 || data.lineStyle is SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width; - } - Cairo.cairo_set_dash(cairo, cairoDashes.ptr, cairoDashes.length, dashesOffset); - } else { - Cairo.cairo_set_dash(cairo, null, 0, 0); - } - } - if ((state & LINE_MITERLIMIT) !is 0) { - Cairo.cairo_set_miter_limit(cairo, data.lineMiterLimit); - } - if ((state & DRAW_OFFSET) !is 0) { - data.cairoXoffset = data.cairoYoffset = 0; - double[] matrix = new double[6]; - Cairo.cairo_get_matrix(cairo,cast(cairo_matrix_t*) matrix.ptr); - double scaling = matrix[0]; - if (scaling < 0) scaling = -scaling; - double strokeWidth = data.lineWidth * scaling; - if (strokeWidth is 0 || (cast(int)strokeWidth % 2) is 1) { - data.cairoXoffset = 0.5 / scaling; - } - scaling = matrix[3]; - if (scaling < 0) scaling = -scaling; - strokeWidth = data.lineWidth * scaling; - if (strokeWidth is 0 || (cast(int)strokeWidth % 2) is 1) { - data.cairoYoffset = 0.5 / scaling; - } - } - return; - } - if ((state & (BACKGROUND | FOREGROUND)) !is 0) { - GdkColor* foreground; - if ((state & FOREGROUND) !is 0) { - foreground = data.foreground; - data.state &= ~BACKGROUND; - } else { - foreground = data.background; - data.state &= ~FOREGROUND; - } - OS.gdk_gc_set_foreground(handle, foreground); - } - if ((state & BACKGROUND_BG) !is 0) { - GdkColor* background = data.background; - OS.gdk_gc_set_background(handle, background); - } - if ((state & FONT) !is 0) { - if (data.layout !is null) { - OS.pango_layout_set_font_description(data.layout, data.font); - } - } - if ((state & (LINE_CAP | LINE_JOIN | LINE_STYLE | LINE_WIDTH)) !is 0) { - int cap_style = 0; - int join_style = 0; - int width = cast(int)data.lineWidth; - int line_style = 0; - float[] dashes = null; - switch (data.lineCap) { - case SWT.CAP_ROUND: cap_style = OS.GDK_CAP_ROUND; break; - case SWT.CAP_FLAT: cap_style = OS.GDK_CAP_BUTT; break; - case SWT.CAP_SQUARE: cap_style = OS.GDK_CAP_PROJECTING; break; + } + if (dashes !is null) { + dashesOffset = data.lineDashesOffset; + double[] cairoDashes = new double[dashes.length]; + for (int i = 0; i < cairoDashes.length; i++) { + cairoDashes[i] = width is 0 || data.lineStyle is SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width; + } + Cairo.cairo_set_dash(cairo, cairoDashes.ptr, cairoDashes.length, dashesOffset); + } else { + Cairo.cairo_set_dash(cairo, null, 0, 0); + } + } + if ((state & LINE_MITERLIMIT) !is 0) { + Cairo.cairo_set_miter_limit(cairo, data.lineMiterLimit); + } + if ((state & DRAW_OFFSET) !is 0) { + data.cairoXoffset = data.cairoYoffset = 0; + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo,cast(cairo_matrix_t*) matrix.ptr); + double scaling = matrix[0]; + if (scaling < 0) scaling = -scaling; + double strokeWidth = data.lineWidth * scaling; + if (strokeWidth is 0 || (cast(int)strokeWidth % 2) is 1) { + data.cairoXoffset = 0.5 / scaling; + } + scaling = matrix[3]; + if (scaling < 0) scaling = -scaling; + strokeWidth = data.lineWidth * scaling; + if (strokeWidth is 0 || (cast(int)strokeWidth % 2) is 1) { + data.cairoYoffset = 0.5 / scaling; + } + } + return; + } + if ((state & (BACKGROUND | FOREGROUND)) !is 0) { + GdkColor* foreground; + if ((state & FOREGROUND) !is 0) { + foreground = data.foreground; + data.state &= ~BACKGROUND; + } else { + foreground = data.background; + data.state &= ~FOREGROUND; + } + OS.gdk_gc_set_foreground(handle, foreground); + } + if ((state & BACKGROUND_BG) !is 0) { + GdkColor* background = data.background; + OS.gdk_gc_set_background(handle, background); + } + if ((state & FONT) !is 0) { + if (data.layout !is null) { + OS.pango_layout_set_font_description(data.layout, data.font); + } + } + if ((state & (LINE_CAP | LINE_JOIN | LINE_STYLE | LINE_WIDTH)) !is 0) { + int cap_style = 0; + int join_style = 0; + int width = cast(int)data.lineWidth; + int line_style = 0; + float[] dashes = null; + switch (data.lineCap) { + case SWT.CAP_ROUND: cap_style = OS.GDK_CAP_ROUND; break; + case SWT.CAP_FLAT: cap_style = OS.GDK_CAP_BUTT; break; + case SWT.CAP_SQUARE: cap_style = OS.GDK_CAP_PROJECTING; break; default: - } - switch (data.lineJoin) { - case SWT.JOIN_ROUND: join_style = OS.GDK_JOIN_ROUND; break; - case SWT.JOIN_MITER: join_style = OS.GDK_JOIN_MITER; break; - case SWT.JOIN_BEVEL: join_style = OS.GDK_JOIN_BEVEL; break; + } + switch (data.lineJoin) { + case SWT.JOIN_ROUND: join_style = OS.GDK_JOIN_ROUND; break; + case SWT.JOIN_MITER: join_style = OS.GDK_JOIN_MITER; break; + case SWT.JOIN_BEVEL: join_style = OS.GDK_JOIN_BEVEL; break; default: - } - switch (data.lineStyle) { - case SWT.LINE_SOLID: break; - case SWT.LINE_DASH: dashes = width !is 0 ? LINE_DASH : LINE_DASH_ZERO; break; - case SWT.LINE_DOT: dashes = width !is 0 ? LINE_DOT : LINE_DOT_ZERO; break; - case SWT.LINE_DASHDOT: dashes = width !is 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; - case SWT.LINE_DASHDOTDOT: dashes = width !is 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; - case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; + } + switch (data.lineStyle) { + case SWT.LINE_SOLID: break; + case SWT.LINE_DASH: dashes = width !is 0 ? LINE_DASH : LINE_DASH_ZERO; break; + case SWT.LINE_DOT: dashes = width !is 0 ? LINE_DOT : LINE_DOT_ZERO; break; + case SWT.LINE_DASHDOT: dashes = width !is 0 ? LINE_DASHDOT : LINE_DASHDOT_ZERO; break; + case SWT.LINE_DASHDOTDOT: dashes = width !is 0 ? LINE_DASHDOTDOT : LINE_DASHDOTDOT_ZERO; break; + case SWT.LINE_CUSTOM: dashes = data.lineDashes; break; default: - } - if (dashes !is null) { - if ((state & LINE_STYLE) !is 0) { - char[] dash_list = new char[dashes.length]; - for (int i = 0; i < dash_list.length; i++) { - dash_list[i] = cast(char)(width is 0 || data.lineStyle is SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width); - } - OS.gdk_gc_set_dashes(handle, 0, dash_list.ptr, dash_list.length); - } - line_style = OS.GDK_LINE_ON_OFF_DASH; - } else { - line_style = OS.GDK_LINE_SOLID; - } - OS.gdk_gc_set_line_attributes(handle, width, line_style, cap_style, join_style); - } + } + if (dashes !is null) { + if ((state & LINE_STYLE) !is 0) { + char[] dash_list = new char[dashes.length]; + for (int i = 0; i < dash_list.length; i++) { + dash_list[i] = cast(char)(width is 0 || data.lineStyle is SWT.LINE_CUSTOM ? dashes[i] : dashes[i] * width); + } + OS.gdk_gc_set_dashes(handle, 0, dash_list.ptr, dash_list.length); + } + line_style = OS.GDK_LINE_ON_OFF_DASH; + } else { + line_style = OS.GDK_LINE_SOLID; + } + OS.gdk_gc_set_line_attributes(handle, width, line_style, cap_style, join_style); + } } GdkRegion* convertRgn(GdkRegion* rgn, double[] matrix) { - auto newRgn = OS.gdk_region_new(); - int nRects; - GdkRectangle* rects; - OS.gdk_region_get_rectangles(rgn, &rects, &nRects); - GdkRectangle* rect = new GdkRectangle(); - int[] pointArray = new int[8]; - double x, y; - for (int i=0; i */ public void copyArea(Image image, int x, int y) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (image.type !is SWT.BITMAP || image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - Rectangle rect = image.getBounds(); - auto gdkGC = OS.gdk_gc_new(image.pixmap); - if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.gdk_gc_set_subwindow(gdkGC, OS.GDK_INCLUDE_INFERIORS); - OS.gdk_draw_drawable(image.pixmap, gdkGC, data.drawable, x, y, 0, 0, rect.width, rect.height); - OS.g_object_unref(gdkGC); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image.type !is SWT.BITMAP || image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + Rectangle rect = image.getBounds(); + auto gdkGC = OS.gdk_gc_new(image.pixmap); + if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.gdk_gc_set_subwindow(gdkGC, OS.GDK_INCLUDE_INFERIORS); + OS.gdk_draw_drawable(image.pixmap, gdkGC, data.drawable, x, y, 0, 0, rect.width, rect.height); + OS.g_object_unref(gdkGC); } /** @@ -504,7 +504,7 @@ * */ public void copyArea(int srcX, int srcY, int width, int height, int destX, int destY) { - copyArea(srcX, srcY, width, height, destX, destY, true); + copyArea(srcX, srcY, width, height, destX, destY, true); } /** * Copies a rectangular area of the receiver at the source @@ -525,69 +525,69 @@ * @since 3.1 */ public void copyArea(int srcX, int srcY, int width, int height, int destX, int destY, bool paint) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (width <= 0 || height <= 0) return; - int deltaX = destX - srcX, deltaY = destY - srcY; - if (deltaX is 0 && deltaY is 0) return; - auto drawable = data.drawable; - if (data.image is null && paint) OS.gdk_gc_set_exposures(handle, true); - OS.gdk_draw_drawable(drawable, handle, drawable, srcX, srcY, destX, destY, width, height); - if (data.image is null & paint) { - OS.gdk_gc_set_exposures(handle, false); - bool disjoint = (destX + width < srcX) || (srcX + width < destX) || (destY + height < srcY) || (srcY + height < destY); - GdkRectangle* rect = new GdkRectangle (); - if (disjoint) { - rect.x = srcX; - rect.y = srcY; - rect.width = width; - rect.height = height; - OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); -// OS.gdk_window_clear_area_e(drawable, srcX, srcY, width, height); - } else { - if (deltaX !is 0) { - int newX = destX - deltaX; - if (deltaX < 0) newX = destX + width; - rect.x = newX; - rect.y = srcY; - rect.width = Math.abs(deltaX); - rect.height = height; - OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); -// OS.gdk_window_clear_area_e(drawable, newX, srcY, Math.abs(deltaX), height); - } - if (deltaY !is 0) { - int newY = destY - deltaY; - if (deltaY < 0) newY = destY + height; - rect.x = srcX; - rect.y = newY; - rect.width = width; - rect.height = Math.abs(deltaY); - OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); -// OS.gdk_window_clear_area_e(drawable, srcX, newY, width, Math.abs(deltaY)); - } - } - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width <= 0 || height <= 0) return; + int deltaX = destX - srcX, deltaY = destY - srcY; + if (deltaX is 0 && deltaY is 0) return; + auto drawable = data.drawable; + if (data.image is null && paint) OS.gdk_gc_set_exposures(handle, true); + OS.gdk_draw_drawable(drawable, handle, drawable, srcX, srcY, destX, destY, width, height); + if (data.image is null & paint) { + OS.gdk_gc_set_exposures(handle, false); + bool disjoint = (destX + width < srcX) || (srcX + width < destX) || (destY + height < srcY) || (srcY + height < destY); + GdkRectangle* rect = new GdkRectangle (); + if (disjoint) { + rect.x = srcX; + rect.y = srcY; + rect.width = width; + rect.height = height; + OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); +// OS.gdk_window_clear_area_e(drawable, srcX, srcY, width, height); + } else { + if (deltaX !is 0) { + int newX = destX - deltaX; + if (deltaX < 0) newX = destX + width; + rect.x = newX; + rect.y = srcY; + rect.width = Math.abs(deltaX); + rect.height = height; + OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); +// OS.gdk_window_clear_area_e(drawable, newX, srcY, Math.abs(deltaX), height); + } + if (deltaY !is 0) { + int newY = destY - deltaY; + if (deltaY < 0) newY = destY + height; + rect.x = srcX; + rect.y = newY; + rect.width = width; + rect.height = Math.abs(deltaY); + OS.gdk_window_invalidate_rect (cast(GdkWindow*)drawable, rect, false); +// OS.gdk_window_clear_area_e(drawable, srcX, newY, width, Math.abs(deltaY)); + } + } + } } void createLayout() { - auto context = OS.gdk_pango_context_get(); - if (context is null) SWT.error(SWT.ERROR_NO_HANDLES); - data.context = context; - auto layout = OS.pango_layout_new(context); - if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); - data.layout = layout; - OS.pango_context_set_language(context, OS.gtk_get_default_language()); - OS.pango_context_set_base_dir(context, OS.PANGO_DIRECTION_LTR); - OS.gdk_pango_context_set_colormap(context, OS.gdk_colormap_get_system()); - if (OS.GTK_VERSION >= OS.buildVERSION(2, 4, 0)) { - OS.pango_layout_set_auto_dir(layout, false); - } + auto context = OS.gdk_pango_context_get(); + if (context is null) SWT.error(SWT.ERROR_NO_HANDLES); + data.context = context; + auto layout = OS.pango_layout_new(context); + if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); + data.layout = layout; + OS.pango_context_set_language(context, OS.gtk_get_default_language()); + OS.pango_context_set_base_dir(context, OS.PANGO_DIRECTION_LTR); + OS.gdk_pango_context_set_colormap(context, OS.gdk_colormap_get_system()); + if (OS.GTK_VERSION >= OS.buildVERSION(2, 4, 0)) { + OS.pango_layout_set_auto_dir(layout, false); + } } void disposeLayout() { - data.str = null; - if (data.context !is null) OS.g_object_unref(data.context); - if (data.layout !is null) OS.g_object_unref(data.layout); - data.layout = null; + data.str = null; + if (data.context !is null) OS.g_object_unref(data.context); + if (data.layout !is null) OS.g_object_unref(data.layout); + data.layout = null; data.context = null; } @@ -601,39 +601,39 @@ * */ public void dispose() { - if (handle is null) return; - if (data.device.isDisposed()) return; + if (handle is null) return; + if (data.device.isDisposed()) return; - if (data.disposeCairo) { - auto cairo = data.cairo; - if (cairo !is null) Cairo.cairo_destroy(cairo); - data.cairo = null; - } + if (data.disposeCairo) { + auto cairo = data.cairo; + if (cairo !is null) Cairo.cairo_destroy(cairo); + data.cairo = null; + } - /* Free resources */ - auto clipRgn = data.clipRgn; - if (clipRgn !is null) OS.gdk_region_destroy(clipRgn); - Image image = data.image; - if (image !is null) { - image.memGC = null; - if (image.transparentPixel !is -1) image.createMask(); - } + /* Free resources */ + auto clipRgn = data.clipRgn; + if (clipRgn !is null) OS.gdk_region_destroy(clipRgn); + Image image = data.image; + if (image !is null) { + image.memGC = null; + if (image.transparentPixel !is -1) image.createMask(); + } - disposeLayout(); + disposeLayout(); - /* Dispose the GC */ - Device device = data.device; - drawable.internal_dispose_GC(handle, data); + /* Dispose the GC */ + Device device = data.device; + drawable.internal_dispose_GC(handle, data); - data.drawable = null; + data.drawable = null; data.clipRgn = null; - drawable = null; - handle = null; - data.image = null; - data.str = null; - if (device.tracking) device.dispose_Object(this); - data.device = null; - data = null; + drawable = null; + handle = null; + data.image = null; + data.str = null; + if (device.tracking) device.dispose_Object(this); + data.device = null; + data = null; } /** @@ -666,41 +666,41 @@ * */ public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { - if (handle is null) 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 is 0 || height is 0 || arcAngle is 0) return; - auto cairo = data.cairo; - if (cairo !is null) { - double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; - if (width is height) { + if (handle is null) 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 is 0 || height is 0 || arcAngle is 0) return; + auto cairo = data.cairo; + if (cairo !is null) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + if (width is height) { if (arcAngle >= 0) { Cairo.cairo_arc_negative(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); } else { Cairo.cairo_arc(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(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); + } 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 * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); } else { Cairo.cairo_arc(cairo, 0, 0, 1, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); } - Cairo.cairo_restore(cairo); - } - Cairo.cairo_stroke(cairo); - return; - } - OS.gdk_draw_arc(data.drawable, handle, 0, x, y, width, height, startAngle * 64, arcAngle * 64); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_stroke(cairo); + return; + } + OS.gdk_draw_arc(data.drawable, handle, 0, x, y, width, height, startAngle * 64, arcAngle * 64); } /** @@ -721,32 +721,32 @@ * @see #drawRectangle(int, int, int, int) */ public void drawFocus(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - /* - * Feature in GTK. The function gtk_widget_get_default_style() - * can't be used here because gtk_paint_focus() uses GCs, which - * are not valid in the default style. The fix is to use a style - * from a widget. - */ - auto style = OS.gtk_widget_get_style(data.device.shellHandle); - auto cairo = data.cairo; - if (cairo !is null) { - checkGC(FOREGROUND); - int lineWidth; - OS.gtk_widget_style_get1(data.device.shellHandle, OS.focus_line_width.ptr, &lineWidth ); - Cairo.cairo_save(cairo); - Cairo.cairo_set_line_width(cairo, lineWidth); - double[] dashes = [1, 1]; - double dash_offset = -lineWidth / 2f; - while (dash_offset < 0) dash_offset += 2; - Cairo.cairo_set_dash(cairo, dashes.ptr, dashes.length, dash_offset); - Cairo.cairo_rectangle(cairo, x + lineWidth / 2f, y + lineWidth / 2f, width, height); - Cairo.cairo_stroke(cairo); - Cairo.cairo_restore(cairo); - return; - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + /* + * Feature in GTK. The function gtk_widget_get_default_style() + * can't be used here because gtk_paint_focus() uses GCs, which + * are not valid in the default style. The fix is to use a style + * from a widget. + */ + auto style = OS.gtk_widget_get_style(data.device.shellHandle); + auto cairo = data.cairo; + if (cairo !is null) { + checkGC(FOREGROUND); + int lineWidth; + OS.gtk_widget_style_get1(data.device.shellHandle, OS.focus_line_width.ptr, &lineWidth ); + Cairo.cairo_save(cairo); + Cairo.cairo_set_line_width(cairo, lineWidth); + double[] dashes = [1, 1]; + double dash_offset = -lineWidth / 2f; + while (dash_offset < 0) dash_offset += 2; + Cairo.cairo_set_dash(cairo, dashes.ptr, dashes.length, dash_offset); + Cairo.cairo_rectangle(cairo, x + lineWidth / 2f, y + lineWidth / 2f, width, height); + Cairo.cairo_stroke(cairo); + Cairo.cairo_restore(cairo); + return; + } char dummy; - OS.gtk_paint_focus(style,cast(GdkWindow *) data.drawable, OS.GTK_STATE_NORMAL, null, data.device.shellHandle, &dummy, x, y, width, height); + OS.gtk_paint_focus(style,cast(GdkWindow *) data.drawable, OS.GTK_STATE_NORMAL, null, data.device.shellHandle, &dummy, x, y, width, height); } /** @@ -769,10 +769,10 @@ * */ public void drawImage(Image image, int x, int y) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (image is 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); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (image is 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); } /** @@ -808,360 +808,360 @@ * */ public void drawImage(Image image, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (srcWidth is 0 || srcHeight is 0 || destWidth is 0 || destHeight is 0) return; - if (srcX < 0 || srcY < 0 || srcWidth < 0 || srcHeight < 0 || destWidth < 0 || destHeight < 0) { - SWT.error (SWT.ERROR_INVALID_ARGUMENT); - } - if (image is 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); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (srcWidth is 0 || srcHeight is 0 || destWidth is 0 || destHeight is 0) return; + if (srcX < 0 || srcY < 0 || srcWidth < 0 || srcHeight < 0 || destWidth < 0 || destHeight < 0) { + SWT.error (SWT.ERROR_INVALID_ARGUMENT); + } + if (image is 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, bool simple) { - int width; - int height; - OS.gdk_drawable_get_size(srcImage.pixmap, &width, &height); - int imgWidth = width; - int imgHeight = height; - if (simple) { - srcWidth = destWidth = imgWidth; - srcHeight = destHeight = imgHeight; - } else { - simple = srcX is 0 && srcY is 0 && - srcWidth is destWidth && destWidth is imgWidth && - srcHeight is destHeight && destHeight is imgHeight; - if (srcX + srcWidth > imgWidth || srcY + srcHeight > imgHeight) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - } - auto cairo = data.cairo; - if (cairo !is null) { - if (data.alpha !is 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 !is destWidth || srcHeight !is destHeight) { - Cairo.cairo_scale(cairo, destWidth / cast(float)srcWidth, destHeight / cast(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 width; + int height; + OS.gdk_drawable_get_size(srcImage.pixmap, &width, &height); + int imgWidth = width; + int imgHeight = height; + if (simple) { + srcWidth = destWidth = imgWidth; + srcHeight = destHeight = imgHeight; + } else { + simple = srcX is 0 && srcY is 0 && + srcWidth is destWidth && destWidth is imgWidth && + srcHeight is destHeight && destHeight is imgHeight; + if (srcX + srcWidth > imgWidth || srcY + srcHeight > imgHeight) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + auto cairo = data.cairo; + if (cairo !is null) { + if (data.alpha !is 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 !is destWidth || srcHeight !is destHeight) { + Cairo.cairo_scale(cairo, destWidth / cast(float)srcWidth, destHeight / cast(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; default: - } - auto pattern = Cairo.cairo_pattern_create_for_surface(srcImage.surface); - if (pattern is null) SWT.error(SWT.ERROR_NO_HANDLES); - if (srcWidth !is destWidth || srcHeight !is 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, 0)) { - auto surface = Cairo.cairo_image_surface_create(Cairo.CAIRO_FORMAT_ARGB32, imgWidth * 3, imgHeight * 3); - auto 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); - auto newPattern = Cairo.cairo_pattern_create_for_surface(surface); - Cairo.cairo_surface_destroy(surface); - if (newPattern is null) 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(cast(cairo_matrix_t*)matrix.ptr, imgWidth, imgHeight); - Cairo.cairo_pattern_set_matrix(pattern, cast(cairo_matrix_t*)matrix.ptr); - } -// 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 !is 0xFF) { - Cairo.cairo_paint_with_alpha(cairo, data.alpha / cast(float)0xFF); - } else { - Cairo.cairo_paint(cairo); - } - Cairo.cairo_restore(cairo); - Cairo.cairo_pattern_destroy(pattern); - } - return; - } - if (srcImage.alpha !is -1 || srcImage.alphaData !is null) { - drawImageAlpha(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); - } else if (srcImage.transparentPixel !is -1 || srcImage.mask !is null) { - drawImageMask(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); - } else { - drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); - } + } + auto pattern = Cairo.cairo_pattern_create_for_surface(srcImage.surface); + if (pattern is null) SWT.error(SWT.ERROR_NO_HANDLES); + if (srcWidth !is destWidth || srcHeight !is 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, 0)) { + auto surface = Cairo.cairo_image_surface_create(Cairo.CAIRO_FORMAT_ARGB32, imgWidth * 3, imgHeight * 3); + auto 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); + auto newPattern = Cairo.cairo_pattern_create_for_surface(surface); + Cairo.cairo_surface_destroy(surface); + if (newPattern is null) 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(cast(cairo_matrix_t*)matrix.ptr, imgWidth, imgHeight); + Cairo.cairo_pattern_set_matrix(pattern, cast(cairo_matrix_t*)matrix.ptr); + } +// 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 !is 0xFF) { + Cairo.cairo_paint_with_alpha(cairo, data.alpha / cast(float)0xFF); + } else { + Cairo.cairo_paint(cairo); + } + Cairo.cairo_restore(cairo); + Cairo.cairo_pattern_destroy(pattern); + } + return; + } + if (srcImage.alpha !is -1 || srcImage.alphaData !is null) { + drawImageAlpha(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); + } else if (srcImage.transparentPixel !is -1 || srcImage.mask !is null) { + drawImageMask(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); + } else { + drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); + } } void drawImage(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, bool simple, int imgWidth, int imgHeight) { - if (srcWidth is destWidth && srcHeight is destHeight) { - OS.gdk_draw_drawable(data.drawable, handle, srcImage.pixmap, srcX, srcY, destX, destY, destWidth, destHeight); - } else { - if (device.useXRender) { - drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, null, -1); - return; - } - auto pixbuf = scale(srcImage.pixmap, srcX, srcY, srcWidth, srcHeight, destWidth, destHeight); - if (pixbuf !is null) { - OS.gdk_pixbuf_render_to_drawable(pixbuf, data.drawable, handle, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_RGB_DITHER_NORMAL, 0, 0); - OS.g_object_unref(pixbuf); - } - } + if (srcWidth is destWidth && srcHeight is destHeight) { + OS.gdk_draw_drawable(data.drawable, handle, srcImage.pixmap, srcX, srcY, destX, destY, destWidth, destHeight); + } else { + if (device.useXRender) { + drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, null, -1); + return; + } + auto pixbuf = scale(srcImage.pixmap, srcX, srcY, srcWidth, srcHeight, destWidth, destHeight); + if (pixbuf !is null) { + OS.gdk_pixbuf_render_to_drawable(pixbuf, data.drawable, handle, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_RGB_DITHER_NORMAL, 0, 0); + OS.g_object_unref(pixbuf); + } + } } void drawImageAlpha(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, bool simple, int imgWidth, int imgHeight) { - if (srcImage.alpha is 0) return; - if (srcImage.alpha is 255) { - drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); - return; - } - if (device.useXRender) { - drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, srcImage.mask, OS.PictStandardA8); - return; - } - auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, true, 8, srcWidth, srcHeight); - if (pixbuf is null) return; - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_pixbuf_get_from_drawable(pixbuf, srcImage.pixmap, colormap, srcX, srcY, 0, 0, srcWidth, srcHeight); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] line = new byte[stride]; - byte alpha = cast(byte)srcImage.alpha; - byte[] alphaData = srcImage.alphaData; - for (int y=0; y= OS.buildVERSION (2, 2, 0)) { - OS.gdk_draw_pixbuf(data.drawable, handle, pixbuf, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_RGB_DITHER_NORMAL, 0, 0); - } else { - OS.gdk_pixbuf_render_to_drawable_alpha(pixbuf, data.drawable, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_PIXBUF_ALPHA_BILEVEL, 128, OS.GDK_RGB_DITHER_NORMAL, 0, 0); - } - OS.g_object_unref(pixbuf); + if (srcImage.alpha is 0) return; + if (srcImage.alpha is 255) { + drawImage(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight); + return; + } + if (device.useXRender) { + drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, srcImage.mask, OS.PictStandardA8); + return; + } + auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, true, 8, srcWidth, srcHeight); + if (pixbuf is null) return; + auto colormap = OS.gdk_colormap_get_system(); + OS.gdk_pixbuf_get_from_drawable(pixbuf, srcImage.pixmap, colormap, srcX, srcY, 0, 0, srcWidth, srcHeight); + int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); + auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); + byte[] line = new byte[stride]; + byte alpha = cast(byte)srcImage.alpha; + byte[] alphaData = srcImage.alphaData; + for (int y=0; y= OS.buildVERSION (2, 2, 0)) { + OS.gdk_draw_pixbuf(data.drawable, handle, pixbuf, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_RGB_DITHER_NORMAL, 0, 0); + } else { + OS.gdk_pixbuf_render_to_drawable_alpha(pixbuf, data.drawable, 0, 0, destX, destY, destWidth, destHeight, OS.GDK_PIXBUF_ALPHA_BILEVEL, 128, OS.GDK_RGB_DITHER_NORMAL, 0, 0); + } + OS.g_object_unref(pixbuf); } void drawImageMask(Image srcImage, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight, bool simple, int imgWidth, int imgHeight) { - auto drawable = data.drawable; - auto colorPixmap = srcImage.pixmap; - /* Generate the mask if necessary. */ - if (srcImage.transparentPixel !is -1) srcImage.createMask(); - auto maskPixmap = srcImage.mask; + auto drawable = data.drawable; + auto colorPixmap = srcImage.pixmap; + /* Generate the mask if necessary. */ + if (srcImage.transparentPixel !is -1) srcImage.createMask(); + auto maskPixmap = srcImage.mask; - if (device.useXRender) { - drawImageXRender(srcImage, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, simple, imgWidth, imgHeight, maskPixmap, OS.PictStandardA1); - } else { - if (srcWidth !is destWidth || srcHeight !is destHeight) { - auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, true, 8, srcWidth, srcHeight); - if (pixbuf !is null) { - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_pixbuf_get_from_drawable(pixbuf, colorPixmap, colormap, srcX, srcY, 0, 0, srcWidth, srcHeight); - auto maskPixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, srcWidth, srcHeight); - if (maskPixbuf !is null) { - OS.gdk_pixbuf_get_from_drawable(maskPixbuf, maskPixmap, null, srcX, srcY, 0, 0, srcWidth, srcHeight); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] line = new byte[stride]; - int maskStride = OS.gdk_pixbuf_get_rowstride(maskPixbuf); - auto maskPixels = OS.gdk_pixbuf_get_pixels(maskPixbuf); - byte[] maskLine = new byte[maskStride]; - for (int y=0; y */ public void drawLine(int x1, int y1, int x2, int y2) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(DRAW); - auto cairo = data.cairo; - if (cairo !is null) { - 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.gdk_draw_line (data.drawable, handle, x1, y1, x2, y2); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + auto cairo = data.cairo; + if (cairo !is null) { + 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.gdk_draw_line (data.drawable, handle, x1, y1, x2, y2); } /** @@ -1213,32 +1213,32 @@ * */ public void drawOval(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(DRAW); - if (width < 0) { - x = x + width; - width = -width; - } - if (height < 0) { - y = y + height; - height = -height; - } - auto cairo = data.cairo; - if (cairo !is null) { - double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; - if (width is height) { - Cairo.cairo_arc_negative(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, 0, -2 * cast(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 * cast(float)Compatibility.PI); - Cairo.cairo_restore(cairo); - } - Cairo.cairo_stroke(cairo); - return; - } - OS.gdk_draw_arc(data.drawable, handle, 0, x, y, width, height, 0, 23040); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + auto cairo = data.cairo; + if (cairo !is null) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + if (width is height) { + Cairo.cairo_arc_negative(cairo, x + xOffset + width / 2f, y + yOffset + height / 2f, width / 2f, 0, -2 * cast(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 * cast(float)Compatibility.PI); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_stroke(cairo); + return; + } + OS.gdk_draw_arc(data.drawable, handle, 0, x, y, width, height, 0, 23040); } /** @@ -1265,21 +1265,21 @@ * @since 3.1 */ public void drawPath(Path path) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (path.handle is null) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - initCairo(); - checkGC(DRAW); - auto cairo = data.cairo; - Cairo.cairo_save(cairo); - double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; - Cairo.cairo_translate(cairo, xOffset, yOffset); - auto copy = Cairo.cairo_copy_path(path.handle); - if (copy is null) 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); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (path.handle is null) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + initCairo(); + checkGC(DRAW); + auto cairo = data.cairo; + Cairo.cairo_save(cairo); + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_translate(cairo, xOffset, yOffset); + auto copy = Cairo.cairo_copy_path(path.handle); + if (copy is null) 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); } /** @@ -1300,15 +1300,15 @@ * @since 3.0 */ public void drawPoint (int x, int y) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(DRAW); - auto cairo = data.cairo; - if (cairo !is null) { - Cairo.cairo_rectangle(cairo, x, y, 1, 1); - Cairo.cairo_fill(cairo); - return; - } - OS.gdk_draw_point(data.drawable, handle, x, y); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + auto cairo = data.cairo; + if (cairo !is null) { + Cairo.cairo_rectangle(cairo, x, y, 1, 1); + Cairo.cairo_fill(cairo); + return; + } + OS.gdk_draw_point(data.drawable, handle, x, y); } /** @@ -1329,16 +1329,16 @@ * */ public void drawPolygon(int[] pointArray) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - checkGC(DRAW); - auto cairo = data.cairo; - if (cairo !is null) { - drawPolyline(cairo, pointArray, true); - Cairo.cairo_stroke(cairo); - return; - } - OS.gdk_draw_polygon(data.drawable, handle, 0, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(DRAW); + auto cairo = data.cairo; + if (cairo !is null) { + drawPolyline(cairo, pointArray, true); + Cairo.cairo_stroke(cairo); + return; + } + OS.gdk_draw_polygon(data.drawable, handle, 0, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); } /** @@ -1359,27 +1359,27 @@ * */ public void drawPolyline(int[] pointArray) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - checkGC(DRAW); - auto cairo = data.cairo; - if (cairo !is null) { - drawPolyline(cairo, pointArray, false); - Cairo.cairo_stroke(cairo); - return; - } - OS.gdk_draw_lines(data.drawable, handle, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(DRAW); + auto cairo = data.cairo; + if (cairo !is null) { + drawPolyline(cairo, pointArray, false); + Cairo.cairo_stroke(cairo); + return; + } + OS.gdk_draw_lines(data.drawable, handle, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); } void drawPolyline(cairo_t* cairo, int[] pointArray, bool close) { - int count = pointArray.length / 2; - if (count is 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); + int count = pointArray.length / 2; + if (count is 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); } /** @@ -1398,24 +1398,24 @@ * */ public void drawRectangle(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(DRAW); - if (width < 0) { - x = x + width; - width = -width; - } - if (height < 0) { - y = y + height; - height = -height; - } - auto cairo = data.cairo; - if (cairo !is null) { - double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; - Cairo.cairo_rectangle(cairo, x + xOffset, y + yOffset, width, height); - Cairo.cairo_stroke(cairo); - return; - } - OS.gdk_draw_rectangle(data.drawable, handle, 0, x, y, width, height); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(DRAW); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + auto cairo = data.cairo; + if (cairo !is null) { + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + Cairo.cairo_rectangle(cairo, x + xOffset, y + yOffset, width, height); + Cairo.cairo_stroke(cairo); + return; + } + OS.gdk_draw_rectangle(data.drawable, handle, 0, x, y, width, height); } /** @@ -1435,8 +1435,8 @@ * */ public void drawRectangle(Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - drawRectangle (rect.x, rect.y, rect.width, rect.height); + if (rect is 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 @@ -1460,73 +1460,73 @@ * */ public void drawRoundRectangle(int x, int y, int width, int height, int arcWidth, int arcHeight) { - if (handle is null) 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; - auto cairo = data.cairo; - if (cairo !is null) { - float naw2 = naw / 2f; - float nah2 = nah / 2f; - float fw = nw / naw2; - float fh = nh / nah2; - Cairo.cairo_save(cairo); - double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; - 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; - auto drawable = data.drawable; - if (nw > naw) { - if (nh > nah) { - OS.gdk_draw_arc(drawable, handle, 0, nx, ny, naw, nah, 5760, 5760); - OS.gdk_draw_line(drawable, handle, nx + naw2, ny, nx + nw - naw2, ny); - OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny, naw, nah, 0, 5760); - OS.gdk_draw_line(drawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); - OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); - OS.gdk_draw_line(drawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); - OS.gdk_draw_arc(drawable, handle, 0, nx, ny + nh - nah, naw, nah, 11520, 5760); - OS.gdk_draw_line(drawable, handle, nx, ny + nah2, nx, ny + nh - nah2); - } else { - OS.gdk_draw_arc(drawable, handle, 0, nx, ny, naw, nh, 5760, 11520); - OS.gdk_draw_line(drawable, handle, nx + naw2, ny, nx + nw - naw2, ny); - OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny, naw, nh, 17280, 11520); - OS.gdk_draw_line(drawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); - } - } else { - if (nh > nah) { - OS.gdk_draw_arc(drawable, handle, 0, nx, ny, nw, nah, 0, 11520); - OS.gdk_draw_line(drawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); - OS.gdk_draw_arc(drawable, handle, 0, nx, ny + nh - nah, nw, nah, 11520, 11520); - OS.gdk_draw_line(drawable,handle, nx, ny + nah2, nx, ny + nh - nah2); - } else { - OS.gdk_draw_arc(drawable, handle, 0, nx, ny, nw, nh, 0, 23040); - } - } + if (handle is null) 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; + auto cairo = data.cairo; + if (cairo !is null) { + float naw2 = naw / 2f; + float nah2 = nah / 2f; + float fw = nw / naw2; + float fh = nh / nah2; + Cairo.cairo_save(cairo); + double xOffset = data.cairoXoffset, yOffset = data.cairoYoffset; + 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; + auto drawable = data.drawable; + if (nw > naw) { + if (nh > nah) { + OS.gdk_draw_arc(drawable, handle, 0, nx, ny, naw, nah, 5760, 5760); + OS.gdk_draw_line(drawable, handle, nx + naw2, ny, nx + nw - naw2, ny); + OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny, naw, nah, 0, 5760); + OS.gdk_draw_line(drawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); + OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); + OS.gdk_draw_line(drawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); + OS.gdk_draw_arc(drawable, handle, 0, nx, ny + nh - nah, naw, nah, 11520, 5760); + OS.gdk_draw_line(drawable, handle, nx, ny + nah2, nx, ny + nh - nah2); + } else { + OS.gdk_draw_arc(drawable, handle, 0, nx, ny, naw, nh, 5760, 11520); + OS.gdk_draw_line(drawable, handle, nx + naw2, ny, nx + nw - naw2, ny); + OS.gdk_draw_arc(drawable, handle, 0, nx + nw - naw, ny, naw, nh, 17280, 11520); + OS.gdk_draw_line(drawable,handle, nx + naw2, ny + nh, nx + nw - naw2, ny + nh); + } + } else { + if (nh > nah) { + OS.gdk_draw_arc(drawable, handle, 0, nx, ny, nw, nah, 0, 11520); + OS.gdk_draw_line(drawable, handle, nx + nw, ny + nah2, nx + nw, ny + nh - nah2); + OS.gdk_draw_arc(drawable, handle, 0, nx, ny + nh - nah, nw, nah, 11520, 11520); + OS.gdk_draw_line(drawable,handle, nx, ny + nah2, nx, ny + nh - nah2); + } else { + OS.gdk_draw_arc(drawable, handle, 0, nx, ny, nw, nh, 0, 23040); + } + } } /** @@ -1548,7 +1548,7 @@ * */ public void drawString (char[] str, int x, int y) { - drawString(str, x, y, false); + drawString(str, x, y, false); } /** * Draws the given str, using the receiver's current font and @@ -1571,7 +1571,7 @@ * */ public void drawString(char[] str, int x, int y, bool isTransparent) { - drawText(str, x, y, isTransparent ? SWT.DRAW_TRANSPARENT : 0); + drawText(str, x, y, isTransparent ? SWT.DRAW_TRANSPARENT : 0); } /** @@ -1593,7 +1593,7 @@ * */ public void drawText(char[] str, int x, int y) { - drawText(str, x, y, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); + drawText(str, x, y, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); } /** @@ -1617,9 +1617,9 @@ * */ public void drawText(char[] str, int x, int y, bool isTransparent) { - int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB; - if (isTransparent) flags |= SWT.DRAW_TRANSPARENT; - drawText(str, x, y, flags); + int flags = SWT.DRAW_DELIMITER | SWT.DRAW_TAB; + if (isTransparent) flags |= SWT.DRAW_TRANSPARENT; + drawText(str, x, y, flags); } /** @@ -1657,62 +1657,62 @@ * */ public void drawText (char[] str, int x, int y, int flags) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (str.length is 0) return; - auto cairo = data.cairo; - if (cairo !is null) { - if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 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); - char[] buffer = str.dup; - Cairo.cairo_show_text(cairo, buffer.ptr); - Cairo.cairo_new_path(cairo); - return; - } - } - setString(str, flags); - if (cairo !is null) { - if ((flags & SWT.DRAW_TRANSPARENT) is 0) { - checkGC(BACKGROUND); - int width, height; - OS.pango_layout_get_size(data.layout, &width, &height); - Cairo.cairo_rectangle(cairo, x, y, OS.PANGO_PIXELS(width), OS.PANGO_PIXELS(height)); - Cairo.cairo_fill(cairo); - } - checkGC(FOREGROUND | FONT); - Cairo.cairo_move_to(cairo, x, y); - OS.pango_cairo_show_layout(cairo, data.layout); - return; - } - checkGC(FOREGROUND | FONT | BACKGROUND_BG); - GdkColor* background = null; - if ((flags & SWT.DRAW_TRANSPARENT) is 0) background = data.background; - if (!data.xorMode) { - OS.gdk_draw_layout_with_colors(data.drawable, handle, x, y, data.layout, null, background); - } else { - auto layout = data.layout; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (str.length is 0) return; + auto cairo = data.cairo; + if (cairo !is null) { + if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 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); + char[] buffer = str.dup; + Cairo.cairo_show_text(cairo, buffer.ptr); + Cairo.cairo_new_path(cairo); + return; + } + } + setString(str, flags); + if (cairo !is null) { + if ((flags & SWT.DRAW_TRANSPARENT) is 0) { + checkGC(BACKGROUND); + int width, height; + OS.pango_layout_get_size(data.layout, &width, &height); + Cairo.cairo_rectangle(cairo, x, y, OS.PANGO_PIXELS(width), OS.PANGO_PIXELS(height)); + Cairo.cairo_fill(cairo); + } + checkGC(FOREGROUND | FONT); + Cairo.cairo_move_to(cairo, x, y); + OS.pango_cairo_show_layout(cairo, data.layout); + return; + } + checkGC(FOREGROUND | FONT | BACKGROUND_BG); + GdkColor* background = null; + if ((flags & SWT.DRAW_TRANSPARENT) is 0) background = data.background; + if (!data.xorMode) { + OS.gdk_draw_layout_with_colors(data.drawable, handle, x, y, data.layout, null, background); + } else { + auto layout = data.layout; int w, h; - OS.pango_layout_get_size(layout, &w, &h); - int width = OS.PANGO_PIXELS(w); - int height = OS.PANGO_PIXELS(h); - auto pixmap = OS.gdk_pixmap_new(cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); - if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto gdkGC = OS.gdk_gc_new(cast(GdkDrawable*)pixmap); - if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); - GdkColor* black = new GdkColor(); - OS.gdk_gc_set_foreground(gdkGC, black); - OS.gdk_draw_rectangle(cast(GdkDrawable*)pixmap, gdkGC, 1, 0, 0, width, height); - OS.gdk_gc_set_foreground(gdkGC, data.foreground); - OS.gdk_draw_layout_with_colors(cast(GdkDrawable*)pixmap, gdkGC, 0, 0, layout, null, background); - OS.g_object_unref(gdkGC); - OS.gdk_draw_drawable(data.drawable, handle, cast(GdkDrawable*)pixmap, 0, 0, x, y, width, height); - OS.g_object_unref(pixmap); - } + OS.pango_layout_get_size(layout, &w, &h); + int width = OS.PANGO_PIXELS(w); + int height = OS.PANGO_PIXELS(h); + auto pixmap = OS.gdk_pixmap_new(cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); + if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto gdkGC = OS.gdk_gc_new(cast(GdkDrawable*)pixmap); + if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); + GdkColor* black = new GdkColor(); + OS.gdk_gc_set_foreground(gdkGC, black); + OS.gdk_draw_rectangle(cast(GdkDrawable*)pixmap, gdkGC, 1, 0, 0, width, height); + OS.gdk_gc_set_foreground(gdkGC, data.foreground); + OS.gdk_draw_layout_with_colors(cast(GdkDrawable*)pixmap, gdkGC, 0, 0, layout, null, background); + OS.g_object_unref(gdkGC); + OS.gdk_draw_drawable(data.drawable, handle, cast(GdkDrawable*)pixmap, 0, 0, x, y, width, height); + OS.g_object_unref(pixmap); + } } /** @@ -1726,8 +1726,8 @@ * @see #hashCode */ public override int opEquals(Object object) { - if (object is this) return true; - if ( auto gc = cast(GC)object){ + if (object is this) return true; + if ( auto gc = cast(GC)object){ return handle is gc.handle; } return false; @@ -1767,42 +1767,42 @@ * @see #drawArc */ public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) { - if (handle is null) 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 is 0 || height is 0 || arcAngle is 0) return; - auto cairo = data.cairo; - if (cairo !is null) { - if (width is height) { + if (handle is null) 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 is 0 || height is 0 || arcAngle is 0) return; + auto cairo = data.cairo; + if (cairo !is null) { + if (width is height) { if (arcAngle >= 0) { - Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); } else { - Cairo.cairo_arc(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + Cairo.cairo_arc(cairo, x + width / 2f, y + height / 2f, width / 2f, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(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 * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } else { - Cairo.cairo_arc(cairo, 0, 0, 1, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } - Cairo.cairo_line_to(cairo, 0, 0); - Cairo.cairo_restore(cairo); - } - Cairo.cairo_fill(cairo); - return; - } - OS.gdk_draw_arc(data.drawable, handle, 1, x, y, width, height, startAngle * 64, arcAngle * 64); + 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 * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(cairo, 0, 0, 1, -startAngle * cast(float)Compatibility.PI / 180, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } + Cairo.cairo_line_to(cairo, 0, 0); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_fill(cairo); + return; + } + OS.gdk_draw_arc(data.drawable, handle, 1, x, y, width, height, startAngle * 64, arcAngle * 64); } /** @@ -1826,58 +1826,58 @@ * @see #drawRectangle(int, int, int, int) */ public void fillGradientRectangle(int x, int y, int width, int height, bool vertical) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if ((width is 0) || (height is 0)) return; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if ((width is 0) || (height is 0)) return; - /* Rewrite this to use GdkPixbuf */ + /* Rewrite this to use GdkPixbuf */ - RGB backgroundRGB, foregroundRGB; - backgroundRGB = getBackground().getRGB(); - foregroundRGB = getForeground().getRGB(); + RGB backgroundRGB, foregroundRGB; + backgroundRGB = getBackground().getRGB(); + foregroundRGB = getForeground().getRGB(); - RGB fromRGB, toRGB; - fromRGB = foregroundRGB; - toRGB = backgroundRGB; - bool 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 ==/*eq*/ toRGB ) { - fillRectangle(x, y, width, height); - return; - } - auto cairo = data.cairo; - if (cairo !is null) { - cairo_pattern_t* 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; - } - ImageData.fillGradientRectangle(this, data.device, - x, y, width, height, vertical, fromRGB, toRGB, - 8, 8, 8); + RGB fromRGB, toRGB; + fromRGB = foregroundRGB; + toRGB = backgroundRGB; + bool 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 ==/*eq*/ toRGB ) { + fillRectangle(x, y, width, height); + return; + } + auto cairo = data.cairo; + if (cairo !is null) { + cairo_pattern_t* 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; + } + ImageData.fillGradientRectangle(this, data.device, + x, y, width, height, vertical, fromRGB, toRGB, + 8, 8, 8); } /** @@ -1897,31 +1897,31 @@ * @see #drawOval */ public void fillOval(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(FILL); - if (width < 0) { - x = x + width; - width = -width; - } - if (height < 0) { - y = y + height; - height = -height; - } - auto cairo = data.cairo; - if (cairo !is null) { - if (width is height) { - Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, 0, 2 * cast(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 * cast(float)Compatibility.PI); - Cairo.cairo_restore(cairo); - } - Cairo.cairo_fill(cairo); - return; - } - OS.gdk_draw_arc(data.drawable, handle, 1, x, y, width, height, 0, 23040); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + auto cairo = data.cairo; + if (cairo !is null) { + if (width is height) { + Cairo.cairo_arc_negative(cairo, x + width / 2f, y + height / 2f, width / 2f, 0, 2 * cast(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 * cast(float)Compatibility.PI); + Cairo.cairo_restore(cairo); + } + Cairo.cairo_fill(cairo); + return; + } + OS.gdk_draw_arc(data.drawable, handle, 1, x, y, width, height, 0, 23040); } /** @@ -1948,17 +1948,17 @@ * @since 3.1 */ public void fillPath (Path path) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (path.handle is null) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - initCairo(); - checkGC(FILL); - auto cairo = data.cairo; - auto copy = Cairo.cairo_copy_path(path.handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_append_path(cairo, copy); - Cairo.cairo_path_destroy(copy); - Cairo.cairo_fill(cairo); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (path.handle is null) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + initCairo(); + checkGC(FILL); + auto cairo = data.cairo; + auto copy = Cairo.cairo_copy_path(path.handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + Cairo.cairo_fill(cairo); } /** @@ -1981,16 +1981,16 @@ * @see #drawPolygon */ public void fillPolygon(int[] pointArray) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - checkGC(FILL); - auto cairo = data.cairo; - if (cairo !is null) { - drawPolyline(cairo, pointArray, true); - Cairo.cairo_fill(cairo); - return; - } - OS.gdk_draw_polygon(data.drawable, handle, 1, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + checkGC(FILL); + auto cairo = data.cairo; + if (cairo !is null) { + drawPolyline(cairo, pointArray, true); + Cairo.cairo_fill(cairo); + return; + } + OS.gdk_draw_polygon(data.drawable, handle, 1, cast(GdkPoint*)pointArray.ptr, pointArray.length / 2); } /** @@ -2009,23 +2009,23 @@ * @see #drawRectangle(int, int, int, int) */ public void fillRectangle(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - checkGC(FILL); - if (width < 0) { - x = x + width; - width = -width; - } - if (height < 0) { - y = y + height; - height = -height; - } - auto cairo = data.cairo; - if (cairo !is null) { - Cairo.cairo_rectangle(cairo, x, y, width, height); - Cairo.cairo_fill(cairo); - return; - } - OS.gdk_draw_rectangle(data.drawable, handle, 1, x, y, width, height); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + checkGC(FILL); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + auto cairo = data.cairo; + if (cairo !is null) { + Cairo.cairo_rectangle(cairo, x, y, width, height); + Cairo.cairo_fill(cairo); + return; + } + OS.gdk_draw_rectangle(data.drawable, handle, 1, x, y, width, height); } /** @@ -2044,9 +2044,9 @@ * @see #drawRectangle(int, int, int, int) */ public void fillRectangle(Rectangle rect) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - fillRectangle(rect.x, rect.y, rect.width, rect.height); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + fillRectangle(rect.x, rect.y, rect.width, rect.height); } /** @@ -2067,84 +2067,84 @@ * @see #drawRoundRectangle */ public void fillRoundRectangle(int x, int y, int width, int height, int arcWidth, int arcHeight) { - if (handle is null) 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; - auto cairo = data.cairo; - if (cairo !is null) { - 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; - auto drawable = data.drawable; - if (nw > naw) { - if (nh > nah) { - OS.gdk_draw_arc(drawable, handle, 1, nx, ny, naw, nah, 5760, 5760); - OS.gdk_draw_rectangle(drawable, handle, 1, nx + naw2, ny, nw - naw2 * 2, nh); - OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny, naw, nah, 0, 5760); - OS.gdk_draw_rectangle(drawable, handle, 1, nx, ny + nah2, naw2, nh - nah2 * 2); - OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); - OS.gdk_draw_rectangle(drawable, handle, 1, nx + nw - naw2, ny + nah2, naw2, nh - nah2 * 2); - OS.gdk_draw_arc(drawable, handle, 1, nx, ny + nh - nah, naw, nah, 11520, 5760); - } else { - OS.gdk_draw_arc(drawable, handle, 1, nx, ny, naw, nh, 5760, 11520); - OS.gdk_draw_rectangle(drawable, handle, 1, nx + naw2, ny, nw - naw2 * 2, nh); - OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny, naw, nh, 17280, 11520); - } - } else { - if (nh > nah) { - OS.gdk_draw_arc(drawable, handle, 1, nx, ny, nw, nah, 0, 11520); - OS.gdk_draw_rectangle(drawable, handle, 1, nx, ny + nah2, nw, nh - nah2 * 2); - OS.gdk_draw_arc(drawable, handle, 1, nx, ny + nh - nah, nw, nah, 11520, 11520); - } else { - OS.gdk_draw_arc(drawable, handle, 1, nx, ny, nw, nh, 0, 23040); - } - } + if (handle is null) 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; + auto cairo = data.cairo; + if (cairo !is null) { + 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; + auto drawable = data.drawable; + if (nw > naw) { + if (nh > nah) { + OS.gdk_draw_arc(drawable, handle, 1, nx, ny, naw, nah, 5760, 5760); + OS.gdk_draw_rectangle(drawable, handle, 1, nx + naw2, ny, nw - naw2 * 2, nh); + OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny, naw, nah, 0, 5760); + OS.gdk_draw_rectangle(drawable, handle, 1, nx, ny + nah2, naw2, nh - nah2 * 2); + OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny + nh - nah, naw, nah, 17280, 5760); + OS.gdk_draw_rectangle(drawable, handle, 1, nx + nw - naw2, ny + nah2, naw2, nh - nah2 * 2); + OS.gdk_draw_arc(drawable, handle, 1, nx, ny + nh - nah, naw, nah, 11520, 5760); + } else { + OS.gdk_draw_arc(drawable, handle, 1, nx, ny, naw, nh, 5760, 11520); + OS.gdk_draw_rectangle(drawable, handle, 1, nx + naw2, ny, nw - naw2 * 2, nh); + OS.gdk_draw_arc(drawable, handle, 1, nx + nw - naw, ny, naw, nh, 17280, 11520); + } + } else { + if (nh > nah) { + OS.gdk_draw_arc(drawable, handle, 1, nx, ny, nw, nah, 0, 11520); + OS.gdk_draw_rectangle(drawable, handle, 1, nx, ny + nah2, nw, nh - nah2 * 2); + OS.gdk_draw_arc(drawable, handle, 1, nx, ny + nh - nah, nw, nah, 11520, 11520); + } else { + OS.gdk_draw_arc(drawable, handle, 1, nx, ny, nw, nh, 0, 23040); + } + } } int fixMnemonic (char [] buffer) { - int i=0, j=0; - int mnemonic=-1; - while (i < buffer.length) { - if ((buffer [j++] = buffer [i++]) is '&') { - if (i is buffer.length) {continue;} - if (buffer [i] is '&') {i++; continue;} - if (mnemonic is -1) mnemonic = j; - j--; - } - } - while (j < buffer.length) buffer [j++] = 0; - return mnemonic; + int i=0, j=0; + int mnemonic=-1; + while (i < buffer.length) { + if ((buffer [j++] = buffer [i++]) is '&') { + if (i is buffer.length) {continue;} + if (buffer [i] is '&') {i++; continue;} + if (mnemonic is -1) mnemonic = j; + j--; + } + } + while (j < buffer.length) buffer [j++] = 0; + return mnemonic; } /** @@ -2163,9 +2163,9 @@ * */ public int getAdvanceWidth(char ch) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - //BOGUS - return stringExtent([ch]).x; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + //BOGUS + return stringExtent([ch]).x; } /** @@ -2194,8 +2194,8 @@ * @since 3.1 */ public bool getAdvanced() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.cairo !is null; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.cairo !is null; } /** @@ -2210,8 +2210,8 @@ * @since 3.1 */ public int getAlpha() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.alpha; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.alpha; } /** @@ -2231,17 +2231,17 @@ * @since 3.1 */ public int getAntialias() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (data.cairo is null) 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; + 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; default: - } - return SWT.DEFAULT; + } + return SWT.DEFAULT; } /** @@ -2254,8 +2254,8 @@ * */ public Color getBackground() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return Color.gtk_new(data.device, data.background); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return Color.gtk_new(data.device, data.background); } /** @@ -2273,8 +2273,8 @@ * @since 3.1 */ public Pattern getBackgroundPattern() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.backgroundPattern; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.backgroundPattern; } /** @@ -2294,9 +2294,9 @@ * */ public int getCharWidth(char ch) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - //BOGUS - return stringExtent([ch]).x; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + //BOGUS + return stringExtent([ch]).x; } /** @@ -2312,54 +2312,54 @@ * */ public Rectangle getClipping() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - /* Calculate visible bounds in device space */ - int x = 0, y = 0, width = 0, height = 0; - int w, h; - OS.gdk_drawable_get_size(data.drawable, &w, &h); - width = w; - height = h; - /* Intersect visible bounds with clipping in device space and then convert then to user space */ - auto cairo = data.cairo; - auto clipRgn = data.clipRgn; - auto damageRgn = data.damageRgn; - if (clipRgn !is null || damageRgn !is null || cairo !is null) { - auto rgn = OS.gdk_region_new(); - GdkRectangle* rect = new GdkRectangle(); - rect.width = width; - rect.height = height; - OS.gdk_region_union_with_rect(rgn, rect); - if (damageRgn !is null) { - OS.gdk_region_intersect (rgn, damageRgn); - } - /* Intersect visible bounds with clipping */ - if (clipRgn !is null) { - /* Convert clipping to device space if needed */ - if (data.clippingTransform !is null) { - clipRgn = convertRgn(clipRgn, data.clippingTransform); - OS.gdk_region_intersect(rgn, clipRgn); - OS.gdk_region_destroy(clipRgn); - } else { - OS.gdk_region_intersect(rgn, clipRgn); - } - } - /* Convert to user space */ - if (cairo !is null) { - double[] matrix = new double[6]; - Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)matrix.ptr); - Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)matrix.ptr); - clipRgn = convertRgn(rgn, matrix); - OS.gdk_region_destroy(rgn); - rgn = clipRgn; - } - OS.gdk_region_get_clipbox(rgn, rect); - OS.gdk_region_destroy(rgn); - x = rect.x; - y = rect.y; - width = rect.width; - height = rect.height; - } - return new Rectangle(x, y, width, height); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + /* Calculate visible bounds in device space */ + int x = 0, y = 0, width = 0, height = 0; + int w, h; + OS.gdk_drawable_get_size(data.drawable, &w, &h); + width = w; + height = h; + /* Intersect visible bounds with clipping in device space and then convert then to user space */ + auto cairo = data.cairo; + auto clipRgn = data.clipRgn; + auto damageRgn = data.damageRgn; + if (clipRgn !is null || damageRgn !is null || cairo !is null) { + auto rgn = OS.gdk_region_new(); + GdkRectangle* rect = new GdkRectangle(); + rect.width = width; + rect.height = height; + OS.gdk_region_union_with_rect(rgn, rect); + if (damageRgn !is null) { + OS.gdk_region_intersect (rgn, damageRgn); + } + /* Intersect visible bounds with clipping */ + if (clipRgn !is null) { + /* Convert clipping to device space if needed */ + if (data.clippingTransform !is null) { + clipRgn = convertRgn(clipRgn, data.clippingTransform); + OS.gdk_region_intersect(rgn, clipRgn); + OS.gdk_region_destroy(clipRgn); + } else { + OS.gdk_region_intersect(rgn, clipRgn); + } + } + /* Convert to user space */ + if (cairo !is null) { + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)matrix.ptr); + Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)matrix.ptr); + clipRgn = convertRgn(rgn, matrix); + OS.gdk_region_destroy(rgn); + rgn = clipRgn; + } + OS.gdk_region_get_clipbox(rgn, rect); + OS.gdk_region_destroy(rgn); + x = rect.x; + y = rect.y; + width = rect.width; + height = rect.height; + } + return new Rectangle(x, y, width, height); } /** @@ -2377,43 +2377,43 @@ * */ public void getClipping(Region region) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - auto clipping = region.handle; - OS.gdk_region_subtract(clipping, clipping); - auto cairo = data.cairo; - auto clipRgn = data.clipRgn; - if (clipRgn is null) { - int width,height; - OS.gdk_drawable_get_size(data.drawable, &width, &height); - GdkRectangle* rect = new GdkRectangle(); - rect.width = width; - rect.height = height; - OS.gdk_region_union_with_rect(clipping, rect); - } else { - /* Convert clipping to device space if needed */ - if (data.clippingTransform !is null) { - auto rgn = convertRgn(clipRgn, data.clippingTransform); - OS.gdk_region_union(clipping, rgn); - OS.gdk_region_destroy(rgn); - } else { - OS.gdk_region_union(clipping, clipRgn); - } - } - if (data.damageRgn !is null) { - OS.gdk_region_intersect(clipping, data.damageRgn); - } - /* Convert to user space */ - if (cairo !is null) { - double[] matrix = new double[6]; - Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)matrix.ptr); - Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)matrix.ptr); - auto rgn = convertRgn(clipping, matrix); - OS.gdk_region_subtract(clipping, clipping); - OS.gdk_region_union(clipping, rgn); - OS.gdk_region_destroy(rgn); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + auto clipping = region.handle; + OS.gdk_region_subtract(clipping, clipping); + auto cairo = data.cairo; + auto clipRgn = data.clipRgn; + if (clipRgn is null) { + int width,height; + OS.gdk_drawable_get_size(data.drawable, &width, &height); + GdkRectangle* rect = new GdkRectangle(); + rect.width = width; + rect.height = height; + OS.gdk_region_union_with_rect(clipping, rect); + } else { + /* Convert clipping to device space if needed */ + if (data.clippingTransform !is null) { + auto rgn = convertRgn(clipRgn, data.clippingTransform); + OS.gdk_region_union(clipping, rgn); + OS.gdk_region_destroy(rgn); + } else { + OS.gdk_region_union(clipping, clipRgn); + } + } + if (data.damageRgn !is null) { + OS.gdk_region_intersect(clipping, data.damageRgn); + } + /* Convert to user space */ + if (cairo !is null) { + double[] matrix = new double[6]; + Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)matrix.ptr); + Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)matrix.ptr); + auto rgn = convertRgn(clipping, matrix); + OS.gdk_region_subtract(clipping, clipping); + OS.gdk_region_union(clipping, rgn); + OS.gdk_region_destroy(rgn); + } } /** @@ -2429,10 +2429,10 @@ * @since 3.1 */ public int getFillRule() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - auto cairo = data.cairo; - if (cairo is null) return SWT.FILL_EVEN_ODD; - return Cairo.cairo_get_fill_rule(cairo) is Cairo.CAIRO_FILL_RULE_WINDING ? SWT.FILL_WINDING : SWT.FILL_EVEN_ODD; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + auto cairo = data.cairo; + if (cairo is null) return SWT.FILL_EVEN_ODD; + return Cairo.cairo_get_fill_rule(cairo) is Cairo.CAIRO_FILL_RULE_WINDING ? SWT.FILL_WINDING : SWT.FILL_EVEN_ODD; } /** @@ -2446,8 +2446,8 @@ * */ public Font getFont() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return Font.gtk_new(data.device, data.font); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return Font.gtk_new(data.device, data.font); } /** @@ -2462,19 +2462,19 @@ * */ public FontMetrics getFontMetrics() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.context is null) createLayout(); - checkGC(FONT); - auto context = data.context; - auto lang = OS.pango_context_get_language(context); - auto metrics = OS.pango_context_get_metrics(context, data.font, lang); - FontMetrics fm = new FontMetrics(); - fm.ascent = OS.PANGO_PIXELS(OS.pango_font_metrics_get_ascent(metrics)); - fm.descent = OS.PANGO_PIXELS(OS.pango_font_metrics_get_descent(metrics)); - fm.averageCharWidth = OS.PANGO_PIXELS(OS.pango_font_metrics_get_approximate_char_width(metrics)); - fm.height = fm.ascent + fm.descent; - OS.pango_font_metrics_unref(metrics); - return fm; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.context is null) createLayout(); + checkGC(FONT); + auto context = data.context; + auto lang = OS.pango_context_get_language(context); + auto metrics = OS.pango_context_get_metrics(context, data.font, lang); + FontMetrics fm = new FontMetrics(); + fm.ascent = OS.PANGO_PIXELS(OS.pango_font_metrics_get_ascent(metrics)); + fm.descent = OS.PANGO_PIXELS(OS.pango_font_metrics_get_descent(metrics)); + fm.averageCharWidth = OS.PANGO_PIXELS(OS.pango_font_metrics_get_approximate_char_width(metrics)); + fm.height = fm.ascent + fm.descent; + OS.pango_font_metrics_unref(metrics); + return fm; } /** @@ -2487,8 +2487,8 @@ * */ public Color getForeground() { - if (handle is null) SWT.error(SWT.ERROR_WIDGET_DISPOSED); - return Color.gtk_new(data.device, data.foreground); + if (handle is null) SWT.error(SWT.ERROR_WIDGET_DISPOSED); + return Color.gtk_new(data.device, data.foreground); } /** @@ -2506,8 +2506,8 @@ * @since 3.1 */ public Pattern getForegroundPattern() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.foregroundPattern; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.foregroundPattern; } /** @@ -2531,8 +2531,8 @@ * @since 3.2 */ public GCData getGCData() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data; } /** @@ -2549,8 +2549,8 @@ * @since 3.1 */ public int getInterpolation() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.interpolation; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.interpolation; } /** @@ -2565,13 +2565,13 @@ * @since 3.3 */ public LineAttributes getLineAttributes() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - float[] dashes = null; - if (data.lineDashes !is null) { + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + float[] dashes = null; + if (data.lineDashes !is 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); + } + return new LineAttributes(data.lineWidth, data.lineCap, data.lineJoin, data.lineStyle, dashes, data.lineDashesOffset, data.lineMiterLimit); } /** @@ -2588,8 +2588,8 @@ * @since 3.1 */ public int getLineCap() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.lineCap; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineCap; } /** @@ -2605,13 +2605,13 @@ * @since 3.1 */ public int[] getLineDash() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.lineDashes is null) return null; - int[] lineDashes = new int[data.lineDashes.length]; - for (int i = 0; i < lineDashes.length; i++) { - lineDashes[i] = cast(int)data.lineDashes[i]; - } - return lineDashes; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineDashes is null) return null; + int[] lineDashes = new int[data.lineDashes.length]; + for (int i = 0; i < lineDashes.length; i++) { + lineDashes[i] = cast(int)data.lineDashes[i]; + } + return lineDashes; } /** @@ -2628,8 +2628,8 @@ * @since 3.1 */ public int getLineJoin() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.lineJoin; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineJoin; } /** @@ -2645,8 +2645,8 @@ * */ public int getLineStyle() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.lineStyle; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.lineStyle; } /** @@ -2662,8 +2662,8 @@ * */ public int getLineWidth() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return cast(int)data.lineWidth; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return cast(int)data.lineWidth; } /** @@ -2685,8 +2685,8 @@ * @since 2.1.2 */ public int getStyle () { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.style; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.style; } /** @@ -2710,24 +2710,24 @@ if (data.cairo is null) return SWT.DEFAULT; int antialias = Cairo.CAIRO_ANTIALIAS_DEFAULT; if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { - auto options = Cairo.cairo_font_options_create(); - Cairo.cairo_get_font_options(data.cairo, options); - antialias = Cairo.cairo_font_options_get_antialias(options); - Cairo.cairo_font_options_destroy(options); + auto options = Cairo.cairo_font_options_create(); + Cairo.cairo_get_font_options(data.cairo, options); + antialias = Cairo.cairo_font_options_get_antialias(options); + Cairo.cairo_font_options_destroy(options); } else { - if (data.context !is null) { - auto options = OS.pango_cairo_context_get_font_options(data.context); - if (options !is null) antialias = Cairo.cairo_font_options_get_antialias(options); - } + if (data.context !is null) { + auto options = OS.pango_cairo_context_get_font_options(data.context); + if (options !is null) antialias = Cairo.cairo_font_options_get_antialias(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; + 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; default: - } - return SWT.DEFAULT; + } + return SWT.DEFAULT; } /** @@ -2749,15 +2749,15 @@ * @since 3.1 */ public void getTransform(Transform transform) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (transform is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - auto cairo = data.cairo; - if (cairo !is null) { - Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)transform.handle.ptr); - } else { - transform.setElements(1, 0, 0, 1, 0, 0); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transform is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + auto cairo = data.cairo; + if (cairo !is null) { + Cairo.cairo_get_matrix(cairo, cast(cairo_matrix_t*)transform.handle.ptr); + } else { + transform.setElements(1, 0, 0, 1, 0, 0); + } } /** @@ -2775,8 +2775,8 @@ * */ public bool getXORMode() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.xorMode; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.xorMode; } /** @@ -2794,61 +2794,61 @@ * @see #equals */ public int hashCode() { - return cast(int)/*64*/handle; + return cast(int)/*64*/handle; } void init(Drawable drawable, GCData data, GdkGC* gdkGC) { - if (data.foreground !is null) data.state &= ~FOREGROUND; - if (data.background !is null) data.state &= ~(BACKGROUND | BACKGROUND_BG); - if (data.font !is null) data.state &= ~FONT; + if (data.foreground !is null) data.state &= ~FOREGROUND; + if (data.background !is null) data.state &= ~(BACKGROUND | BACKGROUND_BG); + if (data.font !is null) data.state &= ~FONT; - Image image = data.image; - if (image !is 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 !is -1) image.destroyMask(); - } - this.drawable = drawable; - this.data = data; - handle = gdkGC; + Image image = data.image; + if (image !is 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 !is -1) image.destroyMask(); + } + this.drawable = drawable; + this.data = data; + handle = gdkGC; } void initCairo() { - data.device.checkCairo(); - auto cairo = data.cairo; - if (cairo !is null) return; - auto xDisplay = OS.GDK_DISPLAY(); - auto xVisual = OS.gdk_x11_visual_get_xvisual(OS.gdk_visual_get_system()); - uint xDrawable; - int translateX = 0, translateY = 0; - auto drawable = data.drawable; - if (data.image !is null) { - xDrawable = OS.GDK_PIXMAP_XID(drawable); - } else { - int x, y; - GdkDrawable* real_drawable; - OS.gdk_window_get_internal_paint_info(cast(GdkWindow*)drawable, &real_drawable, &x, &y); - xDrawable = OS.gdk_x11_drawable_get_xid(real_drawable); - translateX = -x; - translateY = -y; - } - int w, h; - OS.gdk_drawable_get_size(drawable, &w, &h); - int width = w, height = h; - auto surface = Cairo.cairo_xlib_surface_create(cast(void*)xDisplay, xDrawable, xVisual, width, height); - if (surface is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_surface_set_device_offset(surface, translateX, translateY); - data.cairo = cairo = Cairo.cairo_create(surface); - Cairo.cairo_surface_destroy(surface); - if (cairo is null) SWT.error(SWT.ERROR_NO_HANDLES); - data.disposeCairo = true; - 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(cairo, data.clipRgn); + data.device.checkCairo(); + auto cairo = data.cairo; + if (cairo !is null) return; + auto xDisplay = OS.GDK_DISPLAY(); + auto xVisual = OS.gdk_x11_visual_get_xvisual(OS.gdk_visual_get_system()); + uint xDrawable; + int translateX = 0, translateY = 0; + auto drawable = data.drawable; + if (data.image !is null) { + xDrawable = OS.GDK_PIXMAP_XID(drawable); + } else { + int x, y; + GdkDrawable* real_drawable; + OS.gdk_window_get_internal_paint_info(cast(GdkWindow*)drawable, &real_drawable, &x, &y); + xDrawable = OS.gdk_x11_drawable_get_xid(real_drawable); + translateX = -x; + translateY = -y; + } + int w, h; + OS.gdk_drawable_get_size(drawable, &w, &h); + int width = w, height = h; + auto surface = Cairo.cairo_xlib_surface_create(cast(void*)xDisplay, xDrawable, xVisual, width, height); + if (surface is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_surface_set_device_offset(surface, translateX, translateY); + data.cairo = cairo = Cairo.cairo_create(surface); + Cairo.cairo_surface_destroy(surface); + if (cairo is null) SWT.error(SWT.ERROR_NO_HANDLES); + data.disposeCairo = true; + 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(cairo, data.clipRgn); } /** @@ -2866,8 +2866,8 @@ * */ public bool isClipped() { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return data.clipRgn !is null; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return data.clipRgn !is null; } /** @@ -2881,12 +2881,12 @@ * @return true when the GC is disposed and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } bool isIdentity(double[] matrix) { - if (matrix is null) return true; - return matrix[0] is 1 && matrix[1] is 0 && matrix[2] is 0 && matrix[3] is 1 && matrix[4] is 0 && matrix[5] is 0; + if (matrix is null) return true; + return matrix[0] is 1 && matrix[1] is 0 && matrix[2] is 0 && matrix[3] is 1 && matrix[4] is 0 && matrix[5] is 0; } /** @@ -2932,22 +2932,22 @@ * @since 3.1 */ public void setAdvanced(bool advanced) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (advanced && data.cairo !is null) return; - if (advanced) { - try { - initCairo(); - } catch (SWTException e) {} - } else { - if (!data.disposeCairo) return; - auto cairo = data.cairo; - if (cairo !is null) Cairo.cairo_destroy(cairo); - data.cairo = null; - data.interpolation = SWT.DEFAULT; - data.backgroundPattern = data.foregroundPattern = null; - data.state = 0; - setClipping(cast(GdkRegion*)null); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (advanced && data.cairo !is null) return; + if (advanced) { + try { + initCairo(); + } catch (SWTException e) {} + } else { + if (!data.disposeCairo) return; + auto cairo = data.cairo; + if (cairo !is null) Cairo.cairo_destroy(cairo); + data.cairo = null; + data.interpolation = SWT.DEFAULT; + data.backgroundPattern = data.foregroundPattern = null; + data.state = 0; + setClipping(cast(GdkRegion*)null); + } } /** @@ -2970,11 +2970,11 @@ * @since 3.1 */ public void setAlpha(int alpha) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.cairo is null && (alpha & 0xff) is 0xff) return; - initCairo(); - data.alpha = alpha & 0xff; - data.state &= ~(BACKGROUND | FOREGROUND | BACKGROUND_BG); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo is null && (alpha & 0xff) is 0xff) return; + initCairo(); + data.alpha = alpha & 0xff; + data.state &= ~(BACKGROUND | FOREGROUND | BACKGROUND_BG); } /** @@ -3006,17 +3006,17 @@ * @since 3.1 */ public void setAntialias(int antialias) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.cairo is null && antialias is 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; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo is null && antialias is 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); - } + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } initCairo(); auto cairo = data.cairo; Cairo.cairo_set_antialias(cairo, mode); @@ -3038,12 +3038,12 @@ * */ public void setBackground(Color color) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (color is 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); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color is 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); } /** @@ -3071,97 +3071,97 @@ * @since 3.1 */ public void setBackgroundPattern(Pattern pattern) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pattern !is null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (data.cairo is null && pattern is null) return; - initCairo(); - if (data.backgroundPattern is pattern) return; - data.backgroundPattern = pattern; - data.state &= ~BACKGROUND; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pattern !is null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo is null && pattern is null) return; + initCairo(); + if (data.backgroundPattern is pattern) return; + data.backgroundPattern = pattern; + data.state &= ~BACKGROUND; } static void setCairoFont(cairo_t* cairo, Font font) { - setCairoFont(cairo, font.handle); + setCairoFont(cairo, font.handle); } static void setCairoFont(cairo_t* cairo, PangoFontDescription* font) { - auto family = OS.pango_font_description_get_family(font); - int len = /*OS.*/strlen(family); - char[] buffer = new char[len + 1]; - memmove(buffer.ptr, family, len); - //TODO - convert font height from pango to cairo - double height = OS.PANGO_PIXELS(OS.pango_font_description_get_size(font)) * 96 / 72; - int pangoStyle = OS.pango_font_description_get_style(font); - int pangoWeight = OS.pango_font_description_get_weight(font); - int slant = Cairo.CAIRO_FONT_SLANT_NORMAL; - if (pangoStyle is OS.PANGO_STYLE_ITALIC) slant = Cairo.CAIRO_FONT_SLANT_ITALIC; - if (pangoStyle is OS.PANGO_STYLE_OBLIQUE) slant = Cairo.CAIRO_FONT_SLANT_OBLIQUE; - int weight = Cairo.CAIRO_FONT_WEIGHT_NORMAL; - if (pangoWeight is OS.PANGO_WEIGHT_BOLD) weight = Cairo.CAIRO_FONT_WEIGHT_BOLD; - Cairo.cairo_select_font_face(cairo, buffer.ptr, slant, weight); - Cairo.cairo_set_font_size(cairo, height); + auto family = OS.pango_font_description_get_family(font); + int len = /*OS.*/strlen(family); + char[] buffer = new char[len + 1]; + memmove(buffer.ptr, family, len); + //TODO - convert font height from pango to cairo + double height = OS.PANGO_PIXELS(OS.pango_font_description_get_size(font)) * 96 / 72; + int pangoStyle = OS.pango_font_description_get_style(font); + int pangoWeight = OS.pango_font_description_get_weight(font); + int slant = Cairo.CAIRO_FONT_SLANT_NORMAL; + if (pangoStyle is OS.PANGO_STYLE_ITALIC) slant = Cairo.CAIRO_FONT_SLANT_ITALIC; + if (pangoStyle is OS.PANGO_STYLE_OBLIQUE) slant = Cairo.CAIRO_FONT_SLANT_OBLIQUE; + int weight = Cairo.CAIRO_FONT_WEIGHT_NORMAL; + if (pangoWeight is OS.PANGO_WEIGHT_BOLD) weight = Cairo.CAIRO_FONT_WEIGHT_BOLD; + Cairo.cairo_select_font_face(cairo, buffer.ptr, slant, weight); + Cairo.cairo_set_font_size(cairo, height); } static void setCairoClip(cairo_t* cairo, GdkRegion* clipRgn) { - Cairo.cairo_reset_clip(cairo); - if (clipRgn is null) return; - if (OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - OS.gdk_cairo_region(cairo, clipRgn); - } else { - int nRects; - GdkRectangle * rects; - OS.gdk_region_get_rectangles(clipRgn, &rects, &nRects); - GdkRectangle* rect = new GdkRectangle(); - for (int i=0; i= OS.buildVERSION(2, 8, 0)) { + OS.gdk_cairo_region(cairo, clipRgn); + } else { + int nRects; + GdkRectangle * rects; + OS.gdk_region_get_rectangles(clipRgn, &rects, &nRects); + GdkRectangle* rect = new GdkRectangle(); + for (int i=0; i */ public void setClipping(int x, int y, int width, int height) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (width < 0) { - x = x + width; - width = -width; - } - if (height < 0) { - y = y + height; - height = -height; - } - GdkRectangle* rect = new GdkRectangle(); - rect.x = x; - rect.y = y; - rect.width = width; - rect.height = height; - auto clipRgn = OS.gdk_region_new(); - OS.gdk_region_union_with_rect(clipRgn, rect); - setClipping(clipRgn); - OS.gdk_region_destroy(clipRgn); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0) { + x = x + width; + width = -width; + } + if (height < 0) { + y = y + height; + height = -height; + } + GdkRectangle* rect = new GdkRectangle(); + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + auto clipRgn = OS.gdk_region_new(); + OS.gdk_region_union_with_rect(clipRgn, rect); + setClipping(clipRgn); + OS.gdk_region_destroy(clipRgn); } /** @@ -3226,18 +3226,18 @@ * @since 3.1 */ public void setClipping(Path path) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (path !is null && path.isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - setClipping(cast(GdkRegion*)null); - if (path !is null) { - initCairo(); - auto cairo = data.cairo; - auto copy = Cairo.cairo_copy_path(path.handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_append_path(cairo, copy); - Cairo.cairo_path_destroy(copy); - Cairo.cairo_clip(cairo); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path !is null && path.isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + setClipping(cast(GdkRegion*)null); + if (path !is null) { + initCairo(); + auto cairo = data.cairo; + auto copy = Cairo.cairo_copy_path(path.handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + Cairo.cairo_clip(cairo); + } } /** @@ -3254,12 +3254,12 @@ * */ public void setClipping(Rectangle rect) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (rect is null) { - setClipping(cast(GdkRegion*)null); - } else { - setClipping(rect.x, rect.y, rect.width, rect.height); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect is null) { + setClipping(cast(GdkRegion*)null); + } else { + setClipping(rect.x, rect.y, rect.width, rect.height); + } } /** * Sets the area of the receiver which can be changed @@ -3278,9 +3278,9 @@ * */ public void setClipping(Region region) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (region !is null && region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - setClipping(region !is null ? region.handle : cast(GdkRegion*)null); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region !is null && region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + setClipping(region !is null ? region.handle : cast(GdkRegion*)null); } /** @@ -3299,12 +3299,12 @@ * */ public void setFont(Font font) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (font is null) font = data.device.systemFont; - if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - data.font = font.handle; - data.state &= ~FONT; - data.stringWidth = data.stringHeight = -1; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (font is null) font = data.device.systemFont; + if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + data.font = font.handle; + data.state &= ~FONT; + data.stringWidth = data.stringHeight = -1; } /** @@ -3324,22 +3324,22 @@ * @since 3.1 */ public void setFillRule(int rule) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - int cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; - switch (rule) { - case SWT.FILL_WINDING: - cairo_mode = Cairo.CAIRO_FILL_RULE_WINDING; break; - case SWT.FILL_EVEN_ODD: - cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; break; - default: - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - //TODO - need fill rule in X, GDK has no API - initCairo(); - auto cairo = data.cairo; - if (cairo !is null) { - Cairo.cairo_set_fill_rule(cairo, cairo_mode); - } + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + int cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; + switch (rule) { + case SWT.FILL_WINDING: + cairo_mode = Cairo.CAIRO_FILL_RULE_WINDING; break; + case SWT.FILL_EVEN_ODD: + cairo_mode = Cairo.CAIRO_FILL_RULE_EVEN_ODD; break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + //TODO - need fill rule in X, GDK has no API + initCairo(); + auto cairo = data.cairo; + if (cairo !is null) { + Cairo.cairo_set_fill_rule(cairo, cairo_mode); + } } /** @@ -3357,12 +3357,12 @@ * */ public void setForeground(Color color) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (color is 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; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color is 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; } /** @@ -3389,13 +3389,13 @@ * @since 3.1 */ public void setForegroundPattern(Pattern pattern) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pattern !is null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (data.cairo is null && pattern is null) return; - initCairo(); - if (data.foregroundPattern is pattern) return; - data.foregroundPattern = pattern; - data.state &= ~FOREGROUND; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pattern !is null && pattern.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo is null && pattern is null) return; + initCairo(); + if (data.foregroundPattern is pattern) return; + data.foregroundPattern = pattern; + data.state &= ~FOREGROUND; } /** @@ -3425,19 +3425,19 @@ * @since 3.1 */ public void setInterpolation(int interpolation) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.cairo is null && interpolation is 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; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.cairo is null && interpolation is 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; } /** @@ -3465,96 +3465,96 @@ * @since 3.3 */ public void setLineAttributes(LineAttributes attributes) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (attributes is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - int mask = 0; - float lineWidth = attributes.width; - if (lineWidth !is data.lineWidth) { - mask |= LINE_WIDTH | DRAW_OFFSET; - } - int lineStyle = attributes.style; - if (lineStyle !is 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 is null) lineStyle = SWT.LINE_SOLID; - break; - default: - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - } - int join = attributes.join; - if (join !is 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.join; - if (cap !is 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 !is null && dashes.length > 0) { - bool changed = lineDashes is null || lineDashes.length !is 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] !is dash) changed = true; - } - if (changed) { + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (attributes is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int mask = 0; + float lineWidth = attributes.width; + if (lineWidth !is data.lineWidth) { + mask |= LINE_WIDTH | DRAW_OFFSET; + } + int lineStyle = attributes.style; + if (lineStyle !is 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 is null) lineStyle = SWT.LINE_SOLID; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + } + int join = attributes.join; + if (join !is 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.join; + if (cap !is 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 !is null && dashes.length > 0) { + bool changed = lineDashes is null || lineDashes.length !is 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] !is 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 !is null && lineDashes.length > 0) { - mask |= LINE_STYLE; - } else { - dashes = lineDashes; - } - } - float dashOffset = attributes.dashOffset; - if (dashOffset !is data.lineDashesOffset) { - mask |= LINE_STYLE; - } - float miterLimit = attributes.miterLimit; - if (miterLimit !is data.lineMiterLimit) { - mask |= LINE_MITERLIMIT; - } - initCairo(); - if (mask is 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; + mask |= LINE_STYLE; + } else { + dashes = lineDashes; + } + } else { + if (lineDashes !is null && lineDashes.length > 0) { + mask |= LINE_STYLE; + } else { + dashes = lineDashes; + } + } + float dashOffset = attributes.dashOffset; + if (dashOffset !is data.lineDashesOffset) { + mask |= LINE_STYLE; + } + float miterLimit = attributes.miterLimit; + if (miterLimit !is data.lineMiterLimit) { + mask |= LINE_MITERLIMIT; + } + initCairo(); + if (mask is 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; } /** @@ -3574,18 +3574,18 @@ * @since 3.1 */ public void setLineCap(int cap) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.lineCap is 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; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineCap is 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; } /** @@ -3606,27 +3606,27 @@ * @since 3.1 */ public void setLineDash(int[] dashes) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - float[] lineDashes = data.lineDashes; - if (dashes !is null && dashes.length > 0) { - bool changed = data.lineStyle !is SWT.LINE_CUSTOM || lineDashes is null || lineDashes.length !is 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] !is 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 is SWT.LINE_SOLID && (lineDashes is null || lineDashes.length is 0)) return; - data.lineDashes = null; - data.lineStyle = SWT.LINE_SOLID; - } - data.state &= ~LINE_STYLE; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + float[] lineDashes = data.lineDashes; + if (dashes !is null && dashes.length > 0) { + bool changed = data.lineStyle !is SWT.LINE_CUSTOM || lineDashes is null || lineDashes.length !is 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] !is 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 is SWT.LINE_SOLID && (lineDashes is null || lineDashes.length is 0)) return; + data.lineDashes = null; + data.lineStyle = SWT.LINE_SOLID; + } + data.state &= ~LINE_STYLE; } /** @@ -3646,18 +3646,18 @@ * @since 3.1 */ public void setLineJoin(int join) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.lineJoin is 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; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineJoin is 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; } /** @@ -3676,23 +3676,23 @@ * */ public void setLineStyle(int lineStyle) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.lineStyle is 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 is null) lineStyle = SWT.LINE_SOLID; - break; - default: - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - data.lineStyle = lineStyle; - data.state &= ~LINE_STYLE; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineStyle is 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 is null) lineStyle = SWT.LINE_SOLID; + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + data.lineStyle = lineStyle; + data.state &= ~LINE_STYLE; } /** @@ -3714,48 +3714,48 @@ * */ public void setLineWidth(int lineWidth) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.lineWidth is lineWidth) return; - data.lineWidth = lineWidth; - data.state &= ~(LINE_WIDTH | DRAW_OFFSET); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (data.lineWidth is lineWidth) return; + data.lineWidth = lineWidth; + data.state &= ~(LINE_WIDTH | DRAW_OFFSET); } void setString(char[] str, int flags) { - if (data.layout is null) createLayout(); - if (str is data.str && (flags & ~SWT.DRAW_TRANSPARENT) is (data.drawFlags & ~SWT.DRAW_TRANSPARENT)) { - return; - } - char[] buffer; - int mnemonic, len = str.length ; - auto layout = data.layout; - char[] text = str.dup; - if ((flags & SWT.DRAW_MNEMONIC) !is 0 && (mnemonic = fixMnemonic(text)) !is -1) { - char[] text1 = new char[mnemonic - 1]; + if (data.layout is null) createLayout(); + if (str is data.str && (flags & ~SWT.DRAW_TRANSPARENT) is (data.drawFlags & ~SWT.DRAW_TRANSPARENT)) { + return; + } + char[] buffer; + int mnemonic, len = str.length ; + auto layout = data.layout; + char[] text = str.dup; + if ((flags & SWT.DRAW_MNEMONIC) !is 0 && (mnemonic = fixMnemonic(text)) !is -1) { + char[] text1 = new char[mnemonic - 1]; System.arraycopy(text, 0, text1, 0, text1.length); - char[] buffer1 = text1.dup; - char[] text2 = new char[text.length - mnemonic]; + char[] buffer1 = text1.dup; + char[] text2 = new char[text.length - mnemonic]; System.arraycopy(text, mnemonic - 1, text2, 0, text2.length); - char[] buffer2 = text2.dup; - buffer = new char[buffer1.length + buffer2.length]; + char[] buffer2 = text2.dup; + buffer = new char[buffer1.length + buffer2.length]; System.arraycopy(buffer1, 0, buffer, 0, buffer1.length); System.arraycopy(buffer2, 0, buffer, buffer1.length, buffer2.length); - auto attr_list = OS.pango_attr_list_new(); - auto attr = OS.pango_attr_underline_new(OS.PANGO_UNDERLINE_LOW); - attr.start_index = buffer1.length; - attr.end_index = buffer1.length + 1; - OS.pango_attr_list_insert(attr_list, attr); - OS.pango_layout_set_attributes(layout, attr_list); - OS.pango_attr_list_unref(attr_list); - } else { - buffer = text.dup; - OS.pango_layout_set_attributes(layout, null); - } - OS.pango_layout_set_text(layout, buffer.ptr, buffer.length); - OS.pango_layout_set_single_paragraph_mode(layout, (flags & SWT.DRAW_DELIMITER) is 0); - OS.pango_layout_set_tabs(layout, (flags & SWT.DRAW_TAB) !is 0 ? null : data.device.emptyTab); - data.str = str; - data.stringWidth = data.stringHeight = -1; - data.drawFlags = flags; + auto attr_list = OS.pango_attr_list_new(); + auto attr = OS.pango_attr_underline_new(OS.PANGO_UNDERLINE_LOW); + attr.start_index = buffer1.length; + attr.end_index = buffer1.length + 1; + OS.pango_attr_list_insert(attr_list, attr); + OS.pango_layout_set_attributes(layout, attr_list); + OS.pango_attr_list_unref(attr_list); + } else { + buffer = text.dup; + OS.pango_layout_set_attributes(layout, null); + } + OS.pango_layout_set_text(layout, buffer.ptr, buffer.length); + OS.pango_layout_set_single_paragraph_mode(layout, (flags & SWT.DRAW_DELIMITER) is 0); + OS.pango_layout_set_tabs(layout, (flags & SWT.DRAW_TAB) !is 0 ? null : data.device.emptyTab); + data.str = str; + data.stringWidth = data.stringHeight = -1; + data.drawFlags = flags; } /** @@ -3788,24 +3788,24 @@ */ public void setTextAntialias(int antialias) { if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (data.cairo is null && antialias is 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; + if (data.cairo is null && antialias is 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); - } + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } initCairo(); auto options = Cairo.cairo_font_options_create(); Cairo.cairo_font_options_set_antialias(options, mode); if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { - Cairo.cairo_set_font_options(data.cairo, options); + Cairo.cairo_set_font_options(data.cairo, options); } else { - if (data.context is null) createLayout(); - OS.pango_cairo_context_set_font_options(data.context, options); + if (data.context is null) createLayout(); + OS.pango_cairo_context_set_font_options(data.context, options); } Cairo.cairo_font_options_destroy(options); } @@ -3837,17 +3837,17 @@ * @since 3.1 */ public void setTransform(Transform transform) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (transform !is null && transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (data.cairo is null && transform is null) return; - initCairo(); - auto cairo = data.cairo; - if (transform !is null) { - Cairo.cairo_set_matrix(cairo,cast(cairo_matrix_t*) transform.handle.ptr); - } else { - Cairo.cairo_identity_matrix(cairo); - } - data.state &= ~DRAW_OFFSET; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transform !is null && transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (data.cairo is null && transform is null) return; + initCairo(); + auto cairo = data.cairo; + if (transform !is null) { + Cairo.cairo_set_matrix(cairo,cast(cairo_matrix_t*) transform.handle.ptr); + } else { + Cairo.cairo_identity_matrix(cairo); + } + data.state &= ~DRAW_OFFSET; } /** @@ -3872,9 +3872,9 @@ * @deprecated this functionality is not supported on some platforms */ public void setXORMode(bool xor) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - OS.gdk_gc_set_function(handle, xor ? OS.GDK_XOR : OS.GDK_COPY); - data.xorMode = xor; + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + OS.gdk_gc_set_function(handle, xor ? OS.GDK_XOR : OS.GDK_COPY); + data.xorMode = xor; } /** @@ -3897,7 +3897,7 @@ * */ public Point stringExtent(char[] str) { - return textExtent(str, 0); + return textExtent(str, 0); } /** @@ -3920,7 +3920,7 @@ * */ public Point textExtent(char[] str) { - return textExtent(str, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); + return textExtent(str, SWT.DRAW_DELIMITER | SWT.DRAW_TAB); } /** @@ -3955,27 +3955,27 @@ * */ public Point textExtent(char[] str, int flags) { - if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - auto cairo = data.cairo; - if (cairo !is null) { - if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { - //TODO - honor flags - checkGC(FONT); - char[] buffer = str.dup; - 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.ptr, extents); - return new Point(cast(int)extents.width, cast(int)font_extents.height); - } - } - setString(str, flags); - checkGC(FONT); - if (data.stringWidth !is -1) return new Point(data.stringWidth, data.stringHeight); - int width, height; - OS.pango_layout_get_size(data.layout, &width, &height); - return new Point(data.stringWidth = OS.PANGO_PIXELS(width), data.stringHeight = OS.PANGO_PIXELS(height)); + if (handle is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (str is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + auto cairo = data.cairo; + if (cairo !is null) { + if (OS.GTK_VERSION < OS.buildVERSION(2, 8, 0)) { + //TODO - honor flags + checkGC(FONT); + char[] buffer = str.dup; + 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.ptr, extents); + return new Point(cast(int)extents.width, cast(int)font_extents.height); + } + } + setString(str, flags); + checkGC(FONT); + if (data.stringWidth !is -1) return new Point(data.stringWidth, data.stringHeight); + int width, height; + OS.pango_layout_get_size(data.layout, &width, &height); + return new Point(data.stringWidth = OS.PANGO_PIXELS(width), data.stringHeight = OS.PANGO_PIXELS(height)); } /** @@ -3985,8 +3985,8 @@ * @return a str representation of the receiver */ public char[] toString () { - if (isDisposed()) return "GC {*DISPOSED*}"; - return Format( "GC {{{}}", handle ); + if (isDisposed()) return "GC {*DISPOSED*}"; + return Format( "GC {{{}}", handle ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/GCData.d --- a/dwt/graphics/GCData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/GCData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -27,37 +27,37 @@ *

    */ public final class GCData { - public Device device; - public int style, state = -1; - public GdkColor* foreground; - public GdkColor* background; - public PangoFontDescription* font; - public Pattern foregroundPattern; - public Pattern backgroundPattern; - public GdkRegion* clipRgn; - public float lineWidth; - public int lineStyle = SWT.LINE_SOLID; - public float[] lineDashes; - public float lineDashesOffset; - public float lineMiterLimit = 10; - public int lineCap = SWT.CAP_FLAT; - public int lineJoin = SWT.JOIN_MITER; - public bool xorMode; - public int alpha = 0xFF; - public int interpolation = SWT.DEFAULT; + public Device device; + public int style, state = -1; + public GdkColor* foreground; + public GdkColor* background; + public PangoFontDescription* font; + public Pattern foregroundPattern; + public Pattern backgroundPattern; + public GdkRegion* clipRgn; + public float lineWidth; + public int lineStyle = SWT.LINE_SOLID; + public float[] lineDashes; + public float lineDashesOffset; + public float lineMiterLimit = 10; + public int lineCap = SWT.CAP_FLAT; + public int lineJoin = SWT.JOIN_MITER; + public bool xorMode; + public int alpha = 0xFF; + public int interpolation = SWT.DEFAULT; - public PangoContext* context; - public PangoLayout* layout; - public GdkRegion* damageRgn; - public Image image; - public GdkDrawable* drawable; - public cairo_t* cairo; - public double cairoXoffset, cairoYoffset; - public bool disposeCairo; - public double[] clippingTransform; - public char[] str; - public int stringWidth = -1; - public int stringHeight = -1; - public int drawFlags; + public PangoContext* context; + public PangoLayout* layout; + public GdkRegion* damageRgn; + public Image image; + public GdkDrawable* drawable; + public cairo_t* cairo; + public double cairoXoffset, cairoYoffset; + public bool disposeCairo; + public double[] clippingTransform; + public char[] str; + public int stringWidth = -1; + public int stringHeight = -1; + public int drawFlags; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/GlyphMetrics.d --- a/dwt/graphics/GlyphMetrics.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/GlyphMetrics.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -33,20 +33,20 @@ */ public final class GlyphMetrics { - /** - * the ascent of the GlyphMetrics - */ - public int ascent; + /** + * the ascent of the GlyphMetrics + */ + public int ascent; - /** - * the descent of the GlyphMetrics - */ - public int descent; + /** + * the descent of the GlyphMetrics + */ + public int descent; - /** - * the width of the GlyphMetrics - */ - public int width; + /** + * the width of the GlyphMetrics + */ + public int width; /** * Constructs an instance of this class with the given @@ -57,12 +57,12 @@ * */ public this(int ascent, int descent, int width) { - if (ascent < 0 || descent < 0 || width < 0) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - this.ascent = ascent; - this.descent = descent; - this.width = width; + if (ascent < 0 || descent < 0 || width < 0) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + this.ascent = ascent; + this.descent = descent; + this.width = width; } /** @@ -76,8 +76,8 @@ * @see #hashCode() */ public override int opEquals (Object object) { - if (object is this) return true; - if (auto metrics = cast(GlyphMetrics)object ){ + if (object is this) return true; + if (auto metrics = cast(GlyphMetrics)object ){ return metrics.ascent == ascent && metrics.descent == descent && metrics.width == width; } return false; @@ -95,7 +95,7 @@ * @see #equals(Object) */ public override hash_t toHash () { - return ascent ^ descent ^ width; + return ascent ^ descent ^ width; } /** @@ -105,7 +105,7 @@ * @return a string representation of the GlyphMetrics */ public override char[] toString () { - return Format( "GlyphMetrics {{{}, {}, {}}", ascent, descent, width ); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + return Format( "GlyphMetrics {{{}, {}, {}}", ascent, descent, width ); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Image.d --- a/dwt/graphics/Image.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Image.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -89,79 +89,79 @@ */ public final class Image : Resource, Drawable { - /** - * specifies whether the receiver is a bitmap or an icon - * (one of SWT.BITMAP, SWT.ICON) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public int type; + /** + * specifies whether the receiver is a bitmap or an icon + * (one of SWT.BITMAP, SWT.ICON) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public int type; - /** - * The handle to the OS pixmap resource. - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public GdkDrawable* pixmap; + /** + * The handle to the OS pixmap resource. + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public GdkDrawable* pixmap; - /** - * The handle to the OS mask resource. - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public GdkDrawable* mask; + /** + * The handle to the OS mask resource. + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public GdkDrawable* mask; - cairo_surface_t* surface; + cairo_surface_t* surface; cairo_surface_t* surfaceData; - /** - * specifies the transparent pixel - */ - int transparentPixel = -1; + /** + * specifies the transparent pixel + */ + int transparentPixel = -1; - /** - * The GC the image is currently selected in. - */ - GC memGC; + /** + * The GC the image is currently selected in. + */ + GC memGC; - /** - * The alpha data of the image. - */ - byte[] alphaData; + /** + * The alpha data of the image. + */ + byte[] alphaData; - /** - * The global alpha value to be used for every pixel. - */ - int alpha = -1; + /** + * The global alpha value to be used for every pixel. + */ + int alpha = -1; - /** - * The width of the image. - */ - int width = -1; + /** + * The width of the image. + */ + int width = -1; - /** - * The height of the image. - */ - int height = -1; + /** + * The height of the image. + */ + int height = -1; - /** - * Specifies the default scanline padding. - */ - static const int DEFAULT_SCANLINE_PAD = 4; + /** + * Specifies the default scanline padding. + */ + static const int DEFAULT_SCANLINE_PAD = 4; this() { } @@ -197,10 +197,10 @@ * */ public this(Device device, int width, int height) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, width, height); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, width, height); + if (device.tracking) device.new_Object(this); } /** @@ -235,136 +235,136 @@ * */ public this(Device device, Image srcImage, int flag) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (srcImage is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (srcImage.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - switch (flag) { - case SWT.IMAGE_COPY: - case SWT.IMAGE_DISABLE: - case SWT.IMAGE_GRAY: - break; - default: - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - this.device = device; - this.type = srcImage.type; + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (srcImage is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (srcImage.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + switch (flag) { + case SWT.IMAGE_COPY: + case SWT.IMAGE_DISABLE: + case SWT.IMAGE_GRAY: + break; + default: + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + this.device = device; + this.type = srcImage.type; - /* Get source image size */ - int w, h; - OS.gdk_drawable_get_size(srcImage.pixmap, &w, &h); - int width = w; - int height = h; + /* Get source image size */ + int w, h; + OS.gdk_drawable_get_size(srcImage.pixmap, &w, &h); + int width = w; + int height = h; - /* Copy the mask */ - if ((srcImage.type == SWT.ICON && srcImage.mask !is null ) || srcImage.transparentPixel != -1) { - /* Generate the mask if necessary. */ - if (srcImage.transparentPixel != -1) srcImage.createMask(); + /* Copy the mask */ + if ((srcImage.type == SWT.ICON && srcImage.mask !is null ) || srcImage.transparentPixel != -1) { + /* Generate the mask if necessary. */ + if (srcImage.transparentPixel != -1) srcImage.createMask(); //PORTING_FIXME cast - GdkDrawable* mask = cast(GdkDrawable*) OS.gdk_pixmap_new( null, width, height, 1); - if (mask is null ) SWT.error(SWT.ERROR_NO_HANDLES); - auto gdkGC = OS.gdk_gc_new(mask); - if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.gdk_draw_drawable(mask, gdkGC, srcImage.mask, 0, 0, 0, 0, width, height); - OS.g_object_unref(gdkGC); - 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(); - } + GdkDrawable* mask = cast(GdkDrawable*) OS.gdk_pixmap_new( null, width, height, 1); + if (mask is null ) SWT.error(SWT.ERROR_NO_HANDLES); + auto gdkGC = OS.gdk_gc_new(mask); + if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.gdk_draw_drawable(mask, gdkGC, srcImage.mask, 0, 0, 0, 0, width, height); + OS.g_object_unref(gdkGC); + 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(); + } - /* Copy transparent pixel and alpha data */ - if (flag != SWT.IMAGE_DISABLE) transparentPixel = srcImage.transparentPixel; - alpha = srcImage.alpha; - if (srcImage.alphaData != null) { + /* Copy transparent pixel and alpha data */ + if (flag != SWT.IMAGE_DISABLE) 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); + } + createAlphaMask(width, height); - /* Create the new pixmap */ - auto pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new (cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); - if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto gdkGC = OS.gdk_gc_new(pixmap); - if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); - this.pixmap = pixmap; + /* Create the new pixmap */ + auto pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new (cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); + if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto gdkGC = OS.gdk_gc_new(pixmap); + if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); + this.pixmap = pixmap; - if (flag == SWT.IMAGE_COPY) { - OS.gdk_draw_drawable(pixmap, gdkGC, srcImage.pixmap, 0, 0, 0, 0, width, height); - OS.g_object_unref(gdkGC); - if (device.tracking) device.new_Object(this); - return; - } + if (flag == SWT.IMAGE_COPY) { + OS.gdk_draw_drawable(pixmap, gdkGC, srcImage.pixmap, 0, 0, 0, 0, width, height); + OS.g_object_unref(gdkGC); + if (device.tracking) device.new_Object(this); + return; + } - /* Retrieve the source pixmap data */ - auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, width, height); - if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_pixbuf_get_from_drawable(pixbuf, srcImage.pixmap, colormap, 0, 0, 0, 0, width, height); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); + /* Retrieve the source pixmap data */ + auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, width, height); + if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto colormap = OS.gdk_colormap_get_system(); + OS.gdk_pixbuf_get_from_drawable(pixbuf, srcImage.pixmap, colormap, 0, 0, 0, 0, width, height); + int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); + auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - /* Apply transformation */ - switch (flag) { - case SWT.IMAGE_DISABLE: { - Color zeroColor = device.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); - RGB zeroRGB = zeroColor.getRGB(); - byte zeroRed = cast(byte)zeroRGB.red; - byte zeroGreen = cast(byte)zeroRGB.green; - byte zeroBlue = cast(byte)zeroRGB.blue; - Color oneColor = device.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); - RGB oneRGB = oneColor.getRGB(); - byte oneRed = cast(byte)oneRGB.red; - byte oneGreen = cast(byte)oneRGB.green; - byte oneBlue = cast(byte)oneRGB.blue; - byte[] line = new byte[stride]; - for (int y=0; y> 3); - line[offset] = line[offset+1] = line[offset+2] = intensity; - } - memmove(pixels + (y * stride), line.ptr, stride); - } - break; - } + /* Apply transformation */ + switch (flag) { + case SWT.IMAGE_DISABLE: { + Color zeroColor = device.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); + RGB zeroRGB = zeroColor.getRGB(); + byte zeroRed = cast(byte)zeroRGB.red; + byte zeroGreen = cast(byte)zeroRGB.green; + byte zeroBlue = cast(byte)zeroRGB.blue; + Color oneColor = device.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); + RGB oneRGB = oneColor.getRGB(); + byte oneRed = cast(byte)oneRGB.red; + byte oneGreen = cast(byte)oneRGB.green; + byte oneBlue = cast(byte)oneRGB.blue; + byte[] line = new byte[stride]; + for (int y=0; y> 3); + line[offset] = line[offset+1] = line[offset+2] = intensity; + } + memmove(pixels + (y * stride), line.ptr, stride); + } + break; + } default: - } + } - /* Copy data back to destination pixmap */ - OS.gdk_pixbuf_render_to_drawable(pixbuf, pixmap, gdkGC, 0, 0, 0, 0, width, height, OS.GDK_RGB_DITHER_NORMAL, 0, 0); + /* Copy data back to destination pixmap */ + OS.gdk_pixbuf_render_to_drawable(pixbuf, pixmap, gdkGC, 0, 0, 0, 0, width, height, OS.GDK_RGB_DITHER_NORMAL, 0, 0); - /* Free resources */ - OS.g_object_unref(pixbuf); - OS.g_object_unref(gdkGC); - if (device.tracking) device.new_Object(this); + /* Free resources */ + OS.g_object_unref(pixbuf); + OS.g_object_unref(gdkGC); + if (device.tracking) device.new_Object(this); } /** @@ -398,11 +398,11 @@ * */ public this(Device device, Rectangle bounds) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (bounds is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, bounds.width, bounds.height); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (bounds is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, bounds.width, bounds.height); + if (device.tracking) device.new_Object(this); } /** @@ -424,10 +424,10 @@ * */ public this(Device device, ImageData data) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, data); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, data); + if (device.tracking) device.new_Object(this); } /** @@ -456,19 +456,19 @@ * */ public this(Device device, ImageData source, ImageData mask) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (source is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (mask is 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(device, image); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (source is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (mask is 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(device, image); + if (device.tracking) device.new_Object(this); } /** @@ -520,10 +520,10 @@ * */ public this(Device device, InputStream stream) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - init(device, new ImageData(stream)); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + init(device, new ImageData(stream)); + if (device.tracking) device.new_Object(this); } /** @@ -554,222 +554,222 @@ * */ public this(Device device, char[] filename) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - try { - int length = filename.length; - auto pixbuf = OS.gdk_pixbuf_new_from_file(toStringz(filename), null); - if (pixbuf !is null) { - bool hasAlpha = cast(bool)OS.gdk_pixbuf_get_has_alpha(pixbuf); - if (hasAlpha) { - /* - * Bug in GTK. Depending on the image (seems to affect images that have - * some degree of transparency all over the image), gdk_pixbuff_render_pixmap_and_mask() - * will return a corrupt pixmap. To avoid this, read in and store the alpha channel data - * for the image and then set it to 0xFF to prevent any possible corruption from - * gdk_pixbuff_render_pixmap_and_mask(). - */ - int width = OS.gdk_pixbuf_get_width(pixbuf); - int height = OS.gdk_pixbuf_get_height(pixbuf); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] line = new byte[stride]; - alphaData = new byte[width * height]; - for (int y = 0; y < height; y++) { - memmove(line.ptr, pixels + (y * stride), stride); - for (int x = 0; x < width; x++) { - alphaData[y*width+x] = line[x*4 + 3]; - line[x*4 + 3] = cast(byte) 0xFF; - } - memmove(pixels + (y * stride), line.ptr, stride); - } - createAlphaMask(width, height); - } - GdkPixmap* pixmap_return; - OS.gdk_pixbuf_render_pixmap_and_mask(pixbuf, &pixmap_return, null, 0); - this.type = SWT.BITMAP; - this.pixmap = cast(GdkDrawable*)pixmap_return; - if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.g_object_unref (pixbuf); - return; - } - } catch (SWTException e) {} - init(device, new ImageData(filename)); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + try { + int length = filename.length; + auto pixbuf = OS.gdk_pixbuf_new_from_file(toStringz(filename), null); + if (pixbuf !is null) { + bool hasAlpha = cast(bool)OS.gdk_pixbuf_get_has_alpha(pixbuf); + if (hasAlpha) { + /* + * Bug in GTK. Depending on the image (seems to affect images that have + * some degree of transparency all over the image), gdk_pixbuff_render_pixmap_and_mask() + * will return a corrupt pixmap. To avoid this, read in and store the alpha channel data + * for the image and then set it to 0xFF to prevent any possible corruption from + * gdk_pixbuff_render_pixmap_and_mask(). + */ + int width = OS.gdk_pixbuf_get_width(pixbuf); + int height = OS.gdk_pixbuf_get_height(pixbuf); + int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); + auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); + byte[] line = new byte[stride]; + alphaData = new byte[width * height]; + for (int y = 0; y < height; y++) { + memmove(line.ptr, pixels + (y * stride), stride); + for (int x = 0; x < width; x++) { + alphaData[y*width+x] = line[x*4 + 3]; + line[x*4 + 3] = cast(byte) 0xFF; + } + memmove(pixels + (y * stride), line.ptr, stride); + } + createAlphaMask(width, height); + } + GdkPixmap* pixmap_return; + OS.gdk_pixbuf_render_pixmap_and_mask(pixbuf, &pixmap_return, null, 0); + this.type = SWT.BITMAP; + this.pixmap = cast(GdkDrawable*)pixmap_return; + if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.g_object_unref (pixbuf); + return; + } + } catch (SWTException e) {} + init(device, new ImageData(filename)); + if (device.tracking) device.new_Object(this); } void createAlphaMask (int width, int height) { - if (device.useXRender && (alpha != -1 || alphaData != null)) { - mask = cast(GdkDrawable*)OS.gdk_pixmap_new(null, alpha != -1 ? 1 : width, alpha != -1 ? 1 : height, 8); - if (mask is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto gc = OS.gdk_gc_new(mask); - if (alpha != -1) { - GdkColor* color = new GdkColor(); - color.pixel = (alpha & 0xFF) << 8 | (alpha & 0xFF); - OS.gdk_gc_set_foreground(gc, color); - OS.gdk_draw_rectangle(mask, gc, 1, 0, 0, 1, 1); - } else { - GdkImage* imagePtr = OS.gdk_drawable_get_image(mask, 0, 0, width, height); - if (imagePtr is null) SWT.error(SWT.ERROR_NO_HANDLES); - GdkImage* gdkImage = new GdkImage(); - *gdkImage = *imagePtr; - if (gdkImage.bpl == width) { - memmove(gdkImage.mem, alphaData.ptr, alphaData.length); - } else { - byte[] line = new byte[gdkImage.bpl]; - for (int y = 0; y < height; y++) { + if (device.useXRender && (alpha != -1 || alphaData != null)) { + mask = cast(GdkDrawable*)OS.gdk_pixmap_new(null, alpha != -1 ? 1 : width, alpha != -1 ? 1 : height, 8); + if (mask is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto gc = OS.gdk_gc_new(mask); + if (alpha != -1) { + GdkColor* color = new GdkColor(); + color.pixel = (alpha & 0xFF) << 8 | (alpha & 0xFF); + OS.gdk_gc_set_foreground(gc, color); + OS.gdk_draw_rectangle(mask, gc, 1, 0, 0, 1, 1); + } else { + GdkImage* imagePtr = OS.gdk_drawable_get_image(mask, 0, 0, width, height); + if (imagePtr is null) SWT.error(SWT.ERROR_NO_HANDLES); + GdkImage* gdkImage = new GdkImage(); + *gdkImage = *imagePtr; + if (gdkImage.bpl == width) { + memmove(gdkImage.mem, alphaData.ptr, alphaData.length); + } else { + byte[] line = new byte[gdkImage.bpl]; + for (int y = 0; y < height; y++) { System.arraycopy(alphaData, width * y, line, 0, width); - memmove(gdkImage.mem + (gdkImage.bpl * y), line.ptr, gdkImage.bpl); - } - } - OS.gdk_draw_image(mask, gc, imagePtr, 0, 0, 0, 0, width, height); - OS.g_object_unref(imagePtr); - } - OS.g_object_unref(gc); - } + memmove(gdkImage.mem + (gdkImage.bpl * y), line.ptr, gdkImage.bpl); + } + } + OS.gdk_draw_image(mask, gc, imagePtr, 0, 0, 0, 0, width, height); + OS.g_object_unref(imagePtr); + } + OS.g_object_unref(gc); + } } /** * Create the receiver's mask if necessary. */ void createMask() { - if (mask !is null ) return; - mask = createMask(getImageData(), false); - if (mask is null ) SWT.error(SWT.ERROR_NO_HANDLES); + if (mask !is null ) return; + mask = createMask(getImageData(), false); + if (mask is null ) SWT.error(SWT.ERROR_NO_HANDLES); } GdkDrawable* createMask(ImageData image, bool copy) { - ImageData mask = image.getTransparencyMask(); - byte[] data = mask.data; - byte[] maskData = copy ? new byte[data.length] : data; - for (int i = 0; i < maskData.length; i++) { - byte s = data[i]; - maskData[i] = cast(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); - return cast(GdkDrawable*)OS.gdk_bitmap_create_from_data(null, cast(char*)maskData.ptr, mask.width, mask.height); + ImageData mask = image.getTransparencyMask(); + byte[] data = mask.data; + byte[] maskData = copy ? new byte[data.length] : data; + for (int i = 0; i < maskData.length; i++) { + byte s = data[i]; + maskData[i] = cast(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); + return cast(GdkDrawable*)OS.gdk_bitmap_create_from_data(null, cast(char*)maskData.ptr, mask.width, mask.height); } void createSurface() { - if (surface !is null ) return; - /* Generate the mask if necessary. */ - if (transparentPixel != -1) createMask(); - int w, h; - OS.gdk_drawable_get_size(pixmap, &w, &h); - int width = w, height = h; - if (mask !is null || alpha != -1 || alphaData != null) { - auto pixbuf = OS.gdk_pixbuf_new( OS.GDK_COLORSPACE_RGB, true, 8, width, height); - if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_pixbuf_get_from_drawable(pixbuf, pixmap, colormap, 0, 0, 0, 0, width, height); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] line = new byte[stride]; - if (mask !is null && OS.gdk_drawable_get_depth(mask) == 1) { - auto maskPixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, width, height); - if (maskPixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.gdk_pixbuf_get_from_drawable(maskPixbuf, mask, null, 0, 0, 0, 0, width, height); - int maskStride = OS.gdk_pixbuf_get_rowstride(maskPixbuf); - auto maskPixels = OS.gdk_pixbuf_get_pixels(maskPixbuf); - byte[] maskLine = new byte[maskStride]; - auto offset = pixels, maskOffset = maskPixels; - for (int y=0; y> 8)) >> 8; - int g = ((line[offset1 + 1] & 0xFF) * alpha) + 128; - g = (g + (g >> 8)) >> 8; - int b = ((line[offset1 + 2] & 0xFF) * alpha) + 128; - b = (b + (b >> 8)) >> 8; - line[offset1 + 0] = cast(byte)b; - line[offset1 + 1] = cast(byte)g; - line[offset1 + 2] = cast(byte)r; - } - memmove(offset, line.ptr, stride); - offset += stride; - } - } else if (alphaData != null) { - auto offset = pixels; - for (int y = 0; y < h; y++) { - memmove (line.ptr, offset, stride); - for (int x=0, offset1=0; x> 8)) >> 8; - int g = ((line[offset1 + 1] & 0xFF) * alpha) + 128; - g = (g + (g >> 8)) >> 8; - int b = ((line[offset1 + 2] & 0xFF) * alpha) + 128; - b = (b + (b >> 8)) >> 8; - line[offset1 + 0] = cast(byte)b; - line[offset1 + 1] = cast(byte)g; - line[offset1 + 2] = cast(byte)r; - } - memmove (offset, line.ptr, stride); - offset += stride; - } - } else { - auto offset = pixels; - for (int y = 0; y < h; y++) { - memmove (line.ptr, offset, stride); - for (int x=0, offset1=0; x> 8)) >> 8; + int g = ((line[offset1 + 1] & 0xFF) * alpha) + 128; + g = (g + (g >> 8)) >> 8; + int b = ((line[offset1 + 2] & 0xFF) * alpha) + 128; + b = (b + (b >> 8)) >> 8; + line[offset1 + 0] = cast(byte)b; + line[offset1 + 1] = cast(byte)g; + line[offset1 + 2] = cast(byte)r; + } + memmove(offset, line.ptr, stride); + offset += stride; + } + } else if (alphaData != null) { + auto offset = pixels; + for (int y = 0; y < h; y++) { + memmove (line.ptr, offset, stride); + for (int x=0, offset1=0; x> 8)) >> 8; + int g = ((line[offset1 + 1] & 0xFF) * alpha) + 128; + g = (g + (g >> 8)) >> 8; + int b = ((line[offset1 + 2] & 0xFF) * alpha) + 128; + b = (b + (b >> 8)) >> 8; + line[offset1 + 0] = cast(byte)b; + line[offset1 + 1] = cast(byte)g; + line[offset1 + 2] = cast(byte)r; + } + memmove (offset, line.ptr, stride); + offset += stride; + } + } else { + auto offset = pixels; + for (int y = 0; y < h; y++) { + memmove (line.ptr, offset, stride); + for (int x=0, offset1=0; x */ public Color getBackground() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (transparentPixel == -1) return null; - //NOT DONE - return null; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (transparentPixel == -1) return null; + //NOT DONE + return null; } /** @@ -850,13 +850,13 @@ * */ public Rectangle getBounds() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (width != -1 && height != -1) { - return new Rectangle(0, 0, width, height); - } - int w; int h; - OS.gdk_drawable_get_size(pixmap, &w, &h); - return new Rectangle(0, 0, width = w, height = h); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width != -1 && height != -1) { + return new Rectangle(0, 0, width, height); + } + int w; int h; + OS.gdk_drawable_get_size(pixmap, &w, &h); + return new Rectangle(0, 0, width = w, height = h); } /** @@ -874,61 +874,61 @@ * @see ImageData */ public ImageData getImageData() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - int w, h; - OS.gdk_drawable_get_size(pixmap, &w, &h); - int width = w, height = h; - auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, width, height); - if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_pixbuf_get_from_drawable(pixbuf, pixmap, colormap, 0, 0, 0, 0, width, height); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] srcData = new byte[stride * height]; - memmove(srcData.ptr, pixels, srcData.length); - OS.g_object_unref(pixbuf); + int w, h; + OS.gdk_drawable_get_size(pixmap, &w, &h); + int width = w, height = h; + auto pixbuf = OS.gdk_pixbuf_new(OS.GDK_COLORSPACE_RGB, false, 8, width, height); + if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto colormap = OS.gdk_colormap_get_system(); + OS.gdk_pixbuf_get_from_drawable(pixbuf, pixmap, colormap, 0, 0, 0, 0, width, height); + int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); + auto pixels = OS.gdk_pixbuf_get_pixels(pixbuf); + byte[] srcData = new byte[stride * height]; + memmove(srcData.ptr, pixels, srcData.length); + OS.g_object_unref(pixbuf); - PaletteData palette = new PaletteData(0xFF0000, 0xFF00, 0xFF); - ImageData data = new ImageData(width, height, 24, palette); - data.data = srcData; - data.bytesPerLine = stride; + PaletteData palette = new PaletteData(0xFF0000, 0xFF00, 0xFF); + ImageData data = new ImageData(width, height, 24, palette); + data.data = srcData; + data.bytesPerLine = stride; - if (transparentPixel == -1 && type == SWT.ICON && mask !is null) { - /* Get the icon mask data */ - auto gdkImagePtr = OS.gdk_drawable_get_image(mask, 0, 0, width, height); - if (gdkImagePtr is null) SWT.error(SWT.ERROR_NO_HANDLES); - GdkImage* gdkImage = new GdkImage(); - memmove(gdkImage, gdkImagePtr, GdkImage.sizeof ); - byte[] maskData = new byte[gdkImage.bpl * gdkImage.height]; - memmove(maskData.ptr, gdkImage.mem, maskData.length); - OS.g_object_unref(gdkImagePtr); - int maskPad; - for (maskPad = 1; maskPad < 128; maskPad++) { - int bpl = (((width + 7) / 8) + (maskPad - 1)) / maskPad * maskPad; - if (gdkImage.bpl == bpl) break; - } - /* 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 (gdkImage.byte_order == OS.GDK_LSB_FIRST) { - for (int i = 0; i < maskData.length; i++) { - byte b = maskData[i]; - maskData[i] = cast(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) { + if (transparentPixel == -1 && type == SWT.ICON && mask !is null) { + /* Get the icon mask data */ + auto gdkImagePtr = OS.gdk_drawable_get_image(mask, 0, 0, width, height); + if (gdkImagePtr is null) SWT.error(SWT.ERROR_NO_HANDLES); + GdkImage* gdkImage = new GdkImage(); + memmove(gdkImage, gdkImagePtr, GdkImage.sizeof ); + byte[] maskData = new byte[gdkImage.bpl * gdkImage.height]; + memmove(maskData.ptr, gdkImage.mem, maskData.length); + OS.g_object_unref(gdkImagePtr); + int maskPad; + for (maskPad = 1; maskPad < 128; maskPad++) { + int bpl = (((width + 7) / 8) + (maskPad - 1)) / maskPad * maskPad; + if (gdkImage.bpl == bpl) break; + } + /* 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 (gdkImage.byte_order == OS.GDK_LSB_FIRST) { + for (int i = 0; i < maskData.length; i++) { + byte b = maskData[i]; + maskData[i] = cast(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); - } - return data; + } + return data; } /** @@ -949,13 +949,13 @@ * @private */ public static Image gtk_new(Device device, int type, int /*long*/ pixmap, int /*long*/ mask) { - if (device is null) device = Device.getDevice(); - Image image = new Image(); - image.type = type; - image.pixmap = cast(GdkDrawable*)pixmap; - image.mask = cast(GdkDrawable*)mask; - image.device = device; - return image; + if (device is null) device = Device.getDevice(); + Image image = new Image(); + image.type = type; + image.pixmap = cast(GdkDrawable*)pixmap; + image.mask = cast(GdkDrawable*)mask; + image.device = device; + return image; } /** @@ -969,118 +969,118 @@ * @see #equals */ public hash_t toHash () { - return cast(hash_t)/*64*/pixmap; + return cast(hash_t)/*64*/pixmap; } void init(Device device, int width, int height) { - if (width <= 0 || height <= 0) { - SWT.error (SWT.ERROR_INVALID_ARGUMENT); - } - this.device = device; - this.type = SWT.BITMAP; + if (width <= 0 || height <= 0) { + SWT.error (SWT.ERROR_INVALID_ARGUMENT); + } + this.device = device; + this.type = SWT.BITMAP; - /* Create the pixmap */ - this.pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new(cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); - if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); - /* Fill the bitmap with white */ - GdkColor* white = new GdkColor(); - white.red = 0xFFFF; - white.green = 0xFFFF; - white.blue = 0xFFFF; - auto colormap = OS.gdk_colormap_get_system(); - OS.gdk_colormap_alloc_color(colormap, white, true, true); - auto gdkGC = OS.gdk_gc_new(pixmap); - OS.gdk_gc_set_foreground(gdkGC, white); - OS.gdk_draw_rectangle(pixmap, gdkGC, 1, 0, 0, width, height); - OS.g_object_unref(gdkGC); - OS.gdk_colormap_free_colors(colormap, white, 1); + /* Create the pixmap */ + this.pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new(cast(GdkDrawable*)OS.GDK_ROOT_PARENT(), width, height, -1); + if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); + /* Fill the bitmap with white */ + GdkColor* white = new GdkColor(); + white.red = 0xFFFF; + white.green = 0xFFFF; + white.blue = 0xFFFF; + auto colormap = OS.gdk_colormap_get_system(); + OS.gdk_colormap_alloc_color(colormap, white, true, true); + auto gdkGC = OS.gdk_gc_new(pixmap); + OS.gdk_gc_set_foreground(gdkGC, white); + OS.gdk_draw_rectangle(pixmap, gdkGC, 1, 0, 0, width, height); + OS.g_object_unref(gdkGC); + OS.gdk_colormap_free_colors(colormap, white, 1); } void init(Device device, ImageData image) { - if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - int width = image.width; - int height = image.height; - 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))) - SWT.error (SWT.ERROR_UNSUPPORTED_DEPTH); - auto pixbuf = OS.gdk_pixbuf_new( OS.GDK_COLORSPACE_RGB, false, 8, width, height); - if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); - int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); - auto data = OS.gdk_pixbuf_get_pixels(pixbuf); - byte[] buffer = image.data; - if (!palette.isDirect || image.depth != 24 || stride != image.bytesPerLine || palette.redMask != 0xFF0000 || palette.greenMask != 0xFF00 || palette.blueMask != 0xFF) { - buffer = new byte[stride * height]; - if (palette.isDirect) { - ImageData.blit(ImageData.BLIT_SRC, - image.data, image.depth, image.bytesPerLine, image.getByteOrder(), 0, 0, width, height, palette.redMask, palette.greenMask, palette.blueMask, - ImageData.ALPHA_OPAQUE, null, 0, 0, 0, - buffer, 24, stride, ImageData.MSB_FIRST, 0, 0, width, height, 0xFF0000, 0xFF00, 0xFF, - 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 is null) continue; - srcReds[i] = cast(byte)rgb.red; - srcGreens[i] = cast(byte)rgb.green; - srcBlues[i] = cast(byte)rgb.blue; - } - ImageData.blit(ImageData.BLIT_SRC, - image.data, image.depth, image.bytesPerLine, image.getByteOrder(), 0, 0, width, height, srcReds, srcGreens, srcBlues, - ImageData.ALPHA_OPAQUE, null, 0, 0, 0, - buffer, 24, stride, ImageData.MSB_FIRST, 0, 0, width, height, 0xFF0000, 0xFF00, 0xFF, - false, false); - } - } - memmove(data, buffer.ptr, stride * height); - auto pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new (cast(GdkDrawable*) OS.GDK_ROOT_PARENT(), width, height, -1); - if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto gdkGC = OS.gdk_gc_new(pixmap); - if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.gdk_pixbuf_render_to_drawable(pixbuf, pixmap, gdkGC, 0, 0, 0, 0, width, height, OS.GDK_RGB_DITHER_NORMAL, 0, 0); - OS.g_object_unref(gdkGC); - OS.g_object_unref(pixbuf); + if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + int width = image.width; + int height = image.height; + 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))) + SWT.error (SWT.ERROR_UNSUPPORTED_DEPTH); + auto pixbuf = OS.gdk_pixbuf_new( OS.GDK_COLORSPACE_RGB, false, 8, width, height); + if (pixbuf is null) SWT.error(SWT.ERROR_NO_HANDLES); + int stride = OS.gdk_pixbuf_get_rowstride(pixbuf); + auto data = OS.gdk_pixbuf_get_pixels(pixbuf); + byte[] buffer = image.data; + if (!palette.isDirect || image.depth != 24 || stride != image.bytesPerLine || palette.redMask != 0xFF0000 || palette.greenMask != 0xFF00 || palette.blueMask != 0xFF) { + buffer = new byte[stride * height]; + if (palette.isDirect) { + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), 0, 0, width, height, palette.redMask, palette.greenMask, palette.blueMask, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + buffer, 24, stride, ImageData.MSB_FIRST, 0, 0, width, height, 0xFF0000, 0xFF00, 0xFF, + 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 is null) continue; + srcReds[i] = cast(byte)rgb.red; + srcGreens[i] = cast(byte)rgb.green; + srcBlues[i] = cast(byte)rgb.blue; + } + ImageData.blit(ImageData.BLIT_SRC, + image.data, image.depth, image.bytesPerLine, image.getByteOrder(), 0, 0, width, height, srcReds, srcGreens, srcBlues, + ImageData.ALPHA_OPAQUE, null, 0, 0, 0, + buffer, 24, stride, ImageData.MSB_FIRST, 0, 0, width, height, 0xFF0000, 0xFF00, 0xFF, + false, false); + } + } + memmove(data, buffer.ptr, stride * height); + auto pixmap = cast(GdkDrawable*) OS.gdk_pixmap_new (cast(GdkDrawable*) OS.GDK_ROOT_PARENT(), width, height, -1); + if (pixmap is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto gdkGC = OS.gdk_gc_new(pixmap); + if (gdkGC is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.gdk_pixbuf_render_to_drawable(pixbuf, pixmap, gdkGC, 0, 0, 0, 0, width, height, OS.GDK_RGB_DITHER_NORMAL, 0, 0); + OS.g_object_unref(gdkGC); + OS.g_object_unref(pixbuf); - bool isIcon = image.getTransparencyType() == SWT.TRANSPARENCY_MASK; - if (isIcon || image.transparentPixel != -1) { - if (image.transparentPixel != -1) { - RGB rgb = null; - if (palette.isDirect) { - rgb = palette.getRGB(image.transparentPixel); - } else { - if (image.transparentPixel < palette.colors.length) { - rgb = palette.getRGB(image.transparentPixel); - } - } - if (rgb != null) { - transparentPixel = rgb.red << 16 | rgb.green << 8 | rgb.blue; - } - } - auto mask = createMask(image, isIcon); - if (mask is null) SWT.error(SWT.ERROR_NO_HANDLES); - this.mask = mask; - if (isIcon) { - this.type = SWT.ICON; - } else { - this.type = SWT.BITMAP; - } - } else { - this.type = SWT.BITMAP; - this.mask = null; - this.alpha = image.alpha; - if (image.alpha == -1 && image.alphaData != null) { + bool isIcon = image.getTransparencyType() == SWT.TRANSPARENCY_MASK; + if (isIcon || image.transparentPixel != -1) { + if (image.transparentPixel != -1) { + RGB rgb = null; + if (palette.isDirect) { + rgb = palette.getRGB(image.transparentPixel); + } else { + if (image.transparentPixel < palette.colors.length) { + rgb = palette.getRGB(image.transparentPixel); + } + } + if (rgb != null) { + transparentPixel = rgb.red << 16 | rgb.green << 8 | rgb.blue; + } + } + auto mask = createMask(image, isIcon); + if (mask is null) SWT.error(SWT.ERROR_NO_HANDLES); + this.mask = mask; + if (isIcon) { + this.type = SWT.ICON; + } else { + this.type = SWT.BITMAP; + } + } else { + this.type = SWT.BITMAP; + this.mask = null; + 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(width, height); - } - this.pixmap = pixmap; + } + createAlphaMask(width, height); + } + this.pixmap = pixmap; } /** @@ -1097,24 +1097,24 @@ * @return the platform specific GC handle */ public GdkGC* internal_new_GC (GCData data) { - if (pixmap is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (type != SWT.BITMAP || memGC !is null) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - auto gdkGC = OS.gdk_gc_new(pixmap); - if (data !is 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.drawable = pixmap; - data.background = device.COLOR_WHITE.handle; - data.foreground = device.COLOR_BLACK.handle; - data.font = device.systemFont.handle; - data.image = this; - } - return gdkGC; + if (pixmap is null) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (type != SWT.BITMAP || memGC !is null) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + auto gdkGC = OS.gdk_gc_new(pixmap); + if (data !is 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.drawable = pixmap; + data.background = device.COLOR_WHITE.handle; + data.foreground = device.COLOR_BLACK.handle; + data.font = device.systemFont.handle; + data.image = this; + } + return gdkGC; } /** @@ -1131,7 +1131,7 @@ * @param data the platform specific GC data */ public void internal_dispose_GC ( GdkGC* gdkGC, GCData data) { - OS.g_object_unref(gdkGC); + OS.g_object_unref(gdkGC); } /** @@ -1145,7 +1145,7 @@ * @return true when the image is disposed and false otherwise */ public bool isDisposed() { - return pixmap is null; + return pixmap is null; } /** @@ -1183,11 +1183,11 @@ * */ public void setBackground(Color color) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (color is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (transparentPixel == -1) return; - //NOT DONE + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (color is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (transparentPixel == -1) return; + //NOT DONE } /** @@ -1197,9 +1197,9 @@ * @return a string representation of the receiver */ public char[] toString () { - if (isDisposed()) return "Image {*DISPOSED*}"; - return Format( "Image {{{}}", pixmap); + if (isDisposed()) return "Image {*DISPOSED*}"; + return Format( "Image {{{}}", pixmap); } } -} \ No newline at end of file +} diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/ImageData.d --- a/dwt/graphics/ImageData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/ImageData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -41,183 +41,183 @@ public final class ImageData : CloneableCompatibility { - /** - * The width of the image, in pixels. - */ - public int width; + /** + * The width of the image, in pixels. + */ + public int width; - /** - * The height of the image, in pixels. - */ - public int height; + /** + * The height of the image, in pixels. + */ + public int height; - /** - * The color depth of the image, in bits per pixel. - *

    - * Note that a depth of 8 or less does not necessarily - * mean that the image is palette indexed, or - * conversely that a depth greater than 8 means that - * the image is direct color. Check the associated - * PaletteData's isDirect field for such determinations. - */ - public int depth; + /** + * The color depth of the image, in bits per pixel. + *

    + * Note that a depth of 8 or less does not necessarily + * mean that the image is palette indexed, or + * conversely that a depth greater than 8 means that + * the image is direct color. Check the associated + * PaletteData's isDirect field for such determinations. + */ + public int depth; - /** - * The scanline padding. - *

    - * If one scanline of the image is not a multiple of - * this number, it will be padded with zeros until it is. - *

    - */ - public int scanlinePad; + /** + * The scanline padding. + *

    + * If one scanline of the image is not a multiple of + * this number, it will be padded with zeros until it is. + *

    + */ + public int scanlinePad; - /** - * The number of bytes per scanline. - *

    - * This is a multiple of the scanline padding. - *

    - */ - public int bytesPerLine; + /** + * The number of bytes per scanline. + *

    + * This is a multiple of the scanline padding. + *

    + */ + public int bytesPerLine; - /** - * The pixel data of the image. - *

    - * Note that for 16 bit depth images the pixel data is stored - * in least significant byte order; however, for 24bit and - * 32bit depth images the pixel data is stored in most - * significant byte order. - *

    - */ - public byte[] data; + /** + * The pixel data of the image. + *

    + * Note that for 16 bit depth images the pixel data is stored + * in least significant byte order; however, for 24bit and + * 32bit depth images the pixel data is stored in most + * significant byte order. + *

    + */ + public byte[] data; - /** - * The color table for the image. - */ - public PaletteData palette; + /** + * The color table for the image. + */ + public PaletteData palette; - /** - * The transparent pixel. - *

    - * Pixels with this value are transparent. - *

    - * The default is -1 which means 'no transparent pixel'. - *

    - */ - public int transparentPixel; + /** + * The transparent pixel. + *

    + * Pixels with this value are transparent. + *

    + * The default is -1 which means 'no transparent pixel'. + *

    + */ + public int transparentPixel; - /** - * An icon-specific field containing the data from the icon mask. - *

    - * This is a 1 bit bitmap stored with the most significant - * bit first. The number of bytes per scanline is - * '((width + 7) / 8 + (maskPad - 1)) / maskPad * maskPad'. - *

    - * The default is null which means 'no transparency mask'. - *

    - */ - public byte[] maskData; + /** + * An icon-specific field containing the data from the icon mask. + *

    + * This is a 1 bit bitmap stored with the most significant + * bit first. The number of bytes per scanline is + * '((width + 7) / 8 + (maskPad - 1)) / maskPad * maskPad'. + *

    + * The default is null which means 'no transparency mask'. + *

    + */ + public byte[] maskData; - /** - * An icon-specific field containing the scanline pad of the mask. - *

    - * If one scanline of the transparency mask is not a - * multiple of this number, it will be padded with zeros until - * it is. - *

    - */ - public int maskPad; + /** + * An icon-specific field containing the scanline pad of the mask. + *

    + * If one scanline of the transparency mask is not a + * multiple of this number, it will be padded with zeros until + * it is. + *

    + */ + public int maskPad; - /** - * The alpha data of the image. - *

    - * Every pixel can have an alpha blending value that - * varies from 0, meaning fully transparent, to 255 meaning - * fully opaque. The number of bytes per scanline is - * 'width'. - *

    - */ - public byte[] alphaData; + /** + * The alpha data of the image. + *

    + * Every pixel can have an alpha blending value that + * varies from 0, meaning fully transparent, to 255 meaning + * fully opaque. The number of bytes per scanline is + * 'width'. + *

    + */ + public byte[] alphaData; - /** - * The global alpha value to be used for every pixel. - *

    - * If this value is set, the alphaData field - * is ignored and when the image is rendered each pixel - * will be blended with the background an amount - * proportional to this value. - *

    - * The default is -1 which means 'no global alpha value' - *

    - */ - public int alpha; + /** + * The global alpha value to be used for every pixel. + *

    + * If this value is set, the alphaData field + * is ignored and when the image is rendered each pixel + * will be blended with the background an amount + * proportional to this value. + *

    + * The default is -1 which means 'no global alpha value' + *

    + */ + public int alpha; - /** - * The type of file from which the image was read. - * - * It is expressed as one of the following values: - *
    - *
    IMAGE_BMP
    - *
    Windows BMP file format, no compression
    - *
    IMAGE_BMP_RLE
    - *
    Windows BMP file format, RLE compression if appropriate
    - *
    IMAGE_GIF
    - *
    GIF file format
    - *
    IMAGE_ICO
    - *
    Windows ICO file format
    - *
    IMAGE_JPEG
    - *
    JPEG file format
    - *
    IMAGE_PNG
    - *
    PNG file format
    - *
    - */ - public int type; + /** + * The type of file from which the image was read. + * + * It is expressed as one of the following values: + *
    + *
    IMAGE_BMP
    + *
    Windows BMP file format, no compression
    + *
    IMAGE_BMP_RLE
    + *
    Windows BMP file format, RLE compression if appropriate
    + *
    IMAGE_GIF
    + *
    GIF file format
    + *
    IMAGE_ICO
    + *
    Windows ICO file format
    + *
    IMAGE_JPEG
    + *
    JPEG file format
    + *
    IMAGE_PNG
    + *
    PNG file format
    + *
    + */ + public int type; - /** - * The x coordinate of the top left corner of the image - * within the logical screen (this field corresponds to - * the GIF89a Image Left Position value). - */ - public int x; + /** + * The x coordinate of the top left corner of the image + * within the logical screen (this field corresponds to + * the GIF89a Image Left Position value). + */ + public int x; - /** - * The y coordinate of the top left corner of the image - * within the logical screen (this field corresponds to - * the GIF89a Image Top Position value). - */ - public int y; + /** + * The y coordinate of the top left corner of the image + * within the logical screen (this field corresponds to + * the GIF89a Image Top Position value). + */ + public int y; - /** - * A description of how to dispose of the current image - * before displaying the next. - * - * It is expressed as one of the following values: - *
    - *
    DM_UNSPECIFIED
    - *
    disposal method not specified
    - *
    DM_FILL_NONE
    - *
    do nothing - leave the image in place
    - *
    DM_FILL_BACKGROUND
    - *
    fill with the background color
    - *
    DM_FILL_PREVIOUS
    - *
    restore the previous picture
    - *
    - * (this field corresponds to the GIF89a Disposal Method value) - */ - public int disposalMethod; + /** + * A description of how to dispose of the current image + * before displaying the next. + * + * It is expressed as one of the following values: + *
    + *
    DM_UNSPECIFIED
    + *
    disposal method not specified
    + *
    DM_FILL_NONE
    + *
    do nothing - leave the image in place
    + *
    DM_FILL_BACKGROUND
    + *
    fill with the background color
    + *
    DM_FILL_PREVIOUS
    + *
    restore the previous picture
    + *
    + * (this field corresponds to the GIF89a Disposal Method value) + */ + public int disposalMethod; - /** - * The time to delay before displaying the next image - * in an animation (this field corresponds to the GIF89a - * Delay Time value). - */ - public int delayTime; + /** + * The time to delay before displaying the next image + * in an animation (this field corresponds to the GIF89a + * Delay Time value). + */ + public int delayTime; - /** - * Arbitrary channel width data to 8-bit conversion table. - */ - static byte[][] ANY_TO_EIGHT; + /** + * Arbitrary channel width data to 8-bit conversion table. + */ + static byte[][] ANY_TO_EIGHT; - synchronized static void static_this() { + synchronized static void static_this() { ANY_TO_EIGHT = new byte[][](9); for (int b = 0; b < 9; ++b) { byte[] data = ANY_TO_EIGHT[b] = new byte[1 << b]; @@ -227,22 +227,22 @@ for (int v = 0, p = 0; v < 0x10000; v+= inc) data[p++] = cast(byte)(v >> 8); } ONE_TO_ONE_MAPPING = ANY_TO_EIGHT[8]; - } - static byte[] ONE_TO_ONE_MAPPING; + } + static byte[] ONE_TO_ONE_MAPPING; - /** - * Scaled 8x8 Bayer dither matrix. - */ - static const int[][] DITHER_MATRIX = [ - [ 0xfc0000, 0x7c0000, 0xdc0000, 0x5c0000, 0xf40000, 0x740000, 0xd40000, 0x540000 ], - [ 0x3c0000, 0xbc0000, 0x1c0000, 0x9c0000, 0x340000, 0xb40000, 0x140000, 0x940000 ], - [ 0xcc0000, 0x4c0000, 0xec0000, 0x6c0000, 0xc40000, 0x440000, 0xe40000, 0x640000 ], - [ 0x0c0000, 0x8c0000, 0x2c0000, 0xac0000, 0x040000, 0x840000, 0x240000, 0xa40000 ], - [ 0xf00000, 0x700000, 0xd00000, 0x500000, 0xf80000, 0x780000, 0xd80000, 0x580000 ], - [ 0x300000, 0xb00000, 0x100000, 0x900000, 0x380000, 0xb80000, 0x180000, 0x980000 ], - [ 0xc00000, 0x400000, 0xe00000, 0x600000, 0xc80000, 0x480000, 0xe80000, 0x680000 ], - [ 0x000000, 0x800000, 0x200000, 0xa00000, 0x080000, 0x880000, 0x280000, 0xa80000 ] - ]; + /** + * Scaled 8x8 Bayer dither matrix. + */ + static const int[][] DITHER_MATRIX = [ + [ 0xfc0000, 0x7c0000, 0xdc0000, 0x5c0000, 0xf40000, 0x740000, 0xd40000, 0x540000 ], + [ 0x3c0000, 0xbc0000, 0x1c0000, 0x9c0000, 0x340000, 0xb40000, 0x140000, 0x940000 ], + [ 0xcc0000, 0x4c0000, 0xec0000, 0x6c0000, 0xc40000, 0x440000, 0xe40000, 0x640000 ], + [ 0x0c0000, 0x8c0000, 0x2c0000, 0xac0000, 0x040000, 0x840000, 0x240000, 0xa40000 ], + [ 0xf00000, 0x700000, 0xd00000, 0x500000, 0xf80000, 0x780000, 0xd80000, 0x580000 ], + [ 0x300000, 0xb00000, 0x100000, 0x900000, 0x380000, 0xb80000, 0x180000, 0x980000 ], + [ 0xc00000, 0x400000, 0xe00000, 0x600000, 0xc80000, 0x480000, 0xe80000, 0x680000 ], + [ 0x000000, 0x800000, 0x200000, 0xa00000, 0x080000, 0x880000, 0x280000, 0xa80000 ] + ]; /** * Constructs a new, empty ImageData with the given width, height, @@ -256,15 +256,15 @@ * * @exception IllegalArgumentException
      *
    • ERROR_INVALID_ARGUMENT - if the width or height is negative, or if the depth is not - * one of 1, 2, 4, 8, 16, 24 or 32
    • + * one of 1, 2, 4, 8, 16, 24 or 32 *
    • ERROR_NULL_ARGUMENT - if the palette is null
    • *
    */ public this(int width, int height, int depth, PaletteData palette) { - this(width, height, depth, palette, - 4, null, 0, null, - null, -1, -1, SWT.IMAGE_UNDEFINED, - 0, 0, 0, 0); + this(width, height, depth, palette, + 4, null, 0, null, + null, -1, -1, SWT.IMAGE_UNDEFINED, + 0, 0, 0, 0); } /** @@ -280,16 +280,16 @@ * * @exception IllegalArgumentException
      *
    • ERROR_INVALID_ARGUMENT - if the width or height is negative, or if the depth is not - * one of 1, 2, 4, 8, 16, 24 or 32
    • + * one of 1, 2, 4, 8, 16, 24 or 32 *
    • ERROR_NULL_ARGUMENT - if the palette or data is null
    • *
    • ERROR_CANNOT_BE_ZERO - if the scanlinePad is zero
    • *
    */ public this(int width, int height, int depth, PaletteData palette, int scanlinePad, byte[] data) { - this(width, height, depth, palette, - scanlinePad, checkData(data), 0, null, - null, -1, -1, SWT.IMAGE_UNDEFINED, - 0, 0, 0, 0); + this(width, height, depth, palette, + scanlinePad, checkData(data), 0, null, + null, -1, -1, SWT.IMAGE_UNDEFINED, + 0, 0, 0, 0); } /** @@ -336,27 +336,27 @@ * @see ImageLoader#load(InputStream) */ public this(InputStream stream) { - ImageData[] data = ImageDataLoader.load(stream); - if (data.length < 1) SWT.error(SWT.ERROR_INVALID_IMAGE); - ImageData i = data[0]; - setAllFields( - i.width, - i.height, - i.depth, - i.scanlinePad, - i.bytesPerLine, - i.data, - i.palette, - i.transparentPixel, - i.maskData, - i.maskPad, - i.alphaData, - i.alpha, - i.type, - i.x, - i.y, - i.disposalMethod, - i.delayTime); + ImageData[] data = ImageDataLoader.load(stream); + if (data.length < 1) SWT.error(SWT.ERROR_INVALID_IMAGE); + ImageData i = data[0]; + setAllFields( + i.width, + i.height, + i.depth, + i.scanlinePad, + i.bytesPerLine, + i.data, + i.palette, + i.transparentPixel, + i.maskData, + i.maskPad, + i.alphaData, + i.alpha, + i.type, + i.x, + i.y, + i.disposalMethod, + i.delayTime); } /** @@ -382,27 +382,27 @@ * */ public this(char[] filename) { - ImageData[] data = ImageDataLoader.load(filename); - if (data.length < 1) SWT.error(SWT.ERROR_INVALID_IMAGE); - ImageData i = data[0]; - setAllFields( - i.width, - i.height, - i.depth, - i.scanlinePad, - i.bytesPerLine, - i.data, - i.palette, - i.transparentPixel, - i.maskData, - i.maskPad, - i.alphaData, - i.alpha, - i.type, - i.x, - i.y, - i.disposalMethod, - i.delayTime); + ImageData[] data = ImageDataLoader.load(filename); + if (data.length < 1) SWT.error(SWT.ERROR_INVALID_IMAGE); + ImageData i = data[0]; + setAllFields( + i.width, + i.height, + i.depth, + i.scanlinePad, + i.bytesPerLine, + i.data, + i.palette, + i.transparentPixel, + i.maskData, + i.maskPad, + i.alphaData, + i.alpha, + i.type, + i.x, + i.y, + i.disposalMethod, + i.delayTime); } /** @@ -418,41 +418,41 @@ *

    */ this( - int width, int height, int depth, PaletteData palette, - int scanlinePad, byte[] data, int maskPad, byte[] maskData, - byte[] alphaData, int alpha, int transparentPixel, int type, - int x, int y, int disposalMethod, int delayTime) + int width, int height, int depth, PaletteData palette, + int scanlinePad, byte[] data, int maskPad, byte[] maskData, + byte[] alphaData, int alpha, int transparentPixel, int type, + int x, int y, int disposalMethod, int delayTime) { - if (palette == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (!(depth == 1 || depth == 2 || depth == 4 || depth == 8 - || depth == 16 || depth == 24 || depth == 32)) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - if (width <= 0 || height <= 0) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - if (scanlinePad == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); + if (palette == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (!(depth == 1 || depth == 2 || depth == 4 || depth == 8 + || depth == 16 || depth == 24 || depth == 32)) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + if (width <= 0 || height <= 0) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + if (scanlinePad == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); - int bytesPerLine = (((width * depth + 7) / 8) + (scanlinePad - 1)) - / scanlinePad * scanlinePad; - setAllFields( - width, - height, - depth, - scanlinePad, - bytesPerLine, - data != null ? data : new byte[bytesPerLine * height], - palette, - transparentPixel, - maskData, - maskPad, - alphaData, - alpha, - type, - x, - y, - disposalMethod, - delayTime); + int bytesPerLine = (((width * depth + 7) / 8) + (scanlinePad - 1)) + / scanlinePad * scanlinePad; + setAllFields( + width, + height, + depth, + scanlinePad, + bytesPerLine, + data != null ? data : new byte[bytesPerLine * height], + palette, + transparentPixel, + maskData, + maskPad, + alphaData, + alpha, + type, + x, + y, + disposalMethod, + delayTime); } /** @@ -465,27 +465,27 @@ *

    */ void setAllFields(int width, int height, int depth, int scanlinePad, - int bytesPerLine, byte[] data, PaletteData palette, int transparentPixel, - byte[] maskData, int maskPad, byte[] alphaData, int alpha, - int type, int x, int y, int disposalMethod, int delayTime) { + int bytesPerLine, byte[] data, PaletteData palette, int transparentPixel, + byte[] maskData, int maskPad, byte[] alphaData, int alpha, + int type, int x, int y, int disposalMethod, int delayTime) { - this.width = width; - this.height = height; - this.depth = depth; - this.scanlinePad = scanlinePad; - this.bytesPerLine = bytesPerLine; - this.data = data; - this.palette = palette; - this.transparentPixel = transparentPixel; - this.maskData = maskData; - this.maskPad = maskPad; - this.alphaData = alphaData; - this.alpha = alpha; - this.type = type; - this.x = x; - this.y = y; - this.disposalMethod = disposalMethod; - this.delayTime = delayTime; + this.width = width; + this.height = height; + this.depth = depth; + this.scanlinePad = scanlinePad; + this.bytesPerLine = bytesPerLine; + this.data = data; + this.palette = palette; + this.transparentPixel = transparentPixel; + this.maskData = maskData; + this.maskPad = maskPad; + this.alphaData = alphaData; + this.alpha = alpha; + this.type = type; + this.x = x; + this.y = y; + this.disposalMethod = disposalMethod; + this.delayTime = delayTime; } /** @@ -503,38 +503,38 @@ *

    */ public static ImageData internal_new( - int width, int height, int depth, PaletteData palette, - int scanlinePad, byte[] data, int maskPad, byte[] maskData, - byte[] alphaData, int alpha, int transparentPixel, int type, - int x, int y, int disposalMethod, int delayTime) + int width, int height, int depth, PaletteData palette, + int scanlinePad, byte[] data, int maskPad, byte[] maskData, + byte[] alphaData, int alpha, int transparentPixel, int type, + int x, int y, int disposalMethod, int delayTime) { - return new ImageData( - width, height, depth, palette, scanlinePad, data, maskPad, maskData, - alphaData, alpha, transparentPixel, type, x, y, disposalMethod, delayTime); + return new ImageData( + width, height, depth, palette, scanlinePad, data, maskPad, maskData, + alphaData, alpha, transparentPixel, type, x, y, disposalMethod, delayTime); } ImageData colorMaskImage(int pixel) { - ImageData mask = new ImageData(width, height, 1, bwPalette(), - 2, null, 0, null, null, -1, -1, SWT.IMAGE_UNDEFINED, - 0, 0, 0, 0); - int[] row = new int[width]; - for (int y = 0; y < height; y++) { - getPixels(0, y, width, row, 0); - for (int i = 0; i < width; i++) { - if (pixel != -1 && row[i] == pixel) { - row[i] = 0; - } else { - row[i] = 1; - } - } - mask.setPixels(0, y, width, row, 0); - } - return mask; + ImageData mask = new ImageData(width, height, 1, bwPalette(), + 2, null, 0, null, null, -1, -1, SWT.IMAGE_UNDEFINED, + 0, 0, 0, 0); + int[] row = new int[width]; + for (int y = 0; y < height; y++) { + getPixels(0, y, width, row, 0); + for (int i = 0; i < width; i++) { + if (pixel != -1 && row[i] == pixel) { + row[i] = 0; + } else { + row[i] = 1; + } + } + mask.setPixels(0, y, width, row, 0); + } + return mask; } static byte[] checkData(byte [] data) { - if (data == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return data; + if (data == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return data; } /** @@ -546,35 +546,35 @@ * @return a copy of the receiver. */ public Object clone() { - byte[] cloneData = new byte[data.length]; + byte[] cloneData = new byte[data.length]; System.arraycopy(data, 0, cloneData, 0, data.length); - byte[] cloneMaskData = null; - if (maskData != null) { + byte[] cloneMaskData = null; + if (maskData != null) { cloneMaskData = new byte[maskData.length]; System.arraycopy(maskData, 0, cloneMaskData, 0, maskData.length); - } - byte[] cloneAlphaData = null; - if (alphaData != null) { + } + byte[] cloneAlphaData = null; + if (alphaData != null) { cloneAlphaData = new byte[alphaData.length]; System.arraycopy(alphaData, 0, cloneAlphaData, 0, alphaData.length); - } - return new ImageData( - width, - height, - depth, - palette, - scanlinePad, - cloneData, - maskPad, - cloneMaskData, - cloneAlphaData, - alpha, - transparentPixel, - type, - x, - y, - disposalMethod, - delayTime); + } + return new ImageData( + width, + height, + depth, + palette, + scanlinePad, + cloneData, + maskPad, + cloneMaskData, + cloneAlphaData, + alpha, + transparentPixel, + type, + x, + y, + disposalMethod, + delayTime); } /** @@ -590,10 +590,10 @@ * */ public int getAlpha(int x, int y) { - if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (alphaData == null) return 255; - return alphaData[y * width + x] & 0xFF; + if (alphaData == null) return 255; + return alphaData[y * width + x] & 0xFF; } /** @@ -615,18 +615,18 @@ * */ public void getAlphas(int x, int y, int getWidth, byte[] alphas, int startIndex) { - if (alphas == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (getWidth == 0) return; + if (alphas == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (getWidth == 0) return; - if (alphaData == null) { - int endIndex = startIndex + getWidth; - for (int i = startIndex; i < endIndex; i++) { - alphas[i] = cast(byte)255; - } - return; - } - // may throw an IndexOutOfBoundsException + if (alphaData == null) { + int endIndex = startIndex + getWidth; + for (int i = startIndex; i < endIndex; i++) { + alphas[i] = cast(byte)255; + } + return; + } + // may throw an IndexOutOfBoundsException System.arraycopy(alphaData, y * width + x, alphas, startIndex, getWidth); } @@ -646,52 +646,52 @@ * */ public int getPixel(int x, int y) { - if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - int index; - int theByte; - int mask; - switch (depth) { - case 32: - index = (y * bytesPerLine) + (x * 4); - return ((data[index] & 0xFF) << 24) + ((data[index+1] & 0xFF) << 16) + - ((data[index+2] & 0xFF) << 8) + (data[index+3] & 0xFF); - case 24: - index = (y * bytesPerLine) + (x * 3); - return ((data[index] & 0xFF) << 16) + ((data[index+1] & 0xFF) << 8) + - (data[index+2] & 0xFF); - case 16: - index = (y * bytesPerLine) + (x * 2); - return ((data[index+1] & 0xFF) << 8) + (data[index] & 0xFF); - case 8: - index = (y * bytesPerLine) + x ; - return data[index] & 0xFF; - case 4: - index = (y * bytesPerLine) + (x >> 1); - theByte = data[index] & 0xFF; - if ((x & 0x1) == 0) { - return theByte >> 4; - } else { - return theByte & 0x0F; - } - case 2: - index = (y * bytesPerLine) + (x >> 2); - theByte = data[index] & 0xFF; - int offset = 3 - (x % 4); - mask = 3 << (offset * 2); - return (theByte & mask) >> (offset * 2); - case 1: - index = (y * bytesPerLine) + (x >> 3); - theByte = data[index] & 0xFF; - mask = 1 << (7 - (x & 0x7)); - if ((theByte & mask) == 0) { - return 0; - } else { - return 1; - } + if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int index; + int theByte; + int mask; + switch (depth) { + case 32: + index = (y * bytesPerLine) + (x * 4); + return ((data[index] & 0xFF) << 24) + ((data[index+1] & 0xFF) << 16) + + ((data[index+2] & 0xFF) << 8) + (data[index+3] & 0xFF); + case 24: + index = (y * bytesPerLine) + (x * 3); + return ((data[index] & 0xFF) << 16) + ((data[index+1] & 0xFF) << 8) + + (data[index+2] & 0xFF); + case 16: + index = (y * bytesPerLine) + (x * 2); + return ((data[index+1] & 0xFF) << 8) + (data[index] & 0xFF); + case 8: + index = (y * bytesPerLine) + x ; + return data[index] & 0xFF; + case 4: + index = (y * bytesPerLine) + (x >> 1); + theByte = data[index] & 0xFF; + if ((x & 0x1) == 0) { + return theByte >> 4; + } else { + return theByte & 0x0F; + } + case 2: + index = (y * bytesPerLine) + (x >> 2); + theByte = data[index] & 0xFF; + int offset = 3 - (x % 4); + mask = 3 << (offset * 2); + return (theByte & mask) >> (offset * 2); + case 1: + index = (y * bytesPerLine) + (x >> 3); + theByte = data[index] & 0xFF; + mask = 1 << (7 - (x & 0x7)); + if ((theByte & mask) == 0) { + return 0; + } else { + return 1; + } default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - return 0; + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + return 0; } /** @@ -717,129 +717,129 @@ * */ public void getPixels(int x, int y, int getWidth, byte[] pixels, int startIndex) { - if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (getWidth == 0) return; - int index; - int theByte; - int mask = 0; - int n = getWidth; - int i = startIndex; - int srcX = x, srcY = y; - switch (depth) { - case 8: - index = (y * bytesPerLine) + x; - for (int j = 0; j < getWidth; j++) { - pixels[i] = data[index]; - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - return; - case 4: - index = (y * bytesPerLine) + (x >> 1); - if ((x & 0x1) == 1) { - theByte = data[index] & 0xFF; - pixels[i] = cast(byte)(theByte & 0x0F); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - while (n > 1) { - theByte = data[index] & 0xFF; - pixels[i] = cast(byte)(theByte >> 4); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - pixels[i] = cast(byte)(theByte & 0x0F); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - } - if (n > 0) { - theByte = data[index] & 0xFF; - pixels[i] = cast(byte)(theByte >> 4); - } - return; - case 2: - index = (y * bytesPerLine) + (x >> 2); - theByte = data[index] & 0xFF; - int offset; - while (n > 0) { - offset = 3 - (srcX % 4); - mask = 3 << (offset * 2); - pixels[i] = cast(byte)((theByte & mask) >> (offset * 2)); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - if (n > 0) theByte = data[index] & 0xFF; - srcX = 0; - } else { - if (offset == 0) { - index++; - theByte = data[index] & 0xFF; - } - } - } - return; - case 1: - index = (y * bytesPerLine) + (x >> 3); - theByte = data[index] & 0xFF; - while (n > 0) { - mask = 1 << (7 - (srcX & 0x7)); - if ((theByte & mask) == 0) { - pixels[i] = 0; - } else { - pixels[i] = 1; - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - if (n > 0) theByte = data[index] & 0xFF; - srcX = 0; - } else { - if (mask == 1) { - index++; - if (n > 0) theByte = data[index] & 0xFF; - } - } - } - return; + if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (getWidth == 0) return; + int index; + int theByte; + int mask = 0; + int n = getWidth; + int i = startIndex; + int srcX = x, srcY = y; + switch (depth) { + case 8: + index = (y * bytesPerLine) + x; + for (int j = 0; j < getWidth; j++) { + pixels[i] = data[index]; + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + return; + case 4: + index = (y * bytesPerLine) + (x >> 1); + if ((x & 0x1) == 1) { + theByte = data[index] & 0xFF; + pixels[i] = cast(byte)(theByte & 0x0F); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + while (n > 1) { + theByte = data[index] & 0xFF; + pixels[i] = cast(byte)(theByte >> 4); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + pixels[i] = cast(byte)(theByte & 0x0F); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + } + if (n > 0) { + theByte = data[index] & 0xFF; + pixels[i] = cast(byte)(theByte >> 4); + } + return; + case 2: + index = (y * bytesPerLine) + (x >> 2); + theByte = data[index] & 0xFF; + int offset; + while (n > 0) { + offset = 3 - (srcX % 4); + mask = 3 << (offset * 2); + pixels[i] = cast(byte)((theByte & mask) >> (offset * 2)); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + if (n > 0) theByte = data[index] & 0xFF; + srcX = 0; + } else { + if (offset == 0) { + index++; + theByte = data[index] & 0xFF; + } + } + } + return; + case 1: + index = (y * bytesPerLine) + (x >> 3); + theByte = data[index] & 0xFF; + while (n > 0) { + mask = 1 << (7 - (srcX & 0x7)); + if ((theByte & mask) == 0) { + pixels[i] = 0; + } else { + pixels[i] = 1; + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + if (n > 0) theByte = data[index] & 0xFF; + srcX = 0; + } else { + if (mask == 1) { + index++; + if (n > 0) theByte = data[index] & 0xFF; + } + } + } + return; default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); } /** @@ -864,177 +864,177 @@ * */ public void getPixels(int x, int y, int getWidth, int[] pixels, int startIndex) { - if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (getWidth == 0) return; - int index; - int theByte; - int mask; - int n = getWidth; - int i = startIndex; - int srcX = x, srcY = y; - switch (depth) { - case 32: - index = (y * bytesPerLine) + (x * 4); - i = startIndex; - for (int j = 0; j < getWidth; j++) { - pixels[i] = ((data[index] & 0xFF) << 24) | ((data[index+1] & 0xFF) << 16) - | ((data[index+2] & 0xFF) << 8) | (data[index+3] & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 4; - } - } - return; - case 24: - index = (y * bytesPerLine) + (x * 3); - for (int j = 0; j < getWidth; j++) { - pixels[i] = ((data[index] & 0xFF) << 16) | ((data[index+1] & 0xFF) << 8) - | (data[index+2] & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 3; - } - } - return; - case 16: - index = (y * bytesPerLine) + (x * 2); - for (int j = 0; j < getWidth; j++) { - pixels[i] = ((data[index+1] & 0xFF) << 8) + (data[index] & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 2; - } - } - return; - case 8: - index = (y * bytesPerLine) + x; - for (int j = 0; j < getWidth; j++) { - pixels[i] = data[index] & 0xFF; - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - return; - case 4: - index = (y * bytesPerLine) + (x >> 1); - if ((x & 0x1) == 1) { - theByte = data[index] & 0xFF; - pixels[i] = theByte & 0x0F; - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - while (n > 1) { - theByte = data[index] & 0xFF; - pixels[i] = theByte >> 4; - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - pixels[i] = theByte & 0x0F; - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - } - if (n > 0) { - theByte = data[index] & 0xFF; - pixels[i] = theByte >> 4; - } - return; - case 2: - index = (y * bytesPerLine) + (x >> 2); - theByte = data[index] & 0xFF; - int offset; - while (n > 0) { - offset = 3 - (srcX % 4); - mask = 3 << (offset * 2); - pixels[i] = cast(byte)((theByte & mask) >> (offset * 2)); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - if (n > 0) theByte = data[index] & 0xFF; - srcX = 0; - } else { - if (offset == 0) { - index++; - theByte = data[index] & 0xFF; - } - } - } - return; - case 1: - index = (y * bytesPerLine) + (x >> 3); - theByte = data[index] & 0xFF; - while (n > 0) { - mask = 1 << (7 - (srcX & 0x7)); - if ((theByte & mask) == 0) { - pixels[i] = 0; - } else { - pixels[i] = 1; - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - if (n > 0) theByte = data[index] & 0xFF; - srcX = 0; - } else { - if (mask == 1) { - index++; - if (n > 0) theByte = data[index] & 0xFF; - } - } - } - return; + if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (getWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (getWidth == 0) return; + int index; + int theByte; + int mask; + int n = getWidth; + int i = startIndex; + int srcX = x, srcY = y; + switch (depth) { + case 32: + index = (y * bytesPerLine) + (x * 4); + i = startIndex; + for (int j = 0; j < getWidth; j++) { + pixels[i] = ((data[index] & 0xFF) << 24) | ((data[index+1] & 0xFF) << 16) + | ((data[index+2] & 0xFF) << 8) | (data[index+3] & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 4; + } + } + return; + case 24: + index = (y * bytesPerLine) + (x * 3); + for (int j = 0; j < getWidth; j++) { + pixels[i] = ((data[index] & 0xFF) << 16) | ((data[index+1] & 0xFF) << 8) + | (data[index+2] & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 3; + } + } + return; + case 16: + index = (y * bytesPerLine) + (x * 2); + for (int j = 0; j < getWidth; j++) { + pixels[i] = ((data[index+1] & 0xFF) << 8) + (data[index] & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 2; + } + } + return; + case 8: + index = (y * bytesPerLine) + x; + for (int j = 0; j < getWidth; j++) { + pixels[i] = data[index] & 0xFF; + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + return; + case 4: + index = (y * bytesPerLine) + (x >> 1); + if ((x & 0x1) == 1) { + theByte = data[index] & 0xFF; + pixels[i] = theByte & 0x0F; + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + while (n > 1) { + theByte = data[index] & 0xFF; + pixels[i] = theByte >> 4; + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + pixels[i] = theByte & 0x0F; + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + } + if (n > 0) { + theByte = data[index] & 0xFF; + pixels[i] = theByte >> 4; + } + return; + case 2: + index = (y * bytesPerLine) + (x >> 2); + theByte = data[index] & 0xFF; + int offset; + while (n > 0) { + offset = 3 - (srcX % 4); + mask = 3 << (offset * 2); + pixels[i] = cast(byte)((theByte & mask) >> (offset * 2)); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + if (n > 0) theByte = data[index] & 0xFF; + srcX = 0; + } else { + if (offset == 0) { + index++; + theByte = data[index] & 0xFF; + } + } + } + return; + case 1: + index = (y * bytesPerLine) + (x >> 3); + theByte = data[index] & 0xFF; + while (n > 0) { + mask = 1 << (7 - (srcX & 0x7)); + if ((theByte & mask) == 0) { + pixels[i] = 0; + } else { + pixels[i] = 1; + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + if (n > 0) theByte = data[index] & 0xFF; + srcX = 0; + } else { + if (mask == 1) { + index++; + if (n > 0) theByte = data[index] & 0xFF; + } + } + } + return; default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); } /** @@ -1047,7 +1047,7 @@ * @see PaletteData#getRGBs() */ public RGB[] getRGBs() { - return palette.getRGBs(); + return palette.getRGBs(); } /** @@ -1059,11 +1059,11 @@ * @return the transparency mask */ public ImageData getTransparencyMask() { - if (getTransparencyType() == SWT.TRANSPARENCY_MASK) { - return new ImageData(width, height, 1, bwPalette(), maskPad, maskData); - } else { - return colorMaskImage(transparentPixel); - } + if (getTransparencyType() == SWT.TRANSPARENCY_MASK) { + return new ImageData(width, height, 1, bwPalette(), maskPad, maskData); + } else { + return colorMaskImage(transparentPixel); + } } /** @@ -1074,10 +1074,10 @@ * @return the receiver's transparency type */ public int getTransparencyType() { - if (maskData != null) return SWT.TRANSPARENCY_MASK; - if (transparentPixel != -1) return SWT.TRANSPARENCY_PIXEL; - if (alphaData != null) return SWT.TRANSPARENCY_ALPHA; - return SWT.TRANSPARENCY_NONE; + if (maskData != null) return SWT.TRANSPARENCY_MASK; + if (transparentPixel != -1) return SWT.TRANSPARENCY_PIXEL; + if (alphaData != null) return SWT.TRANSPARENCY_ALPHA; + return SWT.TRANSPARENCY_NONE; } /** @@ -1086,7 +1086,7 @@ * @return MSB_FIRST or LSB_FIRST */ int getByteOrder() { - return depth != 16 ? MSB_FIRST : LSB_FIRST; + return depth != 16 ? MSB_FIRST : LSB_FIRST; } /** @@ -1100,54 +1100,54 @@ * @return a scaled copy of the image */ public ImageData scaledTo(int width, int height) { - /* Create a destination image with no data */ - bool flipX = (width < 0); - if (flipX) width = - width; - bool flipY = (height < 0); - if (flipY) height = - height; + /* Create a destination image with no data */ + bool flipX = (width < 0); + if (flipX) width = - width; + bool flipY = (height < 0); + if (flipY) height = - height; - ImageData dest = new ImageData( - width, height, depth, palette, - scanlinePad, null, 0, null, - null, -1, transparentPixel, type, - x, y, disposalMethod, delayTime); + ImageData dest = new ImageData( + width, height, depth, palette, + scanlinePad, null, 0, null, + null, -1, transparentPixel, type, + x, y, disposalMethod, delayTime); - /* Scale the image contents */ - if (palette.isDirect) blit(BLIT_SRC, - this.data, this.depth, this.bytesPerLine, this.getByteOrder(), 0, 0, this.width, this.height, 0, 0, 0, - ALPHA_OPAQUE, null, 0, 0, 0, - dest.data, dest.depth, dest.bytesPerLine, dest.getByteOrder(), 0, 0, dest.width, dest.height, 0, 0, 0, - flipX, flipY); - else blit(BLIT_SRC, - this.data, this.depth, this.bytesPerLine, this.getByteOrder(), 0, 0, this.width, this.height, null, null, null, - ALPHA_OPAQUE, null, 0, 0, 0, - dest.data, dest.depth, dest.bytesPerLine, dest.getByteOrder(), 0, 0, dest.width, dest.height, null, null, null, - flipX, flipY); + /* Scale the image contents */ + if (palette.isDirect) blit(BLIT_SRC, + this.data, this.depth, this.bytesPerLine, this.getByteOrder(), 0, 0, this.width, this.height, 0, 0, 0, + ALPHA_OPAQUE, null, 0, 0, 0, + dest.data, dest.depth, dest.bytesPerLine, dest.getByteOrder(), 0, 0, dest.width, dest.height, 0, 0, 0, + flipX, flipY); + else blit(BLIT_SRC, + this.data, this.depth, this.bytesPerLine, this.getByteOrder(), 0, 0, this.width, this.height, null, null, null, + ALPHA_OPAQUE, null, 0, 0, 0, + dest.data, dest.depth, dest.bytesPerLine, dest.getByteOrder(), 0, 0, dest.width, dest.height, null, null, null, + flipX, flipY); - /* Scale the image mask or alpha */ - if (maskData != null) { - dest.maskPad = this.maskPad; - int destBpl = (dest.width + 7) / 8; - destBpl = (destBpl + (dest.maskPad - 1)) / dest.maskPad * dest.maskPad; - dest.maskData = new byte[destBpl * dest.height]; - int srcBpl = (this.width + 7) / 8; - srcBpl = (srcBpl + (this.maskPad - 1)) / this.maskPad * this.maskPad; - blit(BLIT_SRC, - this.maskData, 1, srcBpl, MSB_FIRST, 0, 0, this.width, this.height, null, null, null, - ALPHA_OPAQUE, null, 0, 0, 0, - dest.maskData, 1, destBpl, MSB_FIRST, 0, 0, dest.width, dest.height, null, null, null, - flipX, flipY); - } else if (alpha != -1) { - dest.alpha = this.alpha; - } else if (alphaData != null) { - dest.alphaData = new byte[dest.width * dest.height]; - blit(BLIT_SRC, - this.alphaData, 8, this.width, MSB_FIRST, 0, 0, this.width, this.height, null, null, null, - ALPHA_OPAQUE, null, 0, 0, 0, - dest.alphaData, 8, dest.width, MSB_FIRST, 0, 0, dest.width, dest.height, null, null, null, - flipX, flipY); - } - return dest; + /* Scale the image mask or alpha */ + if (maskData != null) { + dest.maskPad = this.maskPad; + int destBpl = (dest.width + 7) / 8; + destBpl = (destBpl + (dest.maskPad - 1)) / dest.maskPad * dest.maskPad; + dest.maskData = new byte[destBpl * dest.height]; + int srcBpl = (this.width + 7) / 8; + srcBpl = (srcBpl + (this.maskPad - 1)) / this.maskPad * this.maskPad; + blit(BLIT_SRC, + this.maskData, 1, srcBpl, MSB_FIRST, 0, 0, this.width, this.height, null, null, null, + ALPHA_OPAQUE, null, 0, 0, 0, + dest.maskData, 1, destBpl, MSB_FIRST, 0, 0, dest.width, dest.height, null, null, null, + flipX, flipY); + } else if (alpha != -1) { + dest.alpha = this.alpha; + } else if (alphaData != null) { + dest.alphaData = new byte[dest.width * dest.height]; + blit(BLIT_SRC, + this.alphaData, 8, this.width, MSB_FIRST, 0, 0, this.width, this.height, null, null, null, + ALPHA_OPAQUE, null, 0, 0, 0, + dest.alphaData, 8, dest.width, MSB_FIRST, 0, 0, dest.width, dest.height, null, null, null, + flipX, flipY); + } + return dest; } /** @@ -1163,11 +1163,11 @@ * */ public void setAlpha(int x, int y, int alpha) { - if (x >= width || y >= height || x < 0 || y < 0 || alpha < 0 || alpha > 255) - SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (x >= width || y >= height || x < 0 || y < 0 || alpha < 0 || alpha > 255) + SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (alphaData == null) alphaData = new byte[width * height]; - alphaData[y * width + x] = cast(byte)alpha; + if (alphaData == null) alphaData = new byte[width * height]; + alphaData[y * width + x] = cast(byte)alpha; } /** @@ -1190,12 +1190,12 @@ * */ public void setAlphas(int x, int y, int putWidth, byte[] alphas, int startIndex) { - if (alphas == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (putWidth == 0) return; + if (alphas == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (putWidth == 0) return; - if (alphaData == null) alphaData = new byte[width * height]; - // may throw an IndexOutOfBoundsException + if (alphaData == null) alphaData = new byte[width * height]; + // may throw an IndexOutOfBoundsException System.arraycopy(alphas, startIndex, alphaData, y * width + x, putWidth); } @@ -1215,61 +1215,61 @@ * */ public void setPixel(int x, int y, int pixelValue) { - if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - int index; - byte theByte; - int mask; - switch (depth) { - case 32: - index = (y * bytesPerLine) + (x * 4); - data[index] = cast(byte)((pixelValue >> 24) & 0xFF); - data[index + 1] = cast(byte)((pixelValue >> 16) & 0xFF); - data[index + 2] = cast(byte)((pixelValue >> 8) & 0xFF); - data[index + 3] = cast(byte)(pixelValue & 0xFF); - return; - case 24: - index = (y * bytesPerLine) + (x * 3); - data[index] = cast(byte)((pixelValue >> 16) & 0xFF); - data[index + 1] = cast(byte)((pixelValue >> 8) & 0xFF); - data[index + 2] = cast(byte)(pixelValue & 0xFF); - return; - case 16: - index = (y * bytesPerLine) + (x * 2); - data[index + 1] = cast(byte)((pixelValue >> 8) & 0xFF); - data[index] = cast(byte)(pixelValue & 0xFF); - return; - case 8: - index = (y * bytesPerLine) + x ; - data[index] = cast(byte)(pixelValue & 0xFF); - return; - case 4: - index = (y * bytesPerLine) + (x >> 1); - if ((x & 0x1) == 0) { - data[index] = cast(byte)((data[index] & 0x0F) | ((pixelValue & 0x0F) << 4)); - } else { - data[index] = cast(byte)((data[index] & 0xF0) | (pixelValue & 0x0F)); - } - return; - case 2: - index = (y * bytesPerLine) + (x >> 2); - theByte = data[index]; - int offset = 3 - (x % 4); - mask = 0xFF ^ (3 << (offset * 2)); - data[index] = cast(byte)((data[index] & mask) | (pixelValue << (offset * 2))); - return; - case 1: - index = (y * bytesPerLine) + (x >> 3); - theByte = data[index]; - mask = 1 << (7 - (x & 0x7)); - if ((pixelValue & 0x1) == 1) { - data[index] = cast(byte)(theByte | mask); - } else { - data[index] = cast(byte)(theByte & (mask ^ -1)); - } - return; + if (x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + int index; + byte theByte; + int mask; + switch (depth) { + case 32: + index = (y * bytesPerLine) + (x * 4); + data[index] = cast(byte)((pixelValue >> 24) & 0xFF); + data[index + 1] = cast(byte)((pixelValue >> 16) & 0xFF); + data[index + 2] = cast(byte)((pixelValue >> 8) & 0xFF); + data[index + 3] = cast(byte)(pixelValue & 0xFF); + return; + case 24: + index = (y * bytesPerLine) + (x * 3); + data[index] = cast(byte)((pixelValue >> 16) & 0xFF); + data[index + 1] = cast(byte)((pixelValue >> 8) & 0xFF); + data[index + 2] = cast(byte)(pixelValue & 0xFF); + return; + case 16: + index = (y * bytesPerLine) + (x * 2); + data[index + 1] = cast(byte)((pixelValue >> 8) & 0xFF); + data[index] = cast(byte)(pixelValue & 0xFF); + return; + case 8: + index = (y * bytesPerLine) + x ; + data[index] = cast(byte)(pixelValue & 0xFF); + return; + case 4: + index = (y * bytesPerLine) + (x >> 1); + if ((x & 0x1) == 0) { + data[index] = cast(byte)((data[index] & 0x0F) | ((pixelValue & 0x0F) << 4)); + } else { + data[index] = cast(byte)((data[index] & 0xF0) | (pixelValue & 0x0F)); + } + return; + case 2: + index = (y * bytesPerLine) + (x >> 2); + theByte = data[index]; + int offset = 3 - (x % 4); + mask = 0xFF ^ (3 << (offset * 2)); + data[index] = cast(byte)((data[index] & mask) | (pixelValue << (offset * 2))); + return; + case 1: + index = (y * bytesPerLine) + (x >> 3); + theByte = data[index]; + mask = 1 << (7 - (x & 0x7)); + if ((pixelValue & 0x1) == 1) { + data[index] = cast(byte)(theByte | mask); + } else { + data[index] = cast(byte)(theByte & (mask ^ -1)); + } + return; default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); } /** @@ -1296,106 +1296,106 @@ * */ public void setPixels(int x, int y, int putWidth, byte[] pixels, int startIndex) { - if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (putWidth == 0) return; - int index; - int theByte; - int mask; - int n = putWidth; - int i = startIndex; - int srcX = x, srcY = y; - switch (depth) { - case 8: - index = (y * bytesPerLine) + x; - for (int j = 0; j < putWidth; j++) { - data[index] = cast(byte)(pixels[i] & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - return; - case 4: - index = (y * bytesPerLine) + (x >> 1); - bool high = (x & 0x1) == 0; - while (n > 0) { - theByte = pixels[i] & 0x0F; - if (high) { - data[index] = cast(byte)((data[index] & 0x0F) | (theByte << 4)); - } else { - data[index] = cast(byte)((data[index] & 0xF0) | theByte); - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - high = true; - srcX = 0; - } else { - if (!high) index++; - high = !high; - } - } - return; - case 2: - byte [] masks = [ cast(byte)0xFC, cast(byte)0xF3, cast(byte)0xCF, cast(byte)0x3F ]; - index = (y * bytesPerLine) + (x >> 2); - int offset = 3 - (x % 4); - while (n > 0) { - theByte = pixels[i] & 0x3; - data[index] = cast(byte)((data[index] & masks[offset]) | (theByte << (offset * 2))); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - offset = 0; - srcX = 0; - } else { - if (offset == 0) { - index++; - offset = 3; - } else { - offset--; - } - } - } - return; - case 1: - index = (y * bytesPerLine) + (x >> 3); - while (n > 0) { - mask = 1 << (7 - (srcX & 0x7)); - if ((pixels[i] & 0x1) == 1) { - data[index] = cast(byte)((data[index] & 0xFF) | mask); - } else { - data[index] = cast(byte)((data[index] & 0xFF) & (mask ^ -1)); - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - if (mask == 1) { - index++; - } - } - } - return; + if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (putWidth == 0) return; + int index; + int theByte; + int mask; + int n = putWidth; + int i = startIndex; + int srcX = x, srcY = y; + switch (depth) { + case 8: + index = (y * bytesPerLine) + x; + for (int j = 0; j < putWidth; j++) { + data[index] = cast(byte)(pixels[i] & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + return; + case 4: + index = (y * bytesPerLine) + (x >> 1); + bool high = (x & 0x1) == 0; + while (n > 0) { + theByte = pixels[i] & 0x0F; + if (high) { + data[index] = cast(byte)((data[index] & 0x0F) | (theByte << 4)); + } else { + data[index] = cast(byte)((data[index] & 0xF0) | theByte); + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + high = true; + srcX = 0; + } else { + if (!high) index++; + high = !high; + } + } + return; + case 2: + byte [] masks = [ cast(byte)0xFC, cast(byte)0xF3, cast(byte)0xCF, cast(byte)0x3F ]; + index = (y * bytesPerLine) + (x >> 2); + int offset = 3 - (x % 4); + while (n > 0) { + theByte = pixels[i] & 0x3; + data[index] = cast(byte)((data[index] & masks[offset]) | (theByte << (offset * 2))); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + offset = 0; + srcX = 0; + } else { + if (offset == 0) { + index++; + offset = 3; + } else { + offset--; + } + } + } + return; + case 1: + index = (y * bytesPerLine) + (x >> 3); + while (n > 0) { + mask = 1 << (7 - (srcX & 0x7)); + if ((pixels[i] & 0x1) == 1) { + data[index] = cast(byte)((data[index] & 0xFF) | mask); + } else { + data[index] = cast(byte)((data[index] & 0xFF) & (mask ^ -1)); + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + if (mask == 1) { + index++; + } + } + } + return; default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); } /** @@ -1421,168 +1421,168 @@ * */ public void setPixels(int x, int y, int putWidth, int[] pixels, int startIndex) { - if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (putWidth == 0) return; - int index; - int theByte; - int mask; - int n = putWidth; - int i = startIndex; - int pixel; - int srcX = x, srcY = y; - switch (depth) { - case 32: - index = (y * bytesPerLine) + (x * 4); - for (int j = 0; j < putWidth; j++) { - pixel = pixels[i]; - data[index] = cast(byte)((pixel >> 24) & 0xFF); - data[index + 1] = cast(byte)((pixel >> 16) & 0xFF); - data[index + 2] = cast(byte)((pixel >> 8) & 0xFF); - data[index + 3] = cast(byte)(pixel & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 4; - } - } - return; - case 24: - index = (y * bytesPerLine) + (x * 3); - for (int j = 0; j < putWidth; j++) { - pixel = pixels[i]; - data[index] = cast(byte)((pixel >> 16) & 0xFF); - data[index + 1] = cast(byte)((pixel >> 8) & 0xFF); - data[index + 2] = cast(byte)(pixel & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 3; - } - } - return; - case 16: - index = (y * bytesPerLine) + (x * 2); - for (int j = 0; j < putWidth; j++) { - pixel = pixels[i]; - data[index] = cast(byte)(pixel & 0xFF); - data[index + 1] = cast(byte)((pixel >> 8) & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index += 2; - } - } - return; - case 8: - index = (y * bytesPerLine) + x; - for (int j = 0; j < putWidth; j++) { - data[index] = cast(byte)(pixels[i] & 0xFF); - i++; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - index++; - } - } - return; - case 4: - index = (y * bytesPerLine) + (x >> 1); - bool high = (x & 0x1) == 0; - while (n > 0) { - theByte = pixels[i] & 0x0F; - if (high) { - data[index] = cast(byte)((data[index] & 0x0F) | (theByte << 4)); - } else { - data[index] = cast(byte)((data[index] & 0xF0) | theByte); - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - high = true; - srcX = 0; - } else { - if (!high) index++; - high = !high; - } - } - return; - case 2: - byte [] masks = [ cast(byte)0xFC, cast(byte)0xF3, cast(byte)0xCF, cast(byte)0x3F ]; - index = (y * bytesPerLine) + (x >> 2); - int offset = 3 - (x % 4); - while (n > 0) { - theByte = pixels[i] & 0x3; - data[index] = cast(byte)((data[index] & masks[offset]) | (theByte << (offset * 2))); - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - offset = 3; - srcX = 0; - } else { - if (offset == 0) { - index++; - offset = 3; - } else { - offset--; - } - } - } - return; - case 1: - index = (y * bytesPerLine) + (x >> 3); - while (n > 0) { - mask = 1 << (7 - (srcX & 0x7)); - if ((pixels[i] & 0x1) == 1) { - data[index] = cast(byte)((data[index] & 0xFF) | mask); - } else { - data[index] = cast(byte)((data[index] & 0xFF) & (mask ^ -1)); - } - i++; - n--; - srcX++; - if (srcX >= width) { - srcY++; - index = srcY * bytesPerLine; - srcX = 0; - } else { - if (mask == 1) { - index++; - } - } - } - return; + if (pixels == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (putWidth < 0 || x >= width || y >= height || x < 0 || y < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (putWidth == 0) return; + int index; + int theByte; + int mask; + int n = putWidth; + int i = startIndex; + int pixel; + int srcX = x, srcY = y; + switch (depth) { + case 32: + index = (y * bytesPerLine) + (x * 4); + for (int j = 0; j < putWidth; j++) { + pixel = pixels[i]; + data[index] = cast(byte)((pixel >> 24) & 0xFF); + data[index + 1] = cast(byte)((pixel >> 16) & 0xFF); + data[index + 2] = cast(byte)((pixel >> 8) & 0xFF); + data[index + 3] = cast(byte)(pixel & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 4; + } + } + return; + case 24: + index = (y * bytesPerLine) + (x * 3); + for (int j = 0; j < putWidth; j++) { + pixel = pixels[i]; + data[index] = cast(byte)((pixel >> 16) & 0xFF); + data[index + 1] = cast(byte)((pixel >> 8) & 0xFF); + data[index + 2] = cast(byte)(pixel & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 3; + } + } + return; + case 16: + index = (y * bytesPerLine) + (x * 2); + for (int j = 0; j < putWidth; j++) { + pixel = pixels[i]; + data[index] = cast(byte)(pixel & 0xFF); + data[index + 1] = cast(byte)((pixel >> 8) & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index += 2; + } + } + return; + case 8: + index = (y * bytesPerLine) + x; + for (int j = 0; j < putWidth; j++) { + data[index] = cast(byte)(pixels[i] & 0xFF); + i++; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + index++; + } + } + return; + case 4: + index = (y * bytesPerLine) + (x >> 1); + bool high = (x & 0x1) == 0; + while (n > 0) { + theByte = pixels[i] & 0x0F; + if (high) { + data[index] = cast(byte)((data[index] & 0x0F) | (theByte << 4)); + } else { + data[index] = cast(byte)((data[index] & 0xF0) | theByte); + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + high = true; + srcX = 0; + } else { + if (!high) index++; + high = !high; + } + } + return; + case 2: + byte [] masks = [ cast(byte)0xFC, cast(byte)0xF3, cast(byte)0xCF, cast(byte)0x3F ]; + index = (y * bytesPerLine) + (x >> 2); + int offset = 3 - (x % 4); + while (n > 0) { + theByte = pixels[i] & 0x3; + data[index] = cast(byte)((data[index] & masks[offset]) | (theByte << (offset * 2))); + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + offset = 3; + srcX = 0; + } else { + if (offset == 0) { + index++; + offset = 3; + } else { + offset--; + } + } + } + return; + case 1: + index = (y * bytesPerLine) + (x >> 3); + while (n > 0) { + mask = 1 << (7 - (srcX & 0x7)); + if ((pixels[i] & 0x1) == 1) { + data[index] = cast(byte)((data[index] & 0xFF) | mask); + } else { + data[index] = cast(byte)((data[index] & 0xFF) & (mask ^ -1)); + } + i++; + n--; + srcX++; + if (srcX >= width) { + srcY++; + index = srcY * bytesPerLine; + srcX = 0; + } else { + if (mask == 1) { + index++; + } + } + } + return; default: - } - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); } /** * Returns a palette with 2 colors: black & white. */ static PaletteData bwPalette() { - return new PaletteData( [ new RGB(0, 0, 0), new RGB(255, 255, 255) ] ); + return new PaletteData( [ new RGB(0, 0, 0), new RGB(255, 255, 255) ] ); } /** @@ -1590,105 +1590,105 @@ * the given mask. */ static int getMSBOffset(int mask) { - for (int i = 31; i >= 0; i--) { - if (((mask >> i) & 0x1) != 0) return i + 1; - } - return 0; + for (int i = 31; i >= 0; i--) { + if (((mask >> i) & 0x1) != 0) return i + 1; + } + return 0; } /** * Finds the closest match. */ static int closestMatch(int depth, byte red, byte green, byte blue, int redMask, int greenMask, int blueMask, byte[] reds, byte[] greens, byte[] blues) { - if (depth > 8) { - int rshift = 32 - getMSBOffset(redMask); - int gshift = 32 - getMSBOffset(greenMask); - int bshift = 32 - getMSBOffset(blueMask); - return (((red << 24) >>> rshift) & redMask) | - (((green << 24) >>> gshift) & greenMask) | - (((blue << 24) >>> bshift) & blueMask); - } - int r, g, b; - int minDistance = 0x7fffffff; - int nearestPixel = 0; - int n = reds.length; - for (int j = 0; j < n; j++) { - r = (reds[j] & 0xFF) - (red & 0xFF); - g = (greens[j] & 0xFF) - (green & 0xFF); - b = (blues[j] & 0xFF) - (blue & 0xFF); - int distance = r*r + g*g + b*b; - if (distance < minDistance) { - nearestPixel = j; - if (distance == 0) break; - minDistance = distance; - } - } - return nearestPixel; + if (depth > 8) { + int rshift = 32 - getMSBOffset(redMask); + int gshift = 32 - getMSBOffset(greenMask); + int bshift = 32 - getMSBOffset(blueMask); + return (((red << 24) >>> rshift) & redMask) | + (((green << 24) >>> gshift) & greenMask) | + (((blue << 24) >>> bshift) & blueMask); + } + int r, g, b; + int minDistance = 0x7fffffff; + int nearestPixel = 0; + int n = reds.length; + for (int j = 0; j < n; j++) { + r = (reds[j] & 0xFF) - (red & 0xFF); + g = (greens[j] & 0xFF) - (green & 0xFF); + b = (blues[j] & 0xFF) - (blue & 0xFF); + int distance = r*r + g*g + b*b; + if (distance < minDistance) { + nearestPixel = j; + if (distance == 0) break; + minDistance = distance; + } + } + return nearestPixel; } static final ImageData convertMask(ImageData mask) { - if (mask.depth == 1) return mask; - PaletteData palette = new PaletteData([new RGB(0, 0, 0), new RGB(255,255,255)]); - ImageData newMask = new ImageData(mask.width, mask.height, 1, palette); - /* Find index of black in mask palette */ - int blackIndex = 0; - RGB[] rgbs = mask.getRGBs(); - if (rgbs != null) { - while (blackIndex < rgbs.length) { - if (rgbs[blackIndex] == palette.colors[0] ) break; - blackIndex++; - } - } - int[] pixels = new int[mask.width]; - for (int y = 0; y < mask.height; y++) { - mask.getPixels(0, y, mask.width, pixels, 0); - for (int i = 0; i < pixels.length; i++) { - if (pixels[i] == blackIndex) { - pixels[i] = 0; - } else { - pixels[i] = 1; - } - } - newMask.setPixels(0, y, mask.width, pixels, 0); - } - return newMask; + if (mask.depth == 1) return mask; + PaletteData palette = new PaletteData([new RGB(0, 0, 0), new RGB(255,255,255)]); + ImageData newMask = new ImageData(mask.width, mask.height, 1, palette); + /* Find index of black in mask palette */ + int blackIndex = 0; + RGB[] rgbs = mask.getRGBs(); + if (rgbs != null) { + while (blackIndex < rgbs.length) { + if (rgbs[blackIndex] == palette.colors[0] ) break; + blackIndex++; + } + } + int[] pixels = new int[mask.width]; + for (int y = 0; y < mask.height; y++) { + mask.getPixels(0, y, mask.width, pixels, 0); + for (int i = 0; i < pixels.length; i++) { + if (pixels[i] == blackIndex) { + pixels[i] = 0; + } else { + pixels[i] = 1; + } + } + newMask.setPixels(0, y, mask.width, pixels, 0); + } + return newMask; } static final byte[] convertPad(byte[] data, int width, int height, int depth, int pad, int newPad) { - if (pad == newPad) return data; - int stride = (width * depth + 7) / 8; - int bpl = (stride + (pad - 1)) / pad * pad; - int newBpl = (stride + (newPad - 1)) / newPad * newPad; - byte[] newData = new byte[height * newBpl]; - int srcIndex = 0, destIndex = 0; - for (int y = 0; y < height; y++) { + if (pad == newPad) return data; + int stride = (width * depth + 7) / 8; + int bpl = (stride + (pad - 1)) / pad * pad; + int newBpl = (stride + (newPad - 1)) / newPad * newPad; + byte[] newData = new byte[height * newBpl]; + int srcIndex = 0, destIndex = 0; + for (int y = 0; y < height; y++) { System.arraycopy(data, srcIndex, newData, destIndex, stride); - srcIndex += bpl; - destIndex += newBpl; - } - return newData; + srcIndex += bpl; + destIndex += newBpl; + } + return newData; } /** * Blit operation bits to be OR'ed together to specify the desired operation. */ static const int - BLIT_SRC = 1, // copy source directly, else applies logic operations - BLIT_ALPHA = 2, // enable alpha blending - BLIT_DITHER = 4; // enable dithering in low color modes + BLIT_SRC = 1, // copy source directly, else applies logic operations + BLIT_ALPHA = 2, // enable alpha blending + BLIT_DITHER = 4; // enable dithering in low color modes /** * Alpha mode, values 0 - 255 specify global alpha level */ static const int - ALPHA_OPAQUE = 255, // Fully opaque (ignores any alpha data) - ALPHA_TRANSPARENT = 0, // Fully transparent (ignores any alpha data) - ALPHA_CHANNEL_SEPARATE = -1, // Use alpha channel from separate alphaData - ALPHA_CHANNEL_SOURCE = -2, // Use alpha channel embedded in sourceData - ALPHA_MASK_UNPACKED = -3, // Use transparency mask formed by bytes in alphaData (non-zero is opaque) - ALPHA_MASK_PACKED = -4, // Use transparency mask formed by packed bits in alphaData - ALPHA_MASK_INDEX = -5, // Consider source palette indices transparent if in alphaData array - ALPHA_MASK_RGB = -6; // Consider source RGBs transparent if in RGB888 format alphaData array + ALPHA_OPAQUE = 255, // Fully opaque (ignores any alpha data) + ALPHA_TRANSPARENT = 0, // Fully transparent (ignores any alpha data) + ALPHA_CHANNEL_SEPARATE = -1, // Use alpha channel from separate alphaData + ALPHA_CHANNEL_SOURCE = -2, // Use alpha channel embedded in sourceData + ALPHA_MASK_UNPACKED = -3, // Use transparency mask formed by bytes in alphaData (non-zero is opaque) + ALPHA_MASK_PACKED = -4, // Use transparency mask formed by packed bits in alphaData + ALPHA_MASK_INDEX = -5, // Consider source palette indices transparent if in alphaData array + ALPHA_MASK_RGB = -6; // Consider source RGBs transparent if in RGB888 format alphaData array /** * Byte and bit order constants. @@ -1700,19 +1700,19 @@ * Data types (internal) */ private static const int - // direct / true color formats with arbitrary masks & shifts - TYPE_GENERIC_8 = 0, - TYPE_GENERIC_16_MSB = 1, - TYPE_GENERIC_16_LSB = 2, - TYPE_GENERIC_24 = 3, - TYPE_GENERIC_32_MSB = 4, - TYPE_GENERIC_32_LSB = 5, - // palette indexed color formats - TYPE_INDEX_8 = 6, - TYPE_INDEX_4 = 7, - TYPE_INDEX_2 = 8, - TYPE_INDEX_1_MSB = 9, - TYPE_INDEX_1_LSB = 10; + // direct / true color formats with arbitrary masks & shifts + TYPE_GENERIC_8 = 0, + TYPE_GENERIC_16_MSB = 1, + TYPE_GENERIC_16_LSB = 2, + TYPE_GENERIC_24 = 3, + TYPE_GENERIC_32_MSB = 4, + TYPE_GENERIC_32_LSB = 5, + // palette indexed color formats + TYPE_INDEX_8 = 6, + TYPE_INDEX_4 = 7, + TYPE_INDEX_2 = 8, + TYPE_INDEX_1_MSB = 9, + TYPE_INDEX_1_LSB = 10; /** * Blits a direct palette image into a direct palette image. @@ -1762,387 +1762,387 @@ * @param flipY if true the resulting image is flipped along the horizontal axis */ static void blit(int op, - byte[] srcData, int srcDepth, int srcStride, int srcOrder, - int srcX, int srcY, int srcWidth, int srcHeight, - int srcRedMask, int srcGreenMask, int srcBlueMask, - int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, - byte[] destData, int destDepth, int destStride, int destOrder, - int destX, int destY, int destWidth, int destHeight, - int destRedMask, int destGreenMask, int destBlueMask, - bool flipX, bool flipY) { - if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; + byte[] srcData, int srcDepth, int srcStride, int srcOrder, + int srcX, int srcY, int srcWidth, int srcHeight, + int srcRedMask, int srcGreenMask, int srcBlueMask, + int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, + byte[] destData, int destDepth, int destStride, int destOrder, + int destX, int destY, int destWidth, int destHeight, + int destRedMask, int destGreenMask, int destBlueMask, + bool flipX, bool flipY) { + if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; - // these should be supplied as params later - const int srcAlphaMask = 0, destAlphaMask = 0; + // these should be supplied as params later + const int srcAlphaMask = 0, destAlphaMask = 0; - /*** Prepare scaling data ***/ - int dwm1 = destWidth - 1; - int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; - int dhm1 = destHeight - 1; - int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; + /*** Prepare scaling data ***/ + int dwm1 = destWidth - 1; + int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; + int dhm1 = destHeight - 1; + int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; - /*** Prepare source-related data ***/ - int sbpp, stype; - switch (srcDepth) { - case 8: - sbpp = 1; - stype = TYPE_GENERIC_8; - break; - case 16: - sbpp = 2; - stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; - break; - case 24: - sbpp = 3; - stype = TYPE_GENERIC_24; - break; - case 32: - sbpp = 4; - stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int spr = srcY * srcStride + srcX * sbpp; + /*** Prepare source-related data ***/ + int sbpp, stype; + switch (srcDepth) { + case 8: + sbpp = 1; + stype = TYPE_GENERIC_8; + break; + case 16: + sbpp = 2; + stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; + break; + case 24: + sbpp = 3; + stype = TYPE_GENERIC_24; + break; + case 32: + sbpp = 4; + stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int spr = srcY * srcStride + srcX * sbpp; - /*** Prepare destination-related data ***/ - int dbpp, dtype; - switch (destDepth) { - case 8: - dbpp = 1; - dtype = TYPE_GENERIC_8; - break; - case 16: - dbpp = 2; - dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; - break; - case 24: - dbpp = 3; - dtype = TYPE_GENERIC_24; - break; - case 32: - dbpp = 4; - dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid destination type"); - return; - } - int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX) * dbpp; - int dprxi = (flipX) ? -dbpp : dbpp; - int dpryi = (flipY) ? -destStride : destStride; + /*** Prepare destination-related data ***/ + int dbpp, dtype; + switch (destDepth) { + case 8: + dbpp = 1; + dtype = TYPE_GENERIC_8; + break; + case 16: + dbpp = 2; + dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; + break; + case 24: + dbpp = 3; + dtype = TYPE_GENERIC_24; + break; + case 32: + dbpp = 4; + dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid destination type"); + return; + } + int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX) * dbpp; + int dprxi = (flipX) ? -dbpp : dbpp; + int dpryi = (flipY) ? -destStride : destStride; - /*** Prepare special processing data ***/ - int apr; - if ((op & BLIT_ALPHA) != 0) { - switch (alphaMode) { - case ALPHA_MASK_UNPACKED: - case ALPHA_CHANNEL_SEPARATE: - if (alphaData == null) alphaMode = 0x10000; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_PACKED: - if (alphaData == null) alphaMode = 0x10000; - alphaStride <<= 3; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_INDEX: - //throw new IllegalArgumentException("Invalid alpha type"); - return; - case ALPHA_MASK_RGB: - if (alphaData == null) alphaMode = 0x10000; - apr = 0; - break; - default: - alphaMode = (alphaMode << 16) / 255; // prescale - case ALPHA_CHANNEL_SOURCE: - apr = 0; - break; - } - } else { - alphaMode = 0x10000; - apr = 0; - } + /*** Prepare special processing data ***/ + int apr; + if ((op & BLIT_ALPHA) != 0) { + switch (alphaMode) { + case ALPHA_MASK_UNPACKED: + case ALPHA_CHANNEL_SEPARATE: + if (alphaData == null) alphaMode = 0x10000; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_PACKED: + if (alphaData == null) alphaMode = 0x10000; + alphaStride <<= 3; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_INDEX: + //throw new IllegalArgumentException("Invalid alpha type"); + return; + case ALPHA_MASK_RGB: + if (alphaData == null) alphaMode = 0x10000; + apr = 0; + break; + default: + alphaMode = (alphaMode << 16) / 255; // prescale + case ALPHA_CHANNEL_SOURCE: + apr = 0; + break; + } + } else { + alphaMode = 0x10000; + apr = 0; + } - /*** Blit ***/ - int dp = dpr; - int sp = spr; - if ((alphaMode == 0x10000) && (stype == dtype) && - (srcRedMask == destRedMask) && (srcGreenMask == destGreenMask) && - (srcBlueMask == destBlueMask) && (srcAlphaMask == destAlphaMask)) { - /*** Fast blit (straight copy) ***/ - switch (sbpp) { - case 1: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - destData[dp] = srcData[sp]; - sp += (sfx >>> 16); - } - } - break; - case 2: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - destData[dp] = srcData[sp]; - destData[dp + 1] = srcData[sp + 1]; - sp += (sfx >>> 16) * 2; - } - } - break; - case 3: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - destData[dp] = srcData[sp]; - destData[dp + 1] = srcData[sp + 1]; - destData[dp + 2] = srcData[sp + 2]; - sp += (sfx >>> 16) * 3; - } - } - break; - case 4: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - destData[dp] = srcData[sp]; - destData[dp + 1] = srcData[sp + 1]; - destData[dp + 2] = srcData[sp + 2]; - destData[dp + 3] = srcData[sp + 3]; - sp += (sfx >>> 16) * 4; - } - } - break; + /*** Blit ***/ + int dp = dpr; + int sp = spr; + if ((alphaMode == 0x10000) && (stype == dtype) && + (srcRedMask == destRedMask) && (srcGreenMask == destGreenMask) && + (srcBlueMask == destBlueMask) && (srcAlphaMask == destAlphaMask)) { + /*** Fast blit (straight copy) ***/ + switch (sbpp) { + case 1: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + destData[dp] = srcData[sp]; + sp += (sfx >>> 16); + } + } + break; + case 2: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + destData[dp] = srcData[sp]; + destData[dp + 1] = srcData[sp + 1]; + sp += (sfx >>> 16) * 2; + } + } + break; + case 3: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + destData[dp] = srcData[sp]; + destData[dp + 1] = srcData[sp + 1]; + destData[dp + 2] = srcData[sp + 2]; + sp += (sfx >>> 16) * 3; + } + } + break; + case 4: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + destData[dp] = srcData[sp]; + destData[dp + 1] = srcData[sp + 1]; + destData[dp + 2] = srcData[sp + 2]; + destData[dp + 3] = srcData[sp + 3]; + sp += (sfx >>> 16) * 4; + } + } + break; default: - } - return; - } - /*** Comprehensive blit (apply transformations) ***/ - int srcRedShift = getChannelShift(srcRedMask); - byte[] srcReds = ANY_TO_EIGHT[getChannelWidth(srcRedMask, srcRedShift)]; - int srcGreenShift = getChannelShift(srcGreenMask); - byte[] srcGreens = ANY_TO_EIGHT[getChannelWidth(srcGreenMask, srcGreenShift)]; - int srcBlueShift = getChannelShift(srcBlueMask); - byte[] srcBlues = ANY_TO_EIGHT[getChannelWidth(srcBlueMask, srcBlueShift)]; - int srcAlphaShift = getChannelShift(srcAlphaMask); - byte[] srcAlphas = ANY_TO_EIGHT[getChannelWidth(srcAlphaMask, srcAlphaShift)]; + } + return; + } + /*** Comprehensive blit (apply transformations) ***/ + int srcRedShift = getChannelShift(srcRedMask); + byte[] srcReds = ANY_TO_EIGHT[getChannelWidth(srcRedMask, srcRedShift)]; + int srcGreenShift = getChannelShift(srcGreenMask); + byte[] srcGreens = ANY_TO_EIGHT[getChannelWidth(srcGreenMask, srcGreenShift)]; + int srcBlueShift = getChannelShift(srcBlueMask); + byte[] srcBlues = ANY_TO_EIGHT[getChannelWidth(srcBlueMask, srcBlueShift)]; + int srcAlphaShift = getChannelShift(srcAlphaMask); + byte[] srcAlphas = ANY_TO_EIGHT[getChannelWidth(srcAlphaMask, srcAlphaShift)]; - int destRedShift = getChannelShift(destRedMask); - int destRedWidth = getChannelWidth(destRedMask, destRedShift); - byte[] destReds = ANY_TO_EIGHT[destRedWidth]; - int destRedPreShift = 8 - destRedWidth; - int destGreenShift = getChannelShift(destGreenMask); - int destGreenWidth = getChannelWidth(destGreenMask, destGreenShift); - byte[] destGreens = ANY_TO_EIGHT[destGreenWidth]; - int destGreenPreShift = 8 - destGreenWidth; - int destBlueShift = getChannelShift(destBlueMask); - int destBlueWidth = getChannelWidth(destBlueMask, destBlueShift); - byte[] destBlues = ANY_TO_EIGHT[destBlueWidth]; - int destBluePreShift = 8 - destBlueWidth; - int destAlphaShift = getChannelShift(destAlphaMask); - int destAlphaWidth = getChannelWidth(destAlphaMask, destAlphaShift); - byte[] destAlphas = ANY_TO_EIGHT[destAlphaWidth]; - int destAlphaPreShift = 8 - destAlphaWidth; + int destRedShift = getChannelShift(destRedMask); + int destRedWidth = getChannelWidth(destRedMask, destRedShift); + byte[] destReds = ANY_TO_EIGHT[destRedWidth]; + int destRedPreShift = 8 - destRedWidth; + int destGreenShift = getChannelShift(destGreenMask); + int destGreenWidth = getChannelWidth(destGreenMask, destGreenShift); + byte[] destGreens = ANY_TO_EIGHT[destGreenWidth]; + int destGreenPreShift = 8 - destGreenWidth; + int destBlueShift = getChannelShift(destBlueMask); + int destBlueWidth = getChannelWidth(destBlueMask, destBlueShift); + byte[] destBlues = ANY_TO_EIGHT[destBlueWidth]; + int destBluePreShift = 8 - destBlueWidth; + int destAlphaShift = getChannelShift(destAlphaMask); + int destAlphaWidth = getChannelWidth(destAlphaMask, destAlphaShift); + byte[] destAlphas = ANY_TO_EIGHT[destAlphaWidth]; + int destAlphaPreShift = 8 - destAlphaWidth; - int ap = apr, alpha = alphaMode; - int r = 0, g = 0, b = 0, a = 0; - int rq = 0, gq = 0, bq = 0, aq = 0; - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, - sp = spr += (sfy >>> 16) * srcStride, - ap = apr += (sfy >>> 16) * alphaStride, - sfy = (sfy & 0xffff) + sfyi, - dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, - dp += dprxi, - sfx = (sfx & 0xffff) + sfxi) { - /*** READ NEXT PIXEL ***/ - switch (stype) { - case TYPE_GENERIC_8: { - int data = srcData[sp] & 0xff; - sp += (sfx >>> 16); - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_MSB: { - int data = ((srcData[sp] & 0xff) << 8) | (srcData[sp + 1] & 0xff); - sp += (sfx >>> 16) * 2; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_LSB: { - int data = ((srcData[sp + 1] & 0xff) << 8) | (srcData[sp] & 0xff); - sp += (sfx >>> 16) * 2; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_24: { - int data = (( ((srcData[sp] & 0xff) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp + 2] & 0xff); - sp += (sfx >>> 16) * 3; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_MSB: { - int data = (( (( ((srcData[sp] & 0xff) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp + 2] & 0xff)) << 8) | - (srcData[sp + 3] & 0xff); - sp += (sfx >>> 16) * 4; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_LSB: { - int data = (( (( ((srcData[sp + 3] & 0xff) << 8) | - (srcData[sp + 2] & 0xff)) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp] & 0xff); - sp += (sfx >>> 16) * 4; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; + int ap = apr, alpha = alphaMode; + int r = 0, g = 0, b = 0, a = 0; + int rq = 0, gq = 0, bq = 0, aq = 0; + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, + sp = spr += (sfy >>> 16) * srcStride, + ap = apr += (sfy >>> 16) * alphaStride, + sfy = (sfy & 0xffff) + sfyi, + dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, + dp += dprxi, + sfx = (sfx & 0xffff) + sfxi) { + /*** READ NEXT PIXEL ***/ + switch (stype) { + case TYPE_GENERIC_8: { + int data = srcData[sp] & 0xff; + sp += (sfx >>> 16); + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_MSB: { + int data = ((srcData[sp] & 0xff) << 8) | (srcData[sp + 1] & 0xff); + sp += (sfx >>> 16) * 2; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_LSB: { + int data = ((srcData[sp + 1] & 0xff) << 8) | (srcData[sp] & 0xff); + sp += (sfx >>> 16) * 2; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_24: { + int data = (( ((srcData[sp] & 0xff) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp + 2] & 0xff); + sp += (sfx >>> 16) * 3; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_MSB: { + int data = (( (( ((srcData[sp] & 0xff) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp + 2] & 0xff)) << 8) | + (srcData[sp + 3] & 0xff); + sp += (sfx >>> 16) * 4; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_LSB: { + int data = (( (( ((srcData[sp + 3] & 0xff) << 8) | + (srcData[sp + 2] & 0xff)) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp] & 0xff); + sp += (sfx >>> 16) * 4; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; default: - } + } - /*** DO SPECIAL PROCESSING IF REQUIRED ***/ - switch (alphaMode) { - case ALPHA_CHANNEL_SEPARATE: - alpha = ((alphaData[ap] & 0xff) << 16) / 255; - ap += (sfx >> 16); - break; - case ALPHA_CHANNEL_SOURCE: - alpha = (a << 16) / 255; - break; - case ALPHA_MASK_UNPACKED: - alpha = (alphaData[ap] != 0) ? 0x10000 : 0; - ap += (sfx >> 16); - break; - case ALPHA_MASK_PACKED: - alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; - ap += (sfx >> 16); - break; - case ALPHA_MASK_RGB: - alpha = 0x10000; - for (int i = 0; i < alphaData.length; i += 3) { - if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) { - alpha = 0x0000; - break; - } - } - break; + /*** DO SPECIAL PROCESSING IF REQUIRED ***/ + switch (alphaMode) { + case ALPHA_CHANNEL_SEPARATE: + alpha = ((alphaData[ap] & 0xff) << 16) / 255; + ap += (sfx >> 16); + break; + case ALPHA_CHANNEL_SOURCE: + alpha = (a << 16) / 255; + break; + case ALPHA_MASK_UNPACKED: + alpha = (alphaData[ap] != 0) ? 0x10000 : 0; + ap += (sfx >> 16); + break; + case ALPHA_MASK_PACKED: + alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; + ap += (sfx >> 16); + break; + case ALPHA_MASK_RGB: + alpha = 0x10000; + for (int i = 0; i < alphaData.length; i += 3) { + if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) { + alpha = 0x0000; + break; + } + } + break; default: - } - if (alpha != 0x10000) { - if (alpha == 0x0000) continue; - switch (dtype) { - case TYPE_GENERIC_8: { - int data = destData[dp] & 0xff; - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_MSB: { - int data = ((destData[dp] & 0xff) << 8) | (destData[dp + 1] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_LSB: { - int data = ((destData[dp + 1] & 0xff) << 8) | (destData[dp] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_24: { - int data = (( ((destData[dp] & 0xff) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp + 2] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_MSB: { - int data = (( (( ((destData[dp] & 0xff) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp + 2] & 0xff)) << 8) | - (destData[dp + 3] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_LSB: { - int data = (( (( ((destData[dp + 3] & 0xff) << 8) | - (destData[dp + 2] & 0xff)) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; + } + if (alpha != 0x10000) { + if (alpha == 0x0000) continue; + switch (dtype) { + case TYPE_GENERIC_8: { + int data = destData[dp] & 0xff; + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_MSB: { + int data = ((destData[dp] & 0xff) << 8) | (destData[dp + 1] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_LSB: { + int data = ((destData[dp + 1] & 0xff) << 8) | (destData[dp] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_24: { + int data = (( ((destData[dp] & 0xff) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp + 2] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_MSB: { + int data = (( (( ((destData[dp] & 0xff) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp + 2] & 0xff)) << 8) | + (destData[dp + 3] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_LSB: { + int data = (( (( ((destData[dp + 3] & 0xff) << 8) | + (destData[dp + 2] & 0xff)) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; default: - } - // Perform alpha blending - a = aq + ((a - aq) * alpha >> 16); - r = rq + ((r - rq) * alpha >> 16); - g = gq + ((g - gq) * alpha >> 16); - b = bq + ((b - bq) * alpha >> 16); - } + } + // Perform alpha blending + a = aq + ((a - aq) * alpha >> 16); + r = rq + ((r - rq) * alpha >> 16); + g = gq + ((g - gq) * alpha >> 16); + b = bq + ((b - bq) * alpha >> 16); + } - /*** WRITE NEXT PIXEL ***/ - int data = - (r >>> destRedPreShift << destRedShift) | - (g >>> destGreenPreShift << destGreenShift) | - (b >>> destBluePreShift << destBlueShift) | - (a >>> destAlphaPreShift << destAlphaShift); - switch (dtype) { - case TYPE_GENERIC_8: { - destData[dp] = cast(byte) data; - } break; - case TYPE_GENERIC_16_MSB: { - destData[dp] = cast(byte) (data >>> 8); - destData[dp + 1] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_16_LSB: { - destData[dp] = cast(byte) (data & 0xff); - destData[dp + 1] = cast(byte) (data >>> 8); - } break; - case TYPE_GENERIC_24: { - destData[dp] = cast(byte) (data >>> 16); - destData[dp + 1] = cast(byte) (data >>> 8); - destData[dp + 2] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_32_MSB: { - destData[dp] = cast(byte) (data >>> 24); - destData[dp + 1] = cast(byte) (data >>> 16); - destData[dp + 2] = cast(byte) (data >>> 8); - destData[dp + 3] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_32_LSB: { - destData[dp] = cast(byte) (data & 0xff); - destData[dp + 1] = cast(byte) (data >>> 8); - destData[dp + 2] = cast(byte) (data >>> 16); - destData[dp + 3] = cast(byte) (data >>> 24); - } break; + /*** WRITE NEXT PIXEL ***/ + int data = + (r >>> destRedPreShift << destRedShift) | + (g >>> destGreenPreShift << destGreenShift) | + (b >>> destBluePreShift << destBlueShift) | + (a >>> destAlphaPreShift << destAlphaShift); + switch (dtype) { + case TYPE_GENERIC_8: { + destData[dp] = cast(byte) data; + } break; + case TYPE_GENERIC_16_MSB: { + destData[dp] = cast(byte) (data >>> 8); + destData[dp + 1] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_16_LSB: { + destData[dp] = cast(byte) (data & 0xff); + destData[dp + 1] = cast(byte) (data >>> 8); + } break; + case TYPE_GENERIC_24: { + destData[dp] = cast(byte) (data >>> 16); + destData[dp + 1] = cast(byte) (data >>> 8); + destData[dp + 2] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_32_MSB: { + destData[dp] = cast(byte) (data >>> 24); + destData[dp + 1] = cast(byte) (data >>> 16); + destData[dp + 2] = cast(byte) (data >>> 8); + destData[dp + 3] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_32_LSB: { + destData[dp] = cast(byte) (data & 0xff); + destData[dp + 1] = cast(byte) (data >>> 8); + destData[dp + 2] = cast(byte) (data >>> 16); + destData[dp + 3] = cast(byte) (data >>> 24); + } break; default: - } - } - } + } + } + } } /** @@ -2192,493 +2192,493 @@ * @param flipY if true the resulting image is flipped along the horizontal axis */ static void blit(int op, - byte[] srcData, int srcDepth, int srcStride, int srcOrder, - int srcX, int srcY, int srcWidth, int srcHeight, - byte[] srcReds, byte[] srcGreens, byte[] srcBlues, - int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, - byte[] destData, int destDepth, int destStride, int destOrder, - int destX, int destY, int destWidth, int destHeight, - byte[] destReds, byte[] destGreens, byte[] destBlues, - bool flipX, bool flipY) { - if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; + byte[] srcData, int srcDepth, int srcStride, int srcOrder, + int srcX, int srcY, int srcWidth, int srcHeight, + byte[] srcReds, byte[] srcGreens, byte[] srcBlues, + int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, + byte[] destData, int destDepth, int destStride, int destOrder, + int destX, int destY, int destWidth, int destHeight, + byte[] destReds, byte[] destGreens, byte[] destBlues, + bool flipX, bool flipY) { + if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; - /*** Prepare scaling data ***/ - int dwm1 = destWidth - 1; - int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; - int dhm1 = destHeight - 1; - int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; + /*** Prepare scaling data ***/ + int dwm1 = destWidth - 1; + int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; + int dhm1 = destHeight - 1; + int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; - /*** Prepare source-related data ***/ - int stype; - switch (srcDepth) { - case 8: - stype = TYPE_INDEX_8; - break; - case 4: - srcStride <<= 1; - stype = TYPE_INDEX_4; - break; - case 2: - srcStride <<= 2; - stype = TYPE_INDEX_2; - break; - case 1: - srcStride <<= 3; - stype = (srcOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int spr = srcY * srcStride + srcX; + /*** Prepare source-related data ***/ + int stype; + switch (srcDepth) { + case 8: + stype = TYPE_INDEX_8; + break; + case 4: + srcStride <<= 1; + stype = TYPE_INDEX_4; + break; + case 2: + srcStride <<= 2; + stype = TYPE_INDEX_2; + break; + case 1: + srcStride <<= 3; + stype = (srcOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int spr = srcY * srcStride + srcX; - /*** Prepare destination-related data ***/ - int dtype; - switch (destDepth) { - case 8: - dtype = TYPE_INDEX_8; - break; - case 4: - destStride <<= 1; - dtype = TYPE_INDEX_4; - break; - case 2: - destStride <<= 2; - dtype = TYPE_INDEX_2; - break; - case 1: - destStride <<= 3; - dtype = (destOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX); - int dprxi = (flipX) ? -1 : 1; - int dpryi = (flipY) ? -destStride : destStride; + /*** Prepare destination-related data ***/ + int dtype; + switch (destDepth) { + case 8: + dtype = TYPE_INDEX_8; + break; + case 4: + destStride <<= 1; + dtype = TYPE_INDEX_4; + break; + case 2: + destStride <<= 2; + dtype = TYPE_INDEX_2; + break; + case 1: + destStride <<= 3; + dtype = (destOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX); + int dprxi = (flipX) ? -1 : 1; + int dpryi = (flipY) ? -destStride : destStride; - /*** Prepare special processing data ***/ - int apr; - if ((op & BLIT_ALPHA) != 0) { - switch (alphaMode) { - case ALPHA_MASK_UNPACKED: - case ALPHA_CHANNEL_SEPARATE: - if (alphaData == null) alphaMode = 0x10000; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_PACKED: - if (alphaData == null) alphaMode = 0x10000; - alphaStride <<= 3; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_INDEX: - case ALPHA_MASK_RGB: - if (alphaData == null) alphaMode = 0x10000; - apr = 0; - break; - default: - alphaMode = (alphaMode << 16) / 255; // prescale - case ALPHA_CHANNEL_SOURCE: - apr = 0; - break; - } - } else { - alphaMode = 0x10000; - apr = 0; - } - bool ditherEnabled = (op & BLIT_DITHER) != 0; + /*** Prepare special processing data ***/ + int apr; + if ((op & BLIT_ALPHA) != 0) { + switch (alphaMode) { + case ALPHA_MASK_UNPACKED: + case ALPHA_CHANNEL_SEPARATE: + if (alphaData == null) alphaMode = 0x10000; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_PACKED: + if (alphaData == null) alphaMode = 0x10000; + alphaStride <<= 3; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_INDEX: + case ALPHA_MASK_RGB: + if (alphaData == null) alphaMode = 0x10000; + apr = 0; + break; + default: + alphaMode = (alphaMode << 16) / 255; // prescale + case ALPHA_CHANNEL_SOURCE: + apr = 0; + break; + } + } else { + alphaMode = 0x10000; + apr = 0; + } + bool ditherEnabled = (op & BLIT_DITHER) != 0; - /*** Blit ***/ - int dp = dpr; - int sp = spr; - int ap = apr; - int destPaletteSize = 1 << destDepth; - if ((destReds != null) && (destReds.length < destPaletteSize)) destPaletteSize = destReds.length; - byte[] paletteMapping = null; - bool isExactPaletteMapping = true; - switch (alphaMode) { - case 0x10000: - /*** If the palettes and formats are equivalent use a one-to-one mapping ***/ - if ((stype == dtype) && - (srcReds == destReds) && (srcGreens == destGreens) && (srcBlues == destBlues)) { - paletteMapping = ONE_TO_ONE_MAPPING; - break; - /*** If palettes have not been supplied, supply a suitable mapping ***/ - } else if ((srcReds == null) || (destReds == null)) { - if (srcDepth <= destDepth) { - paletteMapping = ONE_TO_ONE_MAPPING; - } else { - paletteMapping = new byte[1 << srcDepth]; - int mask = (0xff << destDepth) >>> 8; - for (int i = 0; i < paletteMapping.length; ++i) paletteMapping[i] = cast(byte)(i & mask); - } - break; - } - case ALPHA_MASK_UNPACKED: - case ALPHA_MASK_PACKED: - case ALPHA_MASK_INDEX: - case ALPHA_MASK_RGB: - /*** Generate a palette mapping ***/ - int srcPaletteSize = 1 << srcDepth; - paletteMapping = new byte[srcPaletteSize]; - if ((srcReds != null) && (srcReds.length < srcPaletteSize)) srcPaletteSize = srcReds.length; - for (int i = 0, r, g, b, index; i < srcPaletteSize; ++i) { - r = srcReds[i] & 0xff; - g = srcGreens[i] & 0xff; - b = srcBlues[i] & 0xff; - index = 0; - int minDistance = 0x7fffffff; - for (int j = 0, dr, dg, db, distance; j < destPaletteSize; ++j) { - dr = (destReds[j] & 0xff) - r; - dg = (destGreens[j] & 0xff) - g; - db = (destBlues[j] & 0xff) - b; - distance = dr * dr + dg * dg + db * db; - if (distance < minDistance) { - index = j; - if (distance == 0) break; - minDistance = distance; - } - } - paletteMapping[i] = cast(byte)index; - if (minDistance != 0) isExactPaletteMapping = false; - } - break; + /*** Blit ***/ + int dp = dpr; + int sp = spr; + int ap = apr; + int destPaletteSize = 1 << destDepth; + if ((destReds != null) && (destReds.length < destPaletteSize)) destPaletteSize = destReds.length; + byte[] paletteMapping = null; + bool isExactPaletteMapping = true; + switch (alphaMode) { + case 0x10000: + /*** If the palettes and formats are equivalent use a one-to-one mapping ***/ + if ((stype == dtype) && + (srcReds == destReds) && (srcGreens == destGreens) && (srcBlues == destBlues)) { + paletteMapping = ONE_TO_ONE_MAPPING; + break; + /*** If palettes have not been supplied, supply a suitable mapping ***/ + } else if ((srcReds == null) || (destReds == null)) { + if (srcDepth <= destDepth) { + paletteMapping = ONE_TO_ONE_MAPPING; + } else { + paletteMapping = new byte[1 << srcDepth]; + int mask = (0xff << destDepth) >>> 8; + for (int i = 0; i < paletteMapping.length; ++i) paletteMapping[i] = cast(byte)(i & mask); + } + break; + } + case ALPHA_MASK_UNPACKED: + case ALPHA_MASK_PACKED: + case ALPHA_MASK_INDEX: + case ALPHA_MASK_RGB: + /*** Generate a palette mapping ***/ + int srcPaletteSize = 1 << srcDepth; + paletteMapping = new byte[srcPaletteSize]; + if ((srcReds != null) && (srcReds.length < srcPaletteSize)) srcPaletteSize = srcReds.length; + for (int i = 0, r, g, b, index; i < srcPaletteSize; ++i) { + r = srcReds[i] & 0xff; + g = srcGreens[i] & 0xff; + b = srcBlues[i] & 0xff; + index = 0; + int minDistance = 0x7fffffff; + for (int j = 0, dr, dg, db, distance; j < destPaletteSize; ++j) { + dr = (destReds[j] & 0xff) - r; + dg = (destGreens[j] & 0xff) - g; + db = (destBlues[j] & 0xff) - b; + distance = dr * dr + dg * dg + db * db; + if (distance < minDistance) { + index = j; + if (distance == 0) break; + minDistance = distance; + } + } + paletteMapping[i] = cast(byte)index; + if (minDistance != 0) isExactPaletteMapping = false; + } + break; default: - } - if ((paletteMapping != null) && (isExactPaletteMapping || ! ditherEnabled)) { - if ((stype == dtype) && (alphaMode == 0x10000)) { - /*** Fast blit (copy w/ mapping) ***/ - switch (stype) { - case TYPE_INDEX_8: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - destData[dp] = paletteMapping[srcData[sp] & 0xff]; - sp += (sfx >>> 16); - } - } - break; - case TYPE_INDEX_4: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - int v; - if ((sp & 1) != 0) v = paletteMapping[srcData[sp >> 1] & 0x0f]; - else v = (srcData[sp >> 1] >>> 4) & 0x0f; - sp += (sfx >>> 16); - if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | v); - else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (v << 4)); - } - } - break; - case TYPE_INDEX_2: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - int index = paletteMapping[(srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03]; - sp += (sfx >>> 16); - int shift = 6 - (dp & 3) * 2; - destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (index << shift)); - } - } - break; - case TYPE_INDEX_1_MSB: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - int index = paletteMapping[(srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01]; - sp += (sfx >>> 16); - int shift = 7 - (dp & 7); - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); - } - } - break; - case TYPE_INDEX_1_LSB: - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { - int index = paletteMapping[(srcData[sp >> 3] >>> (sp & 7)) & 0x01]; - sp += (sfx >>> 16); - int shift = dp & 7; - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); - } - } - break; + } + if ((paletteMapping != null) && (isExactPaletteMapping || ! ditherEnabled)) { + if ((stype == dtype) && (alphaMode == 0x10000)) { + /*** Fast blit (copy w/ mapping) ***/ + switch (stype) { + case TYPE_INDEX_8: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + destData[dp] = paletteMapping[srcData[sp] & 0xff]; + sp += (sfx >>> 16); + } + } + break; + case TYPE_INDEX_4: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + int v; + if ((sp & 1) != 0) v = paletteMapping[srcData[sp >> 1] & 0x0f]; + else v = (srcData[sp >> 1] >>> 4) & 0x0f; + sp += (sfx >>> 16); + if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | v); + else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (v << 4)); + } + } + break; + case TYPE_INDEX_2: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + int index = paletteMapping[(srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03]; + sp += (sfx >>> 16); + int shift = 6 - (dp & 3) * 2; + destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (index << shift)); + } + } + break; + case TYPE_INDEX_1_MSB: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + int index = paletteMapping[(srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01]; + sp += (sfx >>> 16); + int shift = 7 - (dp & 7); + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); + } + } + break; + case TYPE_INDEX_1_LSB: + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, sp = spr += (sfy >>> 16) * srcStride, sfy = (sfy & 0xffff) + sfyi, dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, dp += dprxi, sfx = (sfx & 0xffff) + sfxi) { + int index = paletteMapping[(srcData[sp >> 3] >>> (sp & 7)) & 0x01]; + sp += (sfx >>> 16); + int shift = dp & 7; + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); + } + } + break; default: - } - } else { - /*** Convert between indexed modes using mapping and mask ***/ - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, - sp = spr += (sfy >>> 16) * srcStride, - sfy = (sfy & 0xffff) + sfyi, - dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, - dp += dprxi, - sfx = (sfx & 0xffff) + sfxi) { - int index; - /*** READ NEXT PIXEL ***/ - switch (stype) { - case TYPE_INDEX_8: - index = srcData[sp] & 0xff; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_4: - if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; - else index = (srcData[sp >> 1] >>> 4) & 0x0f; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_2: - index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_MSB: - index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_LSB: - index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; - sp += (sfx >>> 16); - break; - default: - return; - } - /*** APPLY MASK ***/ - switch (alphaMode) { - case ALPHA_MASK_UNPACKED: { - byte mask = alphaData[ap]; - ap += (sfx >> 16); - if (mask == 0) continue; - } break; - case ALPHA_MASK_PACKED: { - int mask = alphaData[ap >> 3] & (1 << (ap & 7)); - ap += (sfx >> 16); - if (mask == 0) continue; - } break; - case ALPHA_MASK_INDEX: { - int i = 0; - while (i < alphaData.length) { - if (index == (alphaData[i] & 0xff)) break; - } - if (i < alphaData.length) continue; - } break; - case ALPHA_MASK_RGB: { - byte r = srcReds[index], g = srcGreens[index], b = srcBlues[index]; - int i = 0; - while (i < alphaData.length) { - if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) break; - i += 3; - } - if (i < alphaData.length) continue; - } break; + } + } else { + /*** Convert between indexed modes using mapping and mask ***/ + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, + sp = spr += (sfy >>> 16) * srcStride, + sfy = (sfy & 0xffff) + sfyi, + dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, + dp += dprxi, + sfx = (sfx & 0xffff) + sfxi) { + int index; + /*** READ NEXT PIXEL ***/ + switch (stype) { + case TYPE_INDEX_8: + index = srcData[sp] & 0xff; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_4: + if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; + else index = (srcData[sp >> 1] >>> 4) & 0x0f; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_2: + index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_MSB: + index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_LSB: + index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; + sp += (sfx >>> 16); + break; default: - } - index = paletteMapping[index] & 0xff; + return; + } + /*** APPLY MASK ***/ + switch (alphaMode) { + case ALPHA_MASK_UNPACKED: { + byte mask = alphaData[ap]; + ap += (sfx >> 16); + if (mask == 0) continue; + } break; + case ALPHA_MASK_PACKED: { + int mask = alphaData[ap >> 3] & (1 << (ap & 7)); + ap += (sfx >> 16); + if (mask == 0) continue; + } break; + case ALPHA_MASK_INDEX: { + int i = 0; + while (i < alphaData.length) { + if (index == (alphaData[i] & 0xff)) break; + } + if (i < alphaData.length) continue; + } break; + case ALPHA_MASK_RGB: { + byte r = srcReds[index], g = srcGreens[index], b = srcBlues[index]; + int i = 0; + while (i < alphaData.length) { + if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) break; + i += 3; + } + if (i < alphaData.length) continue; + } break; + default: + } + index = paletteMapping[index] & 0xff; - /*** WRITE NEXT PIXEL ***/ - switch (dtype) { - case TYPE_INDEX_8: - destData[dp] = cast(byte) index; - break; - case TYPE_INDEX_4: - if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | index); - else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (index << 4)); - break; - case TYPE_INDEX_2: { - int shift = 6 - (dp & 3) * 2; - destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (index << shift)); - } break; - case TYPE_INDEX_1_MSB: { - int shift = 7 - (dp & 7); - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); - } break; - case TYPE_INDEX_1_LSB: { - int shift = dp & 7; - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); - } break; + /*** WRITE NEXT PIXEL ***/ + switch (dtype) { + case TYPE_INDEX_8: + destData[dp] = cast(byte) index; + break; + case TYPE_INDEX_4: + if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | index); + else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (index << 4)); + break; + case TYPE_INDEX_2: { + int shift = 6 - (dp & 3) * 2; + destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (index << shift)); + } break; + case TYPE_INDEX_1_MSB: { + int shift = 7 - (dp & 7); + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); + } break; + case TYPE_INDEX_1_LSB: { + int shift = dp & 7; + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (index << shift)); + } break; default: - } - } - } - } - return; - } + } + } + } + } + return; + } - /*** Comprehensive blit (apply transformations) ***/ - int alpha = alphaMode; - int index = 0; - int indexq = 0; - int lastindex = 0, lastr = -1, lastg = -1, lastb = -1; - int[] rerr, gerr, berr; - if (ditherEnabled) { - rerr = new int[destWidth + 2]; - gerr = new int[destWidth + 2]; - berr = new int[destWidth + 2]; - } else { - rerr = null; gerr = null; berr = null; - } - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, - sp = spr += (sfy >>> 16) * srcStride, - ap = apr += (sfy >>> 16) * alphaStride, - sfy = (sfy & 0xffff) + sfyi, - dp = dpr += dpryi) { - int lrerr = 0, lgerr = 0, lberr = 0; - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, - dp += dprxi, - sfx = (sfx & 0xffff) + sfxi) { - /*** READ NEXT PIXEL ***/ - switch (stype) { - case TYPE_INDEX_8: - index = srcData[sp] & 0xff; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_4: - if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; - else index = (srcData[sp >> 1] >>> 4) & 0x0f; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_2: - index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_MSB: - index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_LSB: - index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; - sp += (sfx >>> 16); - break; + /*** Comprehensive blit (apply transformations) ***/ + int alpha = alphaMode; + int index = 0; + int indexq = 0; + int lastindex = 0, lastr = -1, lastg = -1, lastb = -1; + int[] rerr, gerr, berr; + if (ditherEnabled) { + rerr = new int[destWidth + 2]; + gerr = new int[destWidth + 2]; + berr = new int[destWidth + 2]; + } else { + rerr = null; gerr = null; berr = null; + } + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, + sp = spr += (sfy >>> 16) * srcStride, + ap = apr += (sfy >>> 16) * alphaStride, + sfy = (sfy & 0xffff) + sfyi, + dp = dpr += dpryi) { + int lrerr = 0, lgerr = 0, lberr = 0; + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, + dp += dprxi, + sfx = (sfx & 0xffff) + sfxi) { + /*** READ NEXT PIXEL ***/ + switch (stype) { + case TYPE_INDEX_8: + index = srcData[sp] & 0xff; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_4: + if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; + else index = (srcData[sp >> 1] >>> 4) & 0x0f; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_2: + index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_MSB: + index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_LSB: + index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; + sp += (sfx >>> 16); + break; default: - } + } - /*** DO SPECIAL PROCESSING IF REQUIRED ***/ - int r = srcReds[index] & 0xff, g = srcGreens[index] & 0xff, b = srcBlues[index] & 0xff; - switch (alphaMode) { - case ALPHA_CHANNEL_SEPARATE: - alpha = ((alphaData[ap] & 0xff) << 16) / 255; - ap += (sfx >> 16); - break; - case ALPHA_MASK_UNPACKED: - alpha = (alphaData[ap] != 0) ? 0x10000 : 0; - ap += (sfx >> 16); - break; - case ALPHA_MASK_PACKED: - alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; - ap += (sfx >> 16); - break; - case ALPHA_MASK_INDEX: { // could speed up using binary search if we sorted the indices - int i = 0; - while (i < alphaData.length) { - if (index == (alphaData[i] & 0xff)) break; - } - if (i < alphaData.length) continue; - } break; - case ALPHA_MASK_RGB: { - int i = 0; - while (i < alphaData.length) { - if ((r == (alphaData[i] & 0xff)) && - (g == (alphaData[i + 1] & 0xff)) && - (b == (alphaData[i + 2] & 0xff))) break; - i += 3; - } - if (i < alphaData.length) continue; - } break; + /*** DO SPECIAL PROCESSING IF REQUIRED ***/ + int r = srcReds[index] & 0xff, g = srcGreens[index] & 0xff, b = srcBlues[index] & 0xff; + switch (alphaMode) { + case ALPHA_CHANNEL_SEPARATE: + alpha = ((alphaData[ap] & 0xff) << 16) / 255; + ap += (sfx >> 16); + break; + case ALPHA_MASK_UNPACKED: + alpha = (alphaData[ap] != 0) ? 0x10000 : 0; + ap += (sfx >> 16); + break; + case ALPHA_MASK_PACKED: + alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; + ap += (sfx >> 16); + break; + case ALPHA_MASK_INDEX: { // could speed up using binary search if we sorted the indices + int i = 0; + while (i < alphaData.length) { + if (index == (alphaData[i] & 0xff)) break; + } + if (i < alphaData.length) continue; + } break; + case ALPHA_MASK_RGB: { + int i = 0; + while (i < alphaData.length) { + if ((r == (alphaData[i] & 0xff)) && + (g == (alphaData[i + 1] & 0xff)) && + (b == (alphaData[i + 2] & 0xff))) break; + i += 3; + } + if (i < alphaData.length) continue; + } break; default: - } - if (alpha != 0x10000) { - if (alpha == 0x0000) continue; - switch (dtype) { - case TYPE_INDEX_8: - indexq = destData[dp] & 0xff; - break; - case TYPE_INDEX_4: - if ((dp & 1) != 0) indexq = destData[dp >> 1] & 0x0f; - else indexq = (destData[dp >> 1] >>> 4) & 0x0f; - break; - case TYPE_INDEX_2: - indexq = (destData[dp >> 2] >>> (6 - (dp & 3) * 2)) & 0x03; - break; - case TYPE_INDEX_1_MSB: - indexq = (destData[dp >> 3] >>> (7 - (dp & 7))) & 0x01; - break; - case TYPE_INDEX_1_LSB: - indexq = (destData[dp >> 3] >>> (dp & 7)) & 0x01; - break; + } + if (alpha != 0x10000) { + if (alpha == 0x0000) continue; + switch (dtype) { + case TYPE_INDEX_8: + indexq = destData[dp] & 0xff; + break; + case TYPE_INDEX_4: + if ((dp & 1) != 0) indexq = destData[dp >> 1] & 0x0f; + else indexq = (destData[dp >> 1] >>> 4) & 0x0f; + break; + case TYPE_INDEX_2: + indexq = (destData[dp >> 2] >>> (6 - (dp & 3) * 2)) & 0x03; + break; + case TYPE_INDEX_1_MSB: + indexq = (destData[dp >> 3] >>> (7 - (dp & 7))) & 0x01; + break; + case TYPE_INDEX_1_LSB: + indexq = (destData[dp >> 3] >>> (dp & 7)) & 0x01; + break; default: - } - // Perform alpha blending - int rq = destReds[indexq] & 0xff; - int gq = destGreens[indexq] & 0xff; - int bq = destBlues[indexq] & 0xff; - r = rq + ((r - rq) * alpha >> 16); - g = gq + ((g - gq) * alpha >> 16); - b = bq + ((b - bq) * alpha >> 16); - } + } + // Perform alpha blending + int rq = destReds[indexq] & 0xff; + int gq = destGreens[indexq] & 0xff; + int bq = destBlues[indexq] & 0xff; + r = rq + ((r - rq) * alpha >> 16); + g = gq + ((g - gq) * alpha >> 16); + b = bq + ((b - bq) * alpha >> 16); + } - /*** MAP COLOR TO THE PALETTE ***/ - if (ditherEnabled) { - // Floyd-Steinberg error diffusion - r += rerr[dx] >> 4; - if (r < 0) r = 0; else if (r > 255) r = 255; - g += gerr[dx] >> 4; - if (g < 0) g = 0; else if (g > 255) g = 255; - b += berr[dx] >> 4; - if (b < 0) b = 0; else if (b > 255) b = 255; - rerr[dx] = lrerr; - gerr[dx] = lgerr; - berr[dx] = lberr; - } - if (r != lastr || g != lastg || b != lastb) { - // moving the variable declarations out seems to make the JDK JIT happier... - for (int j = 0, dr, dg, db, distance, minDistance = 0x7fffffff; j < destPaletteSize; ++j) { - dr = (destReds[j] & 0xff) - r; - dg = (destGreens[j] & 0xff) - g; - db = (destBlues[j] & 0xff) - b; - distance = dr * dr + dg * dg + db * db; - if (distance < minDistance) { - lastindex = j; - if (distance == 0) break; - minDistance = distance; - } - } - lastr = r; lastg = g; lastb = b; - } - if (ditherEnabled) { - // Floyd-Steinberg error diffusion, cont'd... - int dxm1 = dx - 1, dxp1 = dx + 1; - int acc; - rerr[dxp1] += acc = (lrerr = r - (destReds[lastindex] & 0xff)) + lrerr + lrerr; - rerr[dx] += acc += lrerr + lrerr; - rerr[dxm1] += acc + lrerr + lrerr; - gerr[dxp1] += acc = (lgerr = g - (destGreens[lastindex] & 0xff)) + lgerr + lgerr; - gerr[dx] += acc += lgerr + lgerr; - gerr[dxm1] += acc + lgerr + lgerr; - berr[dxp1] += acc = (lberr = b - (destBlues[lastindex] & 0xff)) + lberr + lberr; - berr[dx] += acc += lberr + lberr; - berr[dxm1] += acc + lberr + lberr; - } + /*** MAP COLOR TO THE PALETTE ***/ + if (ditherEnabled) { + // Floyd-Steinberg error diffusion + r += rerr[dx] >> 4; + if (r < 0) r = 0; else if (r > 255) r = 255; + g += gerr[dx] >> 4; + if (g < 0) g = 0; else if (g > 255) g = 255; + b += berr[dx] >> 4; + if (b < 0) b = 0; else if (b > 255) b = 255; + rerr[dx] = lrerr; + gerr[dx] = lgerr; + berr[dx] = lberr; + } + if (r != lastr || g != lastg || b != lastb) { + // moving the variable declarations out seems to make the JDK JIT happier... + for (int j = 0, dr, dg, db, distance, minDistance = 0x7fffffff; j < destPaletteSize; ++j) { + dr = (destReds[j] & 0xff) - r; + dg = (destGreens[j] & 0xff) - g; + db = (destBlues[j] & 0xff) - b; + distance = dr * dr + dg * dg + db * db; + if (distance < minDistance) { + lastindex = j; + if (distance == 0) break; + minDistance = distance; + } + } + lastr = r; lastg = g; lastb = b; + } + if (ditherEnabled) { + // Floyd-Steinberg error diffusion, cont'd... + int dxm1 = dx - 1, dxp1 = dx + 1; + int acc; + rerr[dxp1] += acc = (lrerr = r - (destReds[lastindex] & 0xff)) + lrerr + lrerr; + rerr[dx] += acc += lrerr + lrerr; + rerr[dxm1] += acc + lrerr + lrerr; + gerr[dxp1] += acc = (lgerr = g - (destGreens[lastindex] & 0xff)) + lgerr + lgerr; + gerr[dx] += acc += lgerr + lgerr; + gerr[dxm1] += acc + lgerr + lgerr; + berr[dxp1] += acc = (lberr = b - (destBlues[lastindex] & 0xff)) + lberr + lberr; + berr[dx] += acc += lberr + lberr; + berr[dxm1] += acc + lberr + lberr; + } - /*** WRITE NEXT PIXEL ***/ - switch (dtype) { - case TYPE_INDEX_8: - destData[dp] = cast(byte) lastindex; - break; - case TYPE_INDEX_4: - if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | lastindex); - else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (lastindex << 4)); - break; - case TYPE_INDEX_2: { - int shift = 6 - (dp & 3) * 2; - destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (lastindex << shift)); - } break; - case TYPE_INDEX_1_MSB: { - int shift = 7 - (dp & 7); - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); - } break; - case TYPE_INDEX_1_LSB: { - int shift = dp & 7; - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); - } break; + /*** WRITE NEXT PIXEL ***/ + switch (dtype) { + case TYPE_INDEX_8: + destData[dp] = cast(byte) lastindex; + break; + case TYPE_INDEX_4: + if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | lastindex); + else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (lastindex << 4)); + break; + case TYPE_INDEX_2: { + int shift = 6 - (dp & 3) * 2; + destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (lastindex << shift)); + } break; + case TYPE_INDEX_1_MSB: { + int shift = 7 - (dp & 7); + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); + } break; + case TYPE_INDEX_1_LSB: { + int shift = dp & 7; + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); + } break; default: - } - } - } + } + } + } } /** @@ -2727,300 +2727,300 @@ * @param flipY if true the resulting image is flipped along the horizontal axis */ static void blit(int op, - byte[] srcData, int srcDepth, int srcStride, int srcOrder, - int srcX, int srcY, int srcWidth, int srcHeight, - byte[] srcReds, byte[] srcGreens, byte[] srcBlues, - int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, - byte[] destData, int destDepth, int destStride, int destOrder, - int destX, int destY, int destWidth, int destHeight, - int destRedMask, int destGreenMask, int destBlueMask, - bool flipX, bool flipY) { - if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; + byte[] srcData, int srcDepth, int srcStride, int srcOrder, + int srcX, int srcY, int srcWidth, int srcHeight, + byte[] srcReds, byte[] srcGreens, byte[] srcBlues, + int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, + byte[] destData, int destDepth, int destStride, int destOrder, + int destX, int destY, int destWidth, int destHeight, + int destRedMask, int destGreenMask, int destBlueMask, + bool flipX, bool flipY) { + if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; - // these should be supplied as params later - int destAlphaMask = 0; + // these should be supplied as params later + int destAlphaMask = 0; - /*** Prepare scaling data ***/ - int dwm1 = destWidth - 1; - int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; - int dhm1 = destHeight - 1; - int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; + /*** Prepare scaling data ***/ + int dwm1 = destWidth - 1; + int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; + int dhm1 = destHeight - 1; + int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; - /*** Prepare source-related data ***/ - int stype; - switch (srcDepth) { - case 8: - stype = TYPE_INDEX_8; - break; - case 4: - srcStride <<= 1; - stype = TYPE_INDEX_4; - break; - case 2: - srcStride <<= 2; - stype = TYPE_INDEX_2; - break; - case 1: - srcStride <<= 3; - stype = (srcOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int spr = srcY * srcStride + srcX; + /*** Prepare source-related data ***/ + int stype; + switch (srcDepth) { + case 8: + stype = TYPE_INDEX_8; + break; + case 4: + srcStride <<= 1; + stype = TYPE_INDEX_4; + break; + case 2: + srcStride <<= 2; + stype = TYPE_INDEX_2; + break; + case 1: + srcStride <<= 3; + stype = (srcOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int spr = srcY * srcStride + srcX; - /*** Prepare destination-related data ***/ - int dbpp, dtype; - switch (destDepth) { - case 8: - dbpp = 1; - dtype = TYPE_GENERIC_8; - break; - case 16: - dbpp = 2; - dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; - break; - case 24: - dbpp = 3; - dtype = TYPE_GENERIC_24; - break; - case 32: - dbpp = 4; - dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid destination type"); - return; - } - int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX) * dbpp; - int dprxi = (flipX) ? -dbpp : dbpp; - int dpryi = (flipY) ? -destStride : destStride; + /*** Prepare destination-related data ***/ + int dbpp, dtype; + switch (destDepth) { + case 8: + dbpp = 1; + dtype = TYPE_GENERIC_8; + break; + case 16: + dbpp = 2; + dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; + break; + case 24: + dbpp = 3; + dtype = TYPE_GENERIC_24; + break; + case 32: + dbpp = 4; + dtype = (destOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid destination type"); + return; + } + int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX) * dbpp; + int dprxi = (flipX) ? -dbpp : dbpp; + int dpryi = (flipY) ? -destStride : destStride; - /*** Prepare special processing data ***/ - int apr; - if ((op & BLIT_ALPHA) != 0) { - switch (alphaMode) { - case ALPHA_MASK_UNPACKED: - case ALPHA_CHANNEL_SEPARATE: - if (alphaData == null) alphaMode = 0x10000; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_PACKED: - if (alphaData == null) alphaMode = 0x10000; - alphaStride <<= 3; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_INDEX: - case ALPHA_MASK_RGB: - if (alphaData == null) alphaMode = 0x10000; - apr = 0; - break; - default: - alphaMode = (alphaMode << 16) / 255; // prescale - case ALPHA_CHANNEL_SOURCE: - apr = 0; - break; - } - } else { - alphaMode = 0x10000; - apr = 0; - } + /*** Prepare special processing data ***/ + int apr; + if ((op & BLIT_ALPHA) != 0) { + switch (alphaMode) { + case ALPHA_MASK_UNPACKED: + case ALPHA_CHANNEL_SEPARATE: + if (alphaData == null) alphaMode = 0x10000; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_PACKED: + if (alphaData == null) alphaMode = 0x10000; + alphaStride <<= 3; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_INDEX: + case ALPHA_MASK_RGB: + if (alphaData == null) alphaMode = 0x10000; + apr = 0; + break; + default: + alphaMode = (alphaMode << 16) / 255; // prescale + case ALPHA_CHANNEL_SOURCE: + apr = 0; + break; + } + } else { + alphaMode = 0x10000; + apr = 0; + } - /*** Comprehensive blit (apply transformations) ***/ - int destRedShift = getChannelShift(destRedMask); - int destRedWidth = getChannelWidth(destRedMask, destRedShift); - byte[] destReds = ANY_TO_EIGHT[destRedWidth]; - int destRedPreShift = 8 - destRedWidth; - int destGreenShift = getChannelShift(destGreenMask); - int destGreenWidth = getChannelWidth(destGreenMask, destGreenShift); - byte[] destGreens = ANY_TO_EIGHT[destGreenWidth]; - int destGreenPreShift = 8 - destGreenWidth; - int destBlueShift = getChannelShift(destBlueMask); - int destBlueWidth = getChannelWidth(destBlueMask, destBlueShift); - byte[] destBlues = ANY_TO_EIGHT[destBlueWidth]; - int destBluePreShift = 8 - destBlueWidth; - int destAlphaShift = getChannelShift(destAlphaMask); - int destAlphaWidth = getChannelWidth(destAlphaMask, destAlphaShift); - byte[] destAlphas = ANY_TO_EIGHT[destAlphaWidth]; - int destAlphaPreShift = 8 - destAlphaWidth; + /*** Comprehensive blit (apply transformations) ***/ + int destRedShift = getChannelShift(destRedMask); + int destRedWidth = getChannelWidth(destRedMask, destRedShift); + byte[] destReds = ANY_TO_EIGHT[destRedWidth]; + int destRedPreShift = 8 - destRedWidth; + int destGreenShift = getChannelShift(destGreenMask); + int destGreenWidth = getChannelWidth(destGreenMask, destGreenShift); + byte[] destGreens = ANY_TO_EIGHT[destGreenWidth]; + int destGreenPreShift = 8 - destGreenWidth; + int destBlueShift = getChannelShift(destBlueMask); + int destBlueWidth = getChannelWidth(destBlueMask, destBlueShift); + byte[] destBlues = ANY_TO_EIGHT[destBlueWidth]; + int destBluePreShift = 8 - destBlueWidth; + int destAlphaShift = getChannelShift(destAlphaMask); + int destAlphaWidth = getChannelWidth(destAlphaMask, destAlphaShift); + byte[] destAlphas = ANY_TO_EIGHT[destAlphaWidth]; + int destAlphaPreShift = 8 - destAlphaWidth; - int dp = dpr; - int sp = spr; - int ap = apr, alpha = alphaMode; - int r = 0, g = 0, b = 0, a = 0, index = 0; - int rq = 0, gq = 0, bq = 0, aq = 0; - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, - sp = spr += (sfy >>> 16) * srcStride, - ap = apr += (sfy >>> 16) * alphaStride, - sfy = (sfy & 0xffff) + sfyi, - dp = dpr += dpryi) { - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, - dp += dprxi, - sfx = (sfx & 0xffff) + sfxi) { - /*** READ NEXT PIXEL ***/ - switch (stype) { - case TYPE_INDEX_8: - index = srcData[sp] & 0xff; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_4: - if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; - else index = (srcData[sp >> 1] >>> 4) & 0x0f; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_2: - index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_MSB: - index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; - sp += (sfx >>> 16); - break; - case TYPE_INDEX_1_LSB: - index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; - sp += (sfx >>> 16); - break; + int dp = dpr; + int sp = spr; + int ap = apr, alpha = alphaMode; + int r = 0, g = 0, b = 0, a = 0, index = 0; + int rq = 0, gq = 0, bq = 0, aq = 0; + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, + sp = spr += (sfy >>> 16) * srcStride, + ap = apr += (sfy >>> 16) * alphaStride, + sfy = (sfy & 0xffff) + sfyi, + dp = dpr += dpryi) { + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, + dp += dprxi, + sfx = (sfx & 0xffff) + sfxi) { + /*** READ NEXT PIXEL ***/ + switch (stype) { + case TYPE_INDEX_8: + index = srcData[sp] & 0xff; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_4: + if ((sp & 1) != 0) index = srcData[sp >> 1] & 0x0f; + else index = (srcData[sp >> 1] >>> 4) & 0x0f; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_2: + index = (srcData[sp >> 2] >>> (6 - (sp & 3) * 2)) & 0x03; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_MSB: + index = (srcData[sp >> 3] >>> (7 - (sp & 7))) & 0x01; + sp += (sfx >>> 16); + break; + case TYPE_INDEX_1_LSB: + index = (srcData[sp >> 3] >>> (sp & 7)) & 0x01; + sp += (sfx >>> 16); + break; default: - } + } - /*** DO SPECIAL PROCESSING IF REQUIRED ***/ - r = srcReds[index] & 0xff; - g = srcGreens[index] & 0xff; - b = srcBlues[index] & 0xff; - switch (alphaMode) { - case ALPHA_CHANNEL_SEPARATE: - alpha = ((alphaData[ap] & 0xff) << 16) / 255; - ap += (sfx >> 16); - break; - case ALPHA_MASK_UNPACKED: - alpha = (alphaData[ap] != 0) ? 0x10000 : 0; - ap += (sfx >> 16); - break; - case ALPHA_MASK_PACKED: - alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; - ap += (sfx >> 16); - break; - case ALPHA_MASK_INDEX: { // could speed up using binary search if we sorted the indices - int i = 0; - while (i < alphaData.length) { - if (index == (alphaData[i] & 0xff)) break; - } - if (i < alphaData.length) continue; - } break; - case ALPHA_MASK_RGB: { - int i = 0; - while (i < alphaData.length) { - if ((r == (alphaData[i] & 0xff)) && - (g == (alphaData[i + 1] & 0xff)) && - (b == (alphaData[i + 2] & 0xff))) break; - i += 3; - } - if (i < alphaData.length) continue; - } break; + /*** DO SPECIAL PROCESSING IF REQUIRED ***/ + r = srcReds[index] & 0xff; + g = srcGreens[index] & 0xff; + b = srcBlues[index] & 0xff; + switch (alphaMode) { + case ALPHA_CHANNEL_SEPARATE: + alpha = ((alphaData[ap] & 0xff) << 16) / 255; + ap += (sfx >> 16); + break; + case ALPHA_MASK_UNPACKED: + alpha = (alphaData[ap] != 0) ? 0x10000 : 0; + ap += (sfx >> 16); + break; + case ALPHA_MASK_PACKED: + alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; + ap += (sfx >> 16); + break; + case ALPHA_MASK_INDEX: { // could speed up using binary search if we sorted the indices + int i = 0; + while (i < alphaData.length) { + if (index == (alphaData[i] & 0xff)) break; + } + if (i < alphaData.length) continue; + } break; + case ALPHA_MASK_RGB: { + int i = 0; + while (i < alphaData.length) { + if ((r == (alphaData[i] & 0xff)) && + (g == (alphaData[i + 1] & 0xff)) && + (b == (alphaData[i + 2] & 0xff))) break; + i += 3; + } + if (i < alphaData.length) continue; + } break; default: - } - if (alpha != 0x10000) { - if (alpha == 0x0000) continue; - switch (dtype) { - case TYPE_GENERIC_8: { - int data = destData[dp] & 0xff; - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_MSB: { - int data = ((destData[dp] & 0xff) << 8) | (destData[dp + 1] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_LSB: { - int data = ((destData[dp + 1] & 0xff) << 8) | (destData[dp] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_24: { - int data = (( ((destData[dp] & 0xff) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp + 2] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_MSB: { - int data = (( (( ((destData[dp] & 0xff) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp + 2] & 0xff)) << 8) | - (destData[dp + 3] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_LSB: { - int data = (( (( ((destData[dp + 3] & 0xff) << 8) | - (destData[dp + 2] & 0xff)) << 8) | - (destData[dp + 1] & 0xff)) << 8) | - (destData[dp] & 0xff); - rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; - gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; - bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; - aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; - } break; + } + if (alpha != 0x10000) { + if (alpha == 0x0000) continue; + switch (dtype) { + case TYPE_GENERIC_8: { + int data = destData[dp] & 0xff; + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_MSB: { + int data = ((destData[dp] & 0xff) << 8) | (destData[dp + 1] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_LSB: { + int data = ((destData[dp + 1] & 0xff) << 8) | (destData[dp] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_24: { + int data = (( ((destData[dp] & 0xff) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp + 2] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_MSB: { + int data = (( (( ((destData[dp] & 0xff) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp + 2] & 0xff)) << 8) | + (destData[dp + 3] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_LSB: { + int data = (( (( ((destData[dp + 3] & 0xff) << 8) | + (destData[dp + 2] & 0xff)) << 8) | + (destData[dp + 1] & 0xff)) << 8) | + (destData[dp] & 0xff); + rq = destReds[(data & destRedMask) >>> destRedShift] & 0xff; + gq = destGreens[(data & destGreenMask) >>> destGreenShift] & 0xff; + bq = destBlues[(data & destBlueMask) >>> destBlueShift] & 0xff; + aq = destAlphas[(data & destAlphaMask) >>> destAlphaShift] & 0xff; + } break; default: - } - // Perform alpha blending - a = aq + ((a - aq) * alpha >> 16); - r = rq + ((r - rq) * alpha >> 16); - g = gq + ((g - gq) * alpha >> 16); - b = bq + ((b - bq) * alpha >> 16); - } + } + // Perform alpha blending + a = aq + ((a - aq) * alpha >> 16); + r = rq + ((r - rq) * alpha >> 16); + g = gq + ((g - gq) * alpha >> 16); + b = bq + ((b - bq) * alpha >> 16); + } - /*** WRITE NEXT PIXEL ***/ - int data = - (r >>> destRedPreShift << destRedShift) | - (g >>> destGreenPreShift << destGreenShift) | - (b >>> destBluePreShift << destBlueShift) | - (a >>> destAlphaPreShift << destAlphaShift); - switch (dtype) { - case TYPE_GENERIC_8: { - destData[dp] = cast(byte) data; - } break; - case TYPE_GENERIC_16_MSB: { - destData[dp] = cast(byte) (data >>> 8); - destData[dp + 1] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_16_LSB: { - destData[dp] = cast(byte) (data & 0xff); - destData[dp + 1] = cast(byte) (data >>> 8); - } break; - case TYPE_GENERIC_24: { - destData[dp] = cast(byte) (data >>> 16); - destData[dp + 1] = cast(byte) (data >>> 8); - destData[dp + 2] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_32_MSB: { - destData[dp] = cast(byte) (data >>> 24); - destData[dp + 1] = cast(byte) (data >>> 16); - destData[dp + 2] = cast(byte) (data >>> 8); - destData[dp + 3] = cast(byte) (data & 0xff); - } break; - case TYPE_GENERIC_32_LSB: { - destData[dp] = cast(byte) (data & 0xff); - destData[dp + 1] = cast(byte) (data >>> 8); - destData[dp + 2] = cast(byte) (data >>> 16); - destData[dp + 3] = cast(byte) (data >>> 24); - } break; + /*** WRITE NEXT PIXEL ***/ + int data = + (r >>> destRedPreShift << destRedShift) | + (g >>> destGreenPreShift << destGreenShift) | + (b >>> destBluePreShift << destBlueShift) | + (a >>> destAlphaPreShift << destAlphaShift); + switch (dtype) { + case TYPE_GENERIC_8: { + destData[dp] = cast(byte) data; + } break; + case TYPE_GENERIC_16_MSB: { + destData[dp] = cast(byte) (data >>> 8); + destData[dp + 1] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_16_LSB: { + destData[dp] = cast(byte) (data & 0xff); + destData[dp + 1] = cast(byte) (data >>> 8); + } break; + case TYPE_GENERIC_24: { + destData[dp] = cast(byte) (data >>> 16); + destData[dp + 1] = cast(byte) (data >>> 8); + destData[dp + 2] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_32_MSB: { + destData[dp] = cast(byte) (data >>> 24); + destData[dp + 1] = cast(byte) (data >>> 16); + destData[dp + 2] = cast(byte) (data >>> 8); + destData[dp + 3] = cast(byte) (data & 0xff); + } break; + case TYPE_GENERIC_32_LSB: { + destData[dp] = cast(byte) (data & 0xff); + destData[dp + 1] = cast(byte) (data >>> 8); + destData[dp + 2] = cast(byte) (data >>> 16); + destData[dp + 3] = cast(byte) (data >>> 24); + } break; default: - } - } - } + } + } + } } /** @@ -3069,364 +3069,364 @@ * @param flipY if true the resulting image is flipped along the horizontal axis */ static void blit(int op, - byte[] srcData, int srcDepth, int srcStride, int srcOrder, - int srcX, int srcY, int srcWidth, int srcHeight, - int srcRedMask, int srcGreenMask, int srcBlueMask, - int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, - byte[] destData, int destDepth, int destStride, int destOrder, - int destX, int destY, int destWidth, int destHeight, - byte[] destReds, byte[] destGreens, byte[] destBlues, - bool flipX, bool flipY) { - if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; + byte[] srcData, int srcDepth, int srcStride, int srcOrder, + int srcX, int srcY, int srcWidth, int srcHeight, + int srcRedMask, int srcGreenMask, int srcBlueMask, + int alphaMode, byte[] alphaData, int alphaStride, int alphaX, int alphaY, + byte[] destData, int destDepth, int destStride, int destOrder, + int destX, int destY, int destWidth, int destHeight, + byte[] destReds, byte[] destGreens, byte[] destBlues, + bool flipX, bool flipY) { + if ((destWidth <= 0) || (destHeight <= 0) || (alphaMode == ALPHA_TRANSPARENT)) return; - // these should be supplied as params later - int srcAlphaMask = 0; + // these should be supplied as params later + int srcAlphaMask = 0; - /*** Prepare scaling data ***/ - int dwm1 = destWidth - 1; - int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; - int dhm1 = destHeight - 1; - int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; + /*** Prepare scaling data ***/ + int dwm1 = destWidth - 1; + int sfxi = (dwm1 != 0) ? cast(int)(((cast(long)srcWidth << 16) - 1) / dwm1) : 0; + int dhm1 = destHeight - 1; + int sfyi = (dhm1 != 0) ? cast(int)(((cast(long)srcHeight << 16) - 1) / dhm1) : 0; - /*** Prepare source-related data ***/ - int sbpp, stype; - switch (srcDepth) { - case 8: - sbpp = 1; - stype = TYPE_GENERIC_8; - break; - case 16: - sbpp = 2; - stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; - break; - case 24: - sbpp = 3; - stype = TYPE_GENERIC_24; - break; - case 32: - sbpp = 4; - stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int spr = srcY * srcStride + srcX * sbpp; + /*** Prepare source-related data ***/ + int sbpp, stype; + switch (srcDepth) { + case 8: + sbpp = 1; + stype = TYPE_GENERIC_8; + break; + case 16: + sbpp = 2; + stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_16_MSB : TYPE_GENERIC_16_LSB; + break; + case 24: + sbpp = 3; + stype = TYPE_GENERIC_24; + break; + case 32: + sbpp = 4; + stype = (srcOrder == MSB_FIRST) ? TYPE_GENERIC_32_MSB : TYPE_GENERIC_32_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int spr = srcY * srcStride + srcX * sbpp; - /*** Prepare destination-related data ***/ - int dtype; - switch (destDepth) { - case 8: - dtype = TYPE_INDEX_8; - break; - case 4: - destStride <<= 1; - dtype = TYPE_INDEX_4; - break; - case 2: - destStride <<= 2; - dtype = TYPE_INDEX_2; - break; - case 1: - destStride <<= 3; - dtype = (destOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; - break; - default: - //throw new IllegalArgumentException("Invalid source type"); - return; - } - int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX); - int dprxi = (flipX) ? -1 : 1; - int dpryi = (flipY) ? -destStride : destStride; + /*** Prepare destination-related data ***/ + int dtype; + switch (destDepth) { + case 8: + dtype = TYPE_INDEX_8; + break; + case 4: + destStride <<= 1; + dtype = TYPE_INDEX_4; + break; + case 2: + destStride <<= 2; + dtype = TYPE_INDEX_2; + break; + case 1: + destStride <<= 3; + dtype = (destOrder == MSB_FIRST) ? TYPE_INDEX_1_MSB : TYPE_INDEX_1_LSB; + break; + default: + //throw new IllegalArgumentException("Invalid source type"); + return; + } + int dpr = ((flipY) ? destY + dhm1 : destY) * destStride + ((flipX) ? destX + dwm1 : destX); + int dprxi = (flipX) ? -1 : 1; + int dpryi = (flipY) ? -destStride : destStride; - /*** Prepare special processing data ***/ - int apr; - if ((op & BLIT_ALPHA) != 0) { - switch (alphaMode) { - case ALPHA_MASK_UNPACKED: - case ALPHA_CHANNEL_SEPARATE: - if (alphaData == null) alphaMode = 0x10000; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_PACKED: - if (alphaData == null) alphaMode = 0x10000; - alphaStride <<= 3; - apr = alphaY * alphaStride + alphaX; - break; - case ALPHA_MASK_INDEX: - //throw new IllegalArgumentException("Invalid alpha type"); - return; - case ALPHA_MASK_RGB: - if (alphaData == null) alphaMode = 0x10000; - apr = 0; - break; - default: - alphaMode = (alphaMode << 16) / 255; // prescale - case ALPHA_CHANNEL_SOURCE: - apr = 0; - break; - } - } else { - alphaMode = 0x10000; - apr = 0; - } - bool ditherEnabled = (op & BLIT_DITHER) != 0; + /*** Prepare special processing data ***/ + int apr; + if ((op & BLIT_ALPHA) != 0) { + switch (alphaMode) { + case ALPHA_MASK_UNPACKED: + case ALPHA_CHANNEL_SEPARATE: + if (alphaData == null) alphaMode = 0x10000; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_PACKED: + if (alphaData == null) alphaMode = 0x10000; + alphaStride <<= 3; + apr = alphaY * alphaStride + alphaX; + break; + case ALPHA_MASK_INDEX: + //throw new IllegalArgumentException("Invalid alpha type"); + return; + case ALPHA_MASK_RGB: + if (alphaData == null) alphaMode = 0x10000; + apr = 0; + break; + default: + alphaMode = (alphaMode << 16) / 255; // prescale + case ALPHA_CHANNEL_SOURCE: + apr = 0; + break; + } + } else { + alphaMode = 0x10000; + apr = 0; + } + bool ditherEnabled = (op & BLIT_DITHER) != 0; - /*** Comprehensive blit (apply transformations) ***/ - int srcRedShift = getChannelShift(srcRedMask); - byte[] srcReds = ANY_TO_EIGHT[getChannelWidth(srcRedMask, srcRedShift)]; - int srcGreenShift = getChannelShift(srcGreenMask); - byte[] srcGreens = ANY_TO_EIGHT[getChannelWidth(srcGreenMask, srcGreenShift)]; - int srcBlueShift = getChannelShift(srcBlueMask); - byte[] srcBlues = ANY_TO_EIGHT[getChannelWidth(srcBlueMask, srcBlueShift)]; - int srcAlphaShift = getChannelShift(srcAlphaMask); - byte[] srcAlphas = ANY_TO_EIGHT[getChannelWidth(srcAlphaMask, srcAlphaShift)]; + /*** Comprehensive blit (apply transformations) ***/ + int srcRedShift = getChannelShift(srcRedMask); + byte[] srcReds = ANY_TO_EIGHT[getChannelWidth(srcRedMask, srcRedShift)]; + int srcGreenShift = getChannelShift(srcGreenMask); + byte[] srcGreens = ANY_TO_EIGHT[getChannelWidth(srcGreenMask, srcGreenShift)]; + int srcBlueShift = getChannelShift(srcBlueMask); + byte[] srcBlues = ANY_TO_EIGHT[getChannelWidth(srcBlueMask, srcBlueShift)]; + int srcAlphaShift = getChannelShift(srcAlphaMask); + byte[] srcAlphas = ANY_TO_EIGHT[getChannelWidth(srcAlphaMask, srcAlphaShift)]; - int dp = dpr; - int sp = spr; - int ap = apr, alpha = alphaMode; - int r = 0, g = 0, b = 0, a = 0; - int indexq = 0; - int lastindex = 0, lastr = -1, lastg = -1, lastb = -1; - int[] rerr, gerr, berr; - int destPaletteSize = 1 << destDepth; - if ((destReds != null) && (destReds.length < destPaletteSize)) destPaletteSize = destReds.length; - if (ditherEnabled) { - rerr = new int[destWidth + 2]; - gerr = new int[destWidth + 2]; - berr = new int[destWidth + 2]; - } else { - rerr = null; gerr = null; berr = null; - } - for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, - sp = spr += (sfy >>> 16) * srcStride, - ap = apr += (sfy >>> 16) * alphaStride, - sfy = (sfy & 0xffff) + sfyi, - dp = dpr += dpryi) { - int lrerr = 0, lgerr = 0, lberr = 0; - for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, - dp += dprxi, - sfx = (sfx & 0xffff) + sfxi) { - /*** READ NEXT PIXEL ***/ - switch (stype) { - case TYPE_GENERIC_8: { - int data = srcData[sp] & 0xff; - sp += (sfx >>> 16); - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_MSB: { - int data = ((srcData[sp] & 0xff) << 8) | (srcData[sp + 1] & 0xff); - sp += (sfx >>> 16) * 2; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_16_LSB: { - int data = ((srcData[sp + 1] & 0xff) << 8) | (srcData[sp] & 0xff); - sp += (sfx >>> 16) * 2; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_24: { - int data = (( ((srcData[sp] & 0xff) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp + 2] & 0xff); - sp += (sfx >>> 16) * 3; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_MSB: { - int data = (( (( ((srcData[sp] & 0xff) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp + 2] & 0xff)) << 8) | - (srcData[sp + 3] & 0xff); - sp += (sfx >>> 16) * 4; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; - case TYPE_GENERIC_32_LSB: { - int data = (( (( ((srcData[sp + 3] & 0xff) << 8) | - (srcData[sp + 2] & 0xff)) << 8) | - (srcData[sp + 1] & 0xff)) << 8) | - (srcData[sp] & 0xff); - sp += (sfx >>> 16) * 4; - r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; - g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; - b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; - a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; - } break; + int dp = dpr; + int sp = spr; + int ap = apr, alpha = alphaMode; + int r = 0, g = 0, b = 0, a = 0; + int indexq = 0; + int lastindex = 0, lastr = -1, lastg = -1, lastb = -1; + int[] rerr, gerr, berr; + int destPaletteSize = 1 << destDepth; + if ((destReds != null) && (destReds.length < destPaletteSize)) destPaletteSize = destReds.length; + if (ditherEnabled) { + rerr = new int[destWidth + 2]; + gerr = new int[destWidth + 2]; + berr = new int[destWidth + 2]; + } else { + rerr = null; gerr = null; berr = null; + } + for (int dy = destHeight, sfy = sfyi; dy > 0; --dy, + sp = spr += (sfy >>> 16) * srcStride, + ap = apr += (sfy >>> 16) * alphaStride, + sfy = (sfy & 0xffff) + sfyi, + dp = dpr += dpryi) { + int lrerr = 0, lgerr = 0, lberr = 0; + for (int dx = destWidth, sfx = sfxi; dx > 0; --dx, + dp += dprxi, + sfx = (sfx & 0xffff) + sfxi) { + /*** READ NEXT PIXEL ***/ + switch (stype) { + case TYPE_GENERIC_8: { + int data = srcData[sp] & 0xff; + sp += (sfx >>> 16); + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_MSB: { + int data = ((srcData[sp] & 0xff) << 8) | (srcData[sp + 1] & 0xff); + sp += (sfx >>> 16) * 2; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_16_LSB: { + int data = ((srcData[sp + 1] & 0xff) << 8) | (srcData[sp] & 0xff); + sp += (sfx >>> 16) * 2; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_24: { + int data = (( ((srcData[sp] & 0xff) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp + 2] & 0xff); + sp += (sfx >>> 16) * 3; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_MSB: { + int data = (( (( ((srcData[sp] & 0xff) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp + 2] & 0xff)) << 8) | + (srcData[sp + 3] & 0xff); + sp += (sfx >>> 16) * 4; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; + case TYPE_GENERIC_32_LSB: { + int data = (( (( ((srcData[sp + 3] & 0xff) << 8) | + (srcData[sp + 2] & 0xff)) << 8) | + (srcData[sp + 1] & 0xff)) << 8) | + (srcData[sp] & 0xff); + sp += (sfx >>> 16) * 4; + r = srcReds[(data & srcRedMask) >>> srcRedShift] & 0xff; + g = srcGreens[(data & srcGreenMask) >>> srcGreenShift] & 0xff; + b = srcBlues[(data & srcBlueMask) >>> srcBlueShift] & 0xff; + a = srcAlphas[(data & srcAlphaMask) >>> srcAlphaShift] & 0xff; + } break; default: - } + } - /*** DO SPECIAL PROCESSING IF REQUIRED ***/ - switch (alphaMode) { - case ALPHA_CHANNEL_SEPARATE: - alpha = ((alphaData[ap] & 0xff) << 16) / 255; - ap += (sfx >> 16); - break; - case ALPHA_CHANNEL_SOURCE: - alpha = (a << 16) / 255; - break; - case ALPHA_MASK_UNPACKED: - alpha = (alphaData[ap] != 0) ? 0x10000 : 0; - ap += (sfx >> 16); - break; - case ALPHA_MASK_PACKED: - alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; - ap += (sfx >> 16); - break; - case ALPHA_MASK_RGB: - alpha = 0x10000; - for (int i = 0; i < alphaData.length; i += 3) { - if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) { - alpha = 0x0000; - break; - } - } - break; + /*** DO SPECIAL PROCESSING IF REQUIRED ***/ + switch (alphaMode) { + case ALPHA_CHANNEL_SEPARATE: + alpha = ((alphaData[ap] & 0xff) << 16) / 255; + ap += (sfx >> 16); + break; + case ALPHA_CHANNEL_SOURCE: + alpha = (a << 16) / 255; + break; + case ALPHA_MASK_UNPACKED: + alpha = (alphaData[ap] != 0) ? 0x10000 : 0; + ap += (sfx >> 16); + break; + case ALPHA_MASK_PACKED: + alpha = (alphaData[ap >> 3] << ((ap & 7) + 9)) & 0x10000; + ap += (sfx >> 16); + break; + case ALPHA_MASK_RGB: + alpha = 0x10000; + for (int i = 0; i < alphaData.length; i += 3) { + if ((r == alphaData[i]) && (g == alphaData[i + 1]) && (b == alphaData[i + 2])) { + alpha = 0x0000; + break; + } + } + break; default: - } - if (alpha != 0x10000) { - if (alpha == 0x0000) continue; - switch (dtype) { - case TYPE_INDEX_8: - indexq = destData[dp] & 0xff; - break; - case TYPE_INDEX_4: - if ((dp & 1) != 0) indexq = destData[dp >> 1] & 0x0f; - else indexq = (destData[dp >> 1] >>> 4) & 0x0f; - break; - case TYPE_INDEX_2: - indexq = (destData[dp >> 2] >>> (6 - (dp & 3) * 2)) & 0x03; - break; - case TYPE_INDEX_1_MSB: - indexq = (destData[dp >> 3] >>> (7 - (dp & 7))) & 0x01; - break; - case TYPE_INDEX_1_LSB: - indexq = (destData[dp >> 3] >>> (dp & 7)) & 0x01; - break; + } + if (alpha != 0x10000) { + if (alpha == 0x0000) continue; + switch (dtype) { + case TYPE_INDEX_8: + indexq = destData[dp] & 0xff; + break; + case TYPE_INDEX_4: + if ((dp & 1) != 0) indexq = destData[dp >> 1] & 0x0f; + else indexq = (destData[dp >> 1] >>> 4) & 0x0f; + break; + case TYPE_INDEX_2: + indexq = (destData[dp >> 2] >>> (6 - (dp & 3) * 2)) & 0x03; + break; + case TYPE_INDEX_1_MSB: + indexq = (destData[dp >> 3] >>> (7 - (dp & 7))) & 0x01; + break; + case TYPE_INDEX_1_LSB: + indexq = (destData[dp >> 3] >>> (dp & 7)) & 0x01; + break; default: - } - // Perform alpha blending - int rq = destReds[indexq] & 0xff; - int gq = destGreens[indexq] & 0xff; - int bq = destBlues[indexq] & 0xff; - r = rq + ((r - rq) * alpha >> 16); - g = gq + ((g - gq) * alpha >> 16); - b = bq + ((b - bq) * alpha >> 16); - } + } + // Perform alpha blending + int rq = destReds[indexq] & 0xff; + int gq = destGreens[indexq] & 0xff; + int bq = destBlues[indexq] & 0xff; + r = rq + ((r - rq) * alpha >> 16); + g = gq + ((g - gq) * alpha >> 16); + b = bq + ((b - bq) * alpha >> 16); + } - /*** MAP COLOR TO THE PALETTE ***/ - if (ditherEnabled) { - // Floyd-Steinberg error diffusion - r += rerr[dx] >> 4; - if (r < 0) r = 0; else if (r > 255) r = 255; - g += gerr[dx] >> 4; - if (g < 0) g = 0; else if (g > 255) g = 255; - b += berr[dx] >> 4; - if (b < 0) b = 0; else if (b > 255) b = 255; - rerr[dx] = lrerr; - gerr[dx] = lgerr; - berr[dx] = lberr; - } - if (r != lastr || g != lastg || b != lastb) { - // moving the variable declarations out seems to make the JDK JIT happier... - for (int j = 0, dr, dg, db, distance, minDistance = 0x7fffffff; j < destPaletteSize; ++j) { - dr = (destReds[j] & 0xff) - r; - dg = (destGreens[j] & 0xff) - g; - db = (destBlues[j] & 0xff) - b; - distance = dr * dr + dg * dg + db * db; - if (distance < minDistance) { - lastindex = j; - if (distance == 0) break; - minDistance = distance; - } - } - lastr = r; lastg = g; lastb = b; - } - if (ditherEnabled) { - // Floyd-Steinberg error diffusion, cont'd... - int dxm1 = dx - 1, dxp1 = dx + 1; - int acc; - rerr[dxp1] += acc = (lrerr = r - (destReds[lastindex] & 0xff)) + lrerr + lrerr; - rerr[dx] += acc += lrerr + lrerr; - rerr[dxm1] += acc + lrerr + lrerr; - gerr[dxp1] += acc = (lgerr = g - (destGreens[lastindex] & 0xff)) + lgerr + lgerr; - gerr[dx] += acc += lgerr + lgerr; - gerr[dxm1] += acc + lgerr + lgerr; - berr[dxp1] += acc = (lberr = b - (destBlues[lastindex] & 0xff)) + lberr + lberr; - berr[dx] += acc += lberr + lberr; - berr[dxm1] += acc + lberr + lberr; - } + /*** MAP COLOR TO THE PALETTE ***/ + if (ditherEnabled) { + // Floyd-Steinberg error diffusion + r += rerr[dx] >> 4; + if (r < 0) r = 0; else if (r > 255) r = 255; + g += gerr[dx] >> 4; + if (g < 0) g = 0; else if (g > 255) g = 255; + b += berr[dx] >> 4; + if (b < 0) b = 0; else if (b > 255) b = 255; + rerr[dx] = lrerr; + gerr[dx] = lgerr; + berr[dx] = lberr; + } + if (r != lastr || g != lastg || b != lastb) { + // moving the variable declarations out seems to make the JDK JIT happier... + for (int j = 0, dr, dg, db, distance, minDistance = 0x7fffffff; j < destPaletteSize; ++j) { + dr = (destReds[j] & 0xff) - r; + dg = (destGreens[j] & 0xff) - g; + db = (destBlues[j] & 0xff) - b; + distance = dr * dr + dg * dg + db * db; + if (distance < minDistance) { + lastindex = j; + if (distance == 0) break; + minDistance = distance; + } + } + lastr = r; lastg = g; lastb = b; + } + if (ditherEnabled) { + // Floyd-Steinberg error diffusion, cont'd... + int dxm1 = dx - 1, dxp1 = dx + 1; + int acc; + rerr[dxp1] += acc = (lrerr = r - (destReds[lastindex] & 0xff)) + lrerr + lrerr; + rerr[dx] += acc += lrerr + lrerr; + rerr[dxm1] += acc + lrerr + lrerr; + gerr[dxp1] += acc = (lgerr = g - (destGreens[lastindex] & 0xff)) + lgerr + lgerr; + gerr[dx] += acc += lgerr + lgerr; + gerr[dxm1] += acc + lgerr + lgerr; + berr[dxp1] += acc = (lberr = b - (destBlues[lastindex] & 0xff)) + lberr + lberr; + berr[dx] += acc += lberr + lberr; + berr[dxm1] += acc + lberr + lberr; + } - /*** WRITE NEXT PIXEL ***/ - switch (dtype) { - case TYPE_INDEX_8: - destData[dp] = cast(byte) lastindex; - break; - case TYPE_INDEX_4: - if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | lastindex); - else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (lastindex << 4)); - break; - case TYPE_INDEX_2: { - int shift = 6 - (dp & 3) * 2; - destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (lastindex << shift)); - } break; - case TYPE_INDEX_1_MSB: { - int shift = 7 - (dp & 7); - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); - } break; - case TYPE_INDEX_1_LSB: { - int shift = dp & 7; - destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); - } break; + /*** WRITE NEXT PIXEL ***/ + switch (dtype) { + case TYPE_INDEX_8: + destData[dp] = cast(byte) lastindex; + break; + case TYPE_INDEX_4: + if ((dp & 1) != 0) destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0xf0) | lastindex); + else destData[dp >> 1] = cast(byte)((destData[dp >> 1] & 0x0f) | (lastindex << 4)); + break; + case TYPE_INDEX_2: { + int shift = 6 - (dp & 3) * 2; + destData[dp >> 2] = cast(byte)(destData[dp >> 2] & ~(0x03 << shift) | (lastindex << shift)); + } break; + case TYPE_INDEX_1_MSB: { + int shift = 7 - (dp & 7); + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); + } break; + case TYPE_INDEX_1_LSB: { + int shift = dp & 7; + destData[dp >> 3] = cast(byte)(destData[dp >> 3] & ~(0x01 << shift) | (lastindex << shift)); + } break; default: - } - } - } + } + } + } } /** * Computes the required channel shift from a mask. */ static int getChannelShift(int mask) { - if (mask == 0) return 0; - int i; - for (i = 0; ((mask & 1) == 0) && (i < 32); ++i) { - mask >>>= 1; - } - return i; + if (mask == 0) return 0; + int i; + for (i = 0; ((mask & 1) == 0) && (i < 32); ++i) { + mask >>>= 1; + } + return i; } /** * Computes the required channel width (depth) from a mask. */ static int getChannelWidth(int mask, int shift) { - if (mask == 0) return 0; - int i; - mask >>>= shift; - for (i = shift; ((mask & 1) != 0) && (i < 32); ++i) { - mask >>>= 1; - } - return i - shift; + if (mask == 0) return 0; + int i; + mask >>>= shift; + for (i = shift; ((mask & 1) != 0) && (i < 32); ++i) { + mask >>>= 1; + } + return i - shift; } /** * Extracts a field from packed RGB data given a mask for that field. */ static byte getChannelField(int data, int mask) { - int shift = getChannelShift(mask); - return ANY_TO_EIGHT[getChannelWidth(mask, shift)][(data & mask) >>> shift]; + int shift = getChannelShift(mask); + return ANY_TO_EIGHT[getChannelWidth(mask, shift)][(data & mask) >>> shift]; } /** @@ -3446,139 +3446,139 @@ * @return the new ImageData */ static ImageData createGradientBand( - int width, int height, bool vertical, - RGB fromRGB, RGB toRGB, - int redBits, int greenBits, int blueBits) { - /* Gradients are drawn as tiled bands */ - int bandWidth, bandHeight, bitmapDepth; - byte[] bitmapData; - PaletteData paletteData; - /* Select an algorithm depending on the depth of the screen */ - if (redBits != 0 && greenBits != 0 && blueBits != 0) { - paletteData = new PaletteData(0x0000ff00, 0x00ff0000, 0xff000000); - bitmapDepth = 32; - if (redBits >= 8 && greenBits >= 8 && blueBits >= 8) { - /* Precise color */ - int steps; - if (vertical) { - bandWidth = 1; - bandHeight = height; - steps = bandHeight > 1 ? bandHeight - 1 : 1; - } else { - bandWidth = width; - bandHeight = 1; - steps = bandWidth > 1 ? bandWidth - 1 : 1; - } - int bytesPerLine = bandWidth * 4; - bitmapData = new byte[bandHeight * bytesPerLine]; - buildPreciseGradientChannel(fromRGB.blue, toRGB.blue, steps, bandWidth, bandHeight, vertical, bitmapData, 0, bytesPerLine); - buildPreciseGradientChannel(fromRGB.green, toRGB.green, steps, bandWidth, bandHeight, vertical, bitmapData, 1, bytesPerLine); - buildPreciseGradientChannel(fromRGB.red, toRGB.red, steps, bandWidth, bandHeight, vertical, bitmapData, 2, bytesPerLine); - } else { - /* Dithered color */ - int steps; - if (vertical) { - bandWidth = (width < 8) ? width : 8; - bandHeight = height; - steps = bandHeight > 1 ? bandHeight - 1 : 1; - } else { - bandWidth = width; - bandHeight = (height < 8) ? height : 8; - steps = bandWidth > 1 ? bandWidth - 1 : 1; - } - int bytesPerLine = bandWidth * 4; - bitmapData = new byte[bandHeight * bytesPerLine]; - buildDitheredGradientChannel(fromRGB.blue, toRGB.blue, steps, bandWidth, bandHeight, vertical, bitmapData, 0, bytesPerLine, blueBits); - buildDitheredGradientChannel(fromRGB.green, toRGB.green, steps, bandWidth, bandHeight, vertical, bitmapData, 1, bytesPerLine, greenBits); - buildDitheredGradientChannel(fromRGB.red, toRGB.red, steps, bandWidth, bandHeight, vertical, bitmapData, 2, bytesPerLine, redBits); - } - } else { - /* Dithered two tone */ - paletteData = new PaletteData([ fromRGB, toRGB ]); - bitmapDepth = 8; - int blendi; - if (vertical) { - bandWidth = (width < 8) ? width : 8; - bandHeight = height; - blendi = (bandHeight > 1) ? 0x1040000 / (bandHeight - 1) + 1 : 1; - } else { - bandWidth = width; - bandHeight = (height < 8) ? height : 8; - blendi = (bandWidth > 1) ? 0x1040000 / (bandWidth - 1) + 1 : 1; - } - int bytesPerLine = (bandWidth + 3) & -4; - bitmapData = new byte[bandHeight * bytesPerLine]; - if (vertical) { - for (int dy = 0, blend = 0, dp = 0; dy < bandHeight; - ++dy, blend += blendi, dp += bytesPerLine) { - for (int dx = 0; dx < bandWidth; ++dx) { - bitmapData[dp + dx] = (blend + DITHER_MATRIX[dy & 7][dx]) < - 0x1000000 ? cast(byte)0 : cast(byte)1; - } - } - } else { - for (int dx = 0, blend = 0; dx < bandWidth; ++dx, blend += blendi) { - for (int dy = 0, dptr = dx; dy < bandHeight; ++dy, dptr += bytesPerLine) { - bitmapData[dptr] = (blend + DITHER_MATRIX[dy][dx & 7]) < - 0x1000000 ? cast(byte)0 : cast(byte)1; - } - } - } - } - return new ImageData(bandWidth, bandHeight, bitmapDepth, paletteData, 4, bitmapData); + int width, int height, bool vertical, + RGB fromRGB, RGB toRGB, + int redBits, int greenBits, int blueBits) { + /* Gradients are drawn as tiled bands */ + int bandWidth, bandHeight, bitmapDepth; + byte[] bitmapData; + PaletteData paletteData; + /* Select an algorithm depending on the depth of the screen */ + if (redBits != 0 && greenBits != 0 && blueBits != 0) { + paletteData = new PaletteData(0x0000ff00, 0x00ff0000, 0xff000000); + bitmapDepth = 32; + if (redBits >= 8 && greenBits >= 8 && blueBits >= 8) { + /* Precise color */ + int steps; + if (vertical) { + bandWidth = 1; + bandHeight = height; + steps = bandHeight > 1 ? bandHeight - 1 : 1; + } else { + bandWidth = width; + bandHeight = 1; + steps = bandWidth > 1 ? bandWidth - 1 : 1; + } + int bytesPerLine = bandWidth * 4; + bitmapData = new byte[bandHeight * bytesPerLine]; + buildPreciseGradientChannel(fromRGB.blue, toRGB.blue, steps, bandWidth, bandHeight, vertical, bitmapData, 0, bytesPerLine); + buildPreciseGradientChannel(fromRGB.green, toRGB.green, steps, bandWidth, bandHeight, vertical, bitmapData, 1, bytesPerLine); + buildPreciseGradientChannel(fromRGB.red, toRGB.red, steps, bandWidth, bandHeight, vertical, bitmapData, 2, bytesPerLine); + } else { + /* Dithered color */ + int steps; + if (vertical) { + bandWidth = (width < 8) ? width : 8; + bandHeight = height; + steps = bandHeight > 1 ? bandHeight - 1 : 1; + } else { + bandWidth = width; + bandHeight = (height < 8) ? height : 8; + steps = bandWidth > 1 ? bandWidth - 1 : 1; + } + int bytesPerLine = bandWidth * 4; + bitmapData = new byte[bandHeight * bytesPerLine]; + buildDitheredGradientChannel(fromRGB.blue, toRGB.blue, steps, bandWidth, bandHeight, vertical, bitmapData, 0, bytesPerLine, blueBits); + buildDitheredGradientChannel(fromRGB.green, toRGB.green, steps, bandWidth, bandHeight, vertical, bitmapData, 1, bytesPerLine, greenBits); + buildDitheredGradientChannel(fromRGB.red, toRGB.red, steps, bandWidth, bandHeight, vertical, bitmapData, 2, bytesPerLine, redBits); + } + } else { + /* Dithered two tone */ + paletteData = new PaletteData([ fromRGB, toRGB ]); + bitmapDepth = 8; + int blendi; + if (vertical) { + bandWidth = (width < 8) ? width : 8; + bandHeight = height; + blendi = (bandHeight > 1) ? 0x1040000 / (bandHeight - 1) + 1 : 1; + } else { + bandWidth = width; + bandHeight = (height < 8) ? height : 8; + blendi = (bandWidth > 1) ? 0x1040000 / (bandWidth - 1) + 1 : 1; + } + int bytesPerLine = (bandWidth + 3) & -4; + bitmapData = new byte[bandHeight * bytesPerLine]; + if (vertical) { + for (int dy = 0, blend = 0, dp = 0; dy < bandHeight; + ++dy, blend += blendi, dp += bytesPerLine) { + for (int dx = 0; dx < bandWidth; ++dx) { + bitmapData[dp + dx] = (blend + DITHER_MATRIX[dy & 7][dx]) < + 0x1000000 ? cast(byte)0 : cast(byte)1; + } + } + } else { + for (int dx = 0, blend = 0; dx < bandWidth; ++dx, blend += blendi) { + for (int dy = 0, dptr = dx; dy < bandHeight; ++dy, dptr += bytesPerLine) { + bitmapData[dptr] = (blend + DITHER_MATRIX[dy][dx & 7]) < + 0x1000000 ? cast(byte)0 : cast(byte)1; + } + } + } + } + return new ImageData(bandWidth, bandHeight, bitmapDepth, paletteData, 4, bitmapData); } /* * Fill in gradated values for a color channel */ static final void buildPreciseGradientChannel(int from, int to, int steps, - int bandWidth, int bandHeight, bool vertical, - byte[] bitmapData, int dp, int bytesPerLine) { - int val = from << 16; - int inc = ((to << 16) - val) / steps + 1; - if (vertical) { - for (int dy = 0; dy < bandHeight; ++dy, dp += bytesPerLine) { - bitmapData[dp] = cast(byte)(val >>> 16); - val += inc; - } - } else { - for (int dx = 0; dx < bandWidth; ++dx, dp += 4) { - bitmapData[dp] = cast(byte)(val >>> 16); - val += inc; - } - } + int bandWidth, int bandHeight, bool vertical, + byte[] bitmapData, int dp, int bytesPerLine) { + int val = from << 16; + int inc = ((to << 16) - val) / steps + 1; + if (vertical) { + for (int dy = 0; dy < bandHeight; ++dy, dp += bytesPerLine) { + bitmapData[dp] = cast(byte)(val >>> 16); + val += inc; + } + } else { + for (int dx = 0; dx < bandWidth; ++dx, dp += 4) { + bitmapData[dp] = cast(byte)(val >>> 16); + val += inc; + } + } } /* * Fill in dithered gradated values for a color channel */ static final void buildDitheredGradientChannel(int from, int to, int steps, - int bandWidth, int bandHeight, bool vertical, - byte[] bitmapData, int dp, int bytesPerLine, int bits) { - int mask = 0xff00 >>> bits; - int val = from << 16; - int inc = ((to << 16) - val) / steps + 1; - if (vertical) { - for (int dy = 0; dy < bandHeight; ++dy, dp += bytesPerLine) { - for (int dx = 0, dptr = dp; dx < bandWidth; ++dx, dptr += 4) { - int thresh = DITHER_MATRIX[dy & 7][dx] >>> bits; - int temp = val + thresh; - if (temp > 0xffffff) bitmapData[dptr] = -1; - else bitmapData[dptr] = cast(byte)((temp >>> 16) & mask); - } - val += inc; - } - } else { - for (int dx = 0; dx < bandWidth; ++dx, dp += 4) { - for (int dy = 0, dptr = dp; dy < bandHeight; ++dy, dptr += bytesPerLine) { - int thresh = DITHER_MATRIX[dy][dx & 7] >>> bits; - int temp = val + thresh; - if (temp > 0xffffff) bitmapData[dptr] = -1; - else bitmapData[dptr] = cast(byte)((temp >>> 16) & mask); - } - val += inc; - } - } + int bandWidth, int bandHeight, bool vertical, + byte[] bitmapData, int dp, int bytesPerLine, int bits) { + int mask = 0xff00 >>> bits; + int val = from << 16; + int inc = ((to << 16) - val) / steps + 1; + if (vertical) { + for (int dy = 0; dy < bandHeight; ++dy, dp += bytesPerLine) { + for (int dx = 0, dptr = dp; dx < bandWidth; ++dx, dptr += 4) { + int thresh = DITHER_MATRIX[dy & 7][dx] >>> bits; + int temp = val + thresh; + if (temp > 0xffffff) bitmapData[dptr] = -1; + else bitmapData[dptr] = cast(byte)((temp >>> 16) & mask); + } + val += inc; + } + } else { + for (int dx = 0; dx < bandWidth; ++dx, dp += 4) { + for (int dy = 0, dptr = dp; dy < bandHeight; ++dy, dptr += bytesPerLine) { + int thresh = DITHER_MATRIX[dy][dx & 7] >>> bits; + int temp = val + thresh; + if (temp > 0xffffff) bitmapData[dptr] = -1; + else bitmapData[dptr] = cast(byte)((temp >>> 16) & mask); + } + val += inc; + } + } } /** @@ -3602,31 +3602,31 @@ * @param blueBits the number of significant blue bits, 0 for palette modes */ static void fillGradientRectangle(GC gc, Device device, - int x, int y, int width, int height, bool vertical, - RGB fromRGB, RGB toRGB, - int redBits, int greenBits, int blueBits) { - /* Create the bitmap and tile it */ - ImageData band = createGradientBand(width, height, vertical, - fromRGB, toRGB, redBits, greenBits, blueBits); - Image image = new Image(device, band); - if ((band.width == 1) || (band.height == 1)) { - gc.drawImage(image, 0, 0, band.width, band.height, x, y, width, height); - } else { - if (vertical) { - for (int dx = 0; dx < width; dx += band.width) { - int blitWidth = width - dx; - if (blitWidth > band.width) blitWidth = band.width; - gc.drawImage(image, 0, 0, blitWidth, band.height, dx + x, y, blitWidth, band.height); - } - } else { - for (int dy = 0; dy < height; dy += band.height) { - int blitHeight = height - dy; - if (blitHeight > band.height) blitHeight = band.height; - gc.drawImage(image, 0, 0, band.width, blitHeight, x, dy + y, band.width, blitHeight); - } - } - } - image.dispose(); + int x, int y, int width, int height, bool vertical, + RGB fromRGB, RGB toRGB, + int redBits, int greenBits, int blueBits) { + /* Create the bitmap and tile it */ + ImageData band = createGradientBand(width, height, vertical, + fromRGB, toRGB, redBits, greenBits, blueBits); + Image image = new Image(device, band); + if ((band.width == 1) || (band.height == 1)) { + gc.drawImage(image, 0, 0, band.width, band.height, x, y, width, height); + } else { + if (vertical) { + for (int dx = 0; dx < width; dx += band.width) { + int blitWidth = width - dx; + if (blitWidth > band.width) blitWidth = band.width; + gc.drawImage(image, 0, 0, blitWidth, band.height, dx + x, y, blitWidth, band.height); + } + } else { + for (int dy = 0; dy < height; dy += band.height) { + int blitHeight = height - dy; + if (blitHeight > band.height) blitHeight = band.height; + gc.drawImage(image, 0, 0, band.width, blitHeight, x, dy + y, band.width, blitHeight); + } + } + } + image.dispose(); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/ImageDataLoader.d --- a/dwt/graphics/ImageDataLoader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/ImageDataLoader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -21,12 +21,12 @@ */ class ImageDataLoader { - public static ImageData[] load(InputStream stream) { - return (new ImageLoader()).load(stream); - } + public static ImageData[] load(InputStream stream) { + return (new ImageLoader()).load(stream); + } - public static ImageData[] load(char[] filename) { - return (new ImageLoader()).load(filename); - } + public static ImageData[] load(char[] filename) { + return (new ImageLoader()).load(filename); + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/ImageLoader.d --- a/dwt/graphics/ImageLoader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/ImageLoader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -48,53 +48,53 @@ public class ImageLoader { - /** - * the array of ImageData objects in this ImageLoader. - * This array is read in when the load method is called, - * and it is written out when the save method is called - */ - public ImageData[] data; + /** + * the array of ImageData objects in this ImageLoader. + * This array is read in when the load method is called, + * and it is written out when the save method is called + */ + public ImageData[] data; - /** - * the width of the logical screen on which the images - * reside, in pixels (this corresponds to the GIF89a - * Logical Screen Width value) - */ - public int logicalScreenWidth; + /** + * the width of the logical screen on which the images + * reside, in pixels (this corresponds to the GIF89a + * Logical Screen Width value) + */ + public int logicalScreenWidth; - /** - * the height of the logical screen on which the images - * reside, in pixels (this corresponds to the GIF89a - * Logical Screen Height value) - */ - public int logicalScreenHeight; + /** + * the height of the logical screen on which the images + * reside, in pixels (this corresponds to the GIF89a + * Logical Screen Height value) + */ + public int logicalScreenHeight; - /** - * the background pixel for the logical screen (this - * corresponds to the GIF89a Background Color Index value). - * The default is -1 which means 'unspecified background' - * - */ - public int backgroundPixel; + /** + * the background pixel for the logical screen (this + * corresponds to the GIF89a Background Color Index value). + * The default is -1 which means 'unspecified background' + * + */ + public int backgroundPixel; - /** - * the number of times to repeat the display of a sequence - * of animated images (this corresponds to the commonly-used - * GIF application extension for "NETSCAPE 2.0 01"). - * The default is 1. A value of 0 means 'display repeatedly' - */ - public int repeatCount; + /** + * the number of times to repeat the display of a sequence + * of animated images (this corresponds to the commonly-used + * GIF application extension for "NETSCAPE 2.0 01"). + * The default is 1. A value of 0 means 'display repeatedly' + */ + public int repeatCount; - /* - * the set of ImageLoader event listeners, created on demand - */ - ImageLoaderListener[] imageLoaderListeners; + /* + * the set of ImageLoader event listeners, created on demand + */ + ImageLoaderListener[] imageLoaderListeners; /** * Construct a new empty ImageLoader. */ public this() { - reset(); + reset(); } /** @@ -102,11 +102,11 @@ * imageLoaderListeners field. */ void reset() { - data = null; - logicalScreenWidth = 0; - logicalScreenHeight = 0; - backgroundPixel = -1; - repeatCount = 1; + data = null; + logicalScreenWidth = 0; + logicalScreenHeight = 0; + backgroundPixel = -1; + repeatCount = 1; } /** @@ -128,10 +128,10 @@ * */ public ImageData[] load(InputStream stream) { - if (stream is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - reset(); - data = FileFormat.load(stream, this); - return data; + if (stream is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + reset(); + data = FileFormat.load(stream, this); + return data; } /** @@ -153,8 +153,8 @@ * */ public ImageData[] load(char[] filename) { - if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - InputStream stream = null; + if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + InputStream stream = null; void close(){ try { if( stream !is null ) stream.close(); @@ -162,15 +162,15 @@ // Ignore error } } - try { - stream = Compatibility.newFileInputStream(filename); + try { + stream = Compatibility.newFileInputStream(filename); scope(exit) close(); - return load(stream); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return null; + return load(stream); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return null; } /** @@ -204,8 +204,8 @@ * */ public void save(OutputStream stream, int format) { - if (stream is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - FileFormat.save(stream, format, this); + if (stream is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + FileFormat.save(stream, format, this); } /** @@ -239,18 +239,18 @@ * */ public void save(char[] filename, int format) { - if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - OutputStream stream = null; - try { - stream = Compatibility.newFileOutputStream(filename); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - save(stream, format); - try { - stream.close(); - } catch (IOException e) { - } + if (filename is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + OutputStream stream = null; + try { + stream = Compatibility.newFileOutputStream(filename); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + save(stream, format); + try { + stream.close(); + } catch (IOException e) { + } } /** @@ -273,8 +273,8 @@ * @see ImageLoaderEvent */ public void addImageLoaderListener(ImageLoaderListener listener) { - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - imageLoaderListeners ~= listener; + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + imageLoaderListeners ~= listener; } /** @@ -290,8 +290,8 @@ * @see #addImageLoaderListener(ImageLoaderListener) */ public void removeImageLoaderListener(ImageLoaderListener listener) { - if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - if (imageLoaderListeners.length == 0 ) return; + if (listener is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + if (imageLoaderListeners.length == 0 ) return; tango.core.Array.remove( imageLoaderListeners, listener, delegate bool(ImageLoaderListener l1, ImageLoaderListener l2 ){ return l1 is l2; }); } @@ -305,7 +305,7 @@ * @see #removeImageLoaderListener(ImageLoaderListener) */ public bool hasListeners() { - return imageLoaderListeners.length > 0; + return imageLoaderListeners.length > 0; } /** @@ -315,10 +315,10 @@ * @param event the ImageLoaderEvent to send to each ImageLoaderListener */ public void notifyListeners(ImageLoaderEvent event) { - if (!hasListeners()) return; + if (!hasListeners()) return; foreach( listener; imageLoaderListeners ){ - listener.imageDataLoaded(event); - } + listener.imageDataLoaded(event); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/ImageLoaderEvent.d --- a/dwt/graphics/ImageLoaderEvent.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/ImageLoaderEvent.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -37,29 +37,29 @@ public class ImageLoaderEvent : SWTEventObject { - /** - * if the endOfImage flag is false, then this is a - * partially complete copy of the current ImageData, - * otherwise this is a completely loaded ImageData - */ - public ImageData imageData; + /** + * if the endOfImage flag is false, then this is a + * partially complete copy of the current ImageData, + * otherwise this is a completely loaded ImageData + */ + public ImageData imageData; - /** - * the zero-based count of image data increments -- this is - * equivalent to the number of events that have been generated - * while loading a particular image - */ - public int incrementCount; + /** + * the zero-based count of image data increments -- this is + * equivalent to the number of events that have been generated + * while loading a particular image + */ + public int incrementCount; - /** - * If this flag is true, then the current image data has been - * completely loaded, otherwise the image data is only partially - * loaded, and further ImageLoader events will occur unless an - * exception is thrown - */ - public bool endOfImage; + /** + * If this flag is true, then the current image data has been + * completely loaded, otherwise the image data is only partially + * loaded, and further ImageLoader events will occur unless an + * exception is thrown + */ + public bool endOfImage; - //static final long serialVersionUID = 3257284738325558065L; + //static final long serialVersionUID = 3257284738325558065L; /** * Constructs a new instance of this class given the event source and @@ -71,10 +71,10 @@ * @param endOfImage the end of image flag for the event */ public this(ImageLoader source, ImageData imageData, int incrementCount, bool endOfImage) { - super(source); - this.imageData = imageData; - this.incrementCount = incrementCount; - this.endOfImage = endOfImage; + super(source); + this.imageData = imageData; + this.incrementCount = incrementCount; + this.endOfImage = endOfImage; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/LineAttributes.d --- a/dwt/graphics/LineAttributes.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/LineAttributes.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -28,55 +28,55 @@ */ public class LineAttributes { - /** - * The line width. - */ - public float width; + /** + * The line width. + */ + public float width; - /** - * The line style. - * - * @see dwt.SWT#LINE_CUSTOM - * @see dwt.SWT#LINE_DASH - * @see dwt.SWT#LINE_DASHDOT - * @see dwt.SWT#LINE_DASHDOTDOT - * @see dwt.SWT#LINE_DOT - * @see dwt.SWT#LINE_SOLID - */ - public int style; + /** + * The line style. + * + * @see dwt.SWT#LINE_CUSTOM + * @see dwt.SWT#LINE_DASH + * @see dwt.SWT#LINE_DASHDOT + * @see dwt.SWT#LINE_DASHDOTDOT + * @see dwt.SWT#LINE_DOT + * @see dwt.SWT#LINE_SOLID + */ + public int style; - /** - * The line cap style. - * - * @see dwt.SWT#CAP_FLAT - * @see dwt.SWT#CAP_ROUND - * @see dwt.SWT#CAP_SQUARE - */ - public int cap; + /** + * The line cap style. + * + * @see dwt.SWT#CAP_FLAT + * @see dwt.SWT#CAP_ROUND + * @see dwt.SWT#CAP_SQUARE + */ + public int cap; - /** - * The line join style. - * - * @see dwt.SWT#JOIN_BEVEL - * @see dwt.SWT#JOIN_MITER - * @see dwt.SWT#JOIN_ROUND - */ - public int join; + /** + * The line join style. + * + * @see dwt.SWT#JOIN_BEVEL + * @see dwt.SWT#JOIN_MITER + * @see dwt.SWT#JOIN_ROUND + */ + public int join; - /** - * The line dash style for SWT.LINE_CUSTOM. - */ - public float[] dash; + /** + * The line dash style for SWT.LINE_CUSTOM. + */ + public float[] dash; - /** - * The line dash style offset for SWT.LINE_CUSTOM. - */ - public float dashOffset; + /** + * The line dash style offset for SWT.LINE_CUSTOM. + */ + public float dashOffset; - /** - * The line miter limit. - */ - public float miterLimit; + /** + * The line miter limit. + */ + public float miterLimit; /** * Create a new line attributes with the specified line width. @@ -84,7 +84,7 @@ * @param width the line width */ public this(float width) { - this(width, SWT.CAP_FLAT, SWT.JOIN_MITER, SWT.LINE_SOLID, null, 0, 10); + this(width, SWT.CAP_FLAT, SWT.JOIN_MITER, SWT.LINE_SOLID, null, 0, 10); } /** @@ -95,7 +95,7 @@ * @param join the line join style */ public this(float width, int cap, int join) { - this(width, cap, join, SWT.LINE_SOLID, null, 0, 10); + this(width, cap, join, SWT.LINE_SOLID, null, 0, 10); } /** @@ -110,12 +110,12 @@ * @param miterLimit the line miter limit */ public this(float width, int cap, int join, int style, float[] dash, float dashOffset, float miterLimit) { - this.width = width; - this.cap = cap; - this.join = join; - this.style = style; - this.dash = dash; - this.dashOffset = dashOffset; - this.miterLimit = miterLimit; + this.width = width; + this.cap = cap; + this.join = join; + this.style = style; + this.dash = dash; + this.dashOffset = dashOffset; + this.miterLimit = miterLimit; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/PaletteData.d --- a/dwt/graphics/PaletteData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/PaletteData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -55,47 +55,47 @@ public final class PaletteData { - /** - * true if the receiver is a direct palette, - * and false otherwise - */ - public bool isDirect; + /** + * true if the receiver is a direct palette, + * and false otherwise + */ + public bool isDirect; - /** - * the RGB values for an indexed palette, where the - * indices of the array correspond to pixel values - */ - public RGB[] colors; + /** + * the RGB values for an indexed palette, where the + * indices of the array correspond to pixel values + */ + public RGB[] colors; - /** - * the red mask for a direct palette - */ - public int redMask; + /** + * the red mask for a direct palette + */ + public int redMask; - /** - * the green mask for a direct palette - */ - public int greenMask; + /** + * the green mask for a direct palette + */ + public int greenMask; - /** - * the blue mask for a direct palette - */ - public int blueMask; + /** + * the blue mask for a direct palette + */ + public int blueMask; - /** - * the red shift for a direct palette - */ - public int redShift; + /** + * the red shift for a direct palette + */ + public int redShift; - /** - * the green shift for a direct palette - */ - public int greenShift; + /** + * the green shift for a direct palette + */ + public int greenShift; - /** - * the blue shift for a direct palette - */ - public int blueShift; + /** + * the blue shift for a direct palette + */ + public int blueShift; /** * Constructs a new indexed palette given an array of RGB values. @@ -107,9 +107,9 @@ * */ public this(RGB[] colors) { - if (colors == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.colors = colors; - this.isDirect = false; + if (colors == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.colors = colors; + this.isDirect = false; } /** @@ -120,13 +120,13 @@ * @param blueMask the blue mask */ public this(int redMask, int greenMask, int blueMask) { - this.redMask = redMask; - this.greenMask = greenMask; - this.blueMask = blueMask; - this.isDirect = true; - this.redShift = shiftForMask(redMask); - this.greenShift = shiftForMask(greenMask); - this.blueShift = shiftForMask(blueMask); + this.redMask = redMask; + this.greenMask = greenMask; + this.blueMask = blueMask; + this.isDirect = true; + this.redShift = shiftForMask(redMask); + this.greenShift = shiftForMask(greenMask); + this.blueShift = shiftForMask(blueMask); } /** @@ -141,21 +141,21 @@ * */ public int getPixel(RGB rgb) { - if (rgb is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (isDirect) { - int pixel = 0; - pixel |= (redShift < 0 ? rgb.red << -redShift : rgb.red >>> redShift) & redMask; - pixel |= (greenShift < 0 ? rgb.green << -greenShift : rgb.green >>> greenShift) & greenMask; - pixel |= (blueShift < 0 ? rgb.blue << -blueShift : rgb.blue >>> blueShift) & blueMask; - return pixel; - } else { - for (int i = 0; i < colors.length; i++) { - if (colors[i] == rgb ) return i; - } - /* The RGB did not exist in the palette */ - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - return 0; - } + if (rgb is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (isDirect) { + int pixel = 0; + pixel |= (redShift < 0 ? rgb.red << -redShift : rgb.red >>> redShift) & redMask; + pixel |= (greenShift < 0 ? rgb.green << -greenShift : rgb.green >>> greenShift) & greenMask; + pixel |= (blueShift < 0 ? rgb.blue << -blueShift : rgb.blue >>> blueShift) & blueMask; + return pixel; + } else { + for (int i = 0; i < colors.length; i++) { + if (colors[i] == rgb ) return i; + } + /* The RGB did not exist in the palette */ + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + return 0; + } } /** @@ -170,20 +170,20 @@ * */ public RGB getRGB(int pixel) { - if (isDirect) { - int r = pixel & redMask; - r = (redShift < 0) ? r >>> -redShift : r << redShift; - int g = pixel & greenMask; - g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; - int b = pixel & blueMask; - b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; - return new RGB(r, g, b); - } else { - if (pixel < 0 || pixel >= colors.length) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - return colors[pixel]; - } + if (isDirect) { + int r = pixel & redMask; + r = (redShift < 0) ? r >>> -redShift : r << redShift; + int g = pixel & greenMask; + g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; + int b = pixel & blueMask; + b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; + return new RGB(r, g, b); + } else { + if (pixel < 0 || pixel >= colors.length) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + return colors[pixel]; + } } /** @@ -193,7 +193,7 @@ * @return the RGBs for the receiver or null */ public RGB[] getRGBs() { - return colors; + return colors; } /** @@ -205,10 +205,10 @@ * @see PaletteData */ int shiftForMask(int mask) { - for (int i = 31; i >= 0; i--) { - if (((mask >> i) & 0x1) != 0) return 7 - i; - } - return 32; + for (int i = 31; i >= 0; i--) { + if (((mask >> i) & 0x1) != 0) return 7 - i; + } + return 32; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Path.d --- a/dwt/graphics/Path.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Path.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -42,19 +42,19 @@ */ public class Path : Resource { - /** - * the OS resource for the Path - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public cairo_t* handle; + /** + * the OS resource for the Path + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public cairo_t* handle; - bool moved, closed = true; + bool moved, closed = true; /** * Constructs a new empty Path. @@ -79,16 +79,16 @@ * @see #dispose() */ public this (Device device) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - device.checkCairo(); - auto surface = Cairo.cairo_image_surface_create(Cairo.CAIRO_FORMAT_ARGB32, 1, 1); - if (surface is null) SWT.error(SWT.ERROR_NO_HANDLES); - handle = Cairo.cairo_create(surface); - Cairo.cairo_surface_destroy(surface); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + device.checkCairo(); + auto surface = Cairo.cairo_image_surface_create(Cairo.CAIRO_FORMAT_ARGB32, 1, 1); + if (surface is null) SWT.error(SWT.ERROR_NO_HANDLES); + handle = Cairo.cairo_create(surface); + Cairo.cairo_surface_destroy(surface); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + if (device.tracking) device.new_Object(this); } /** @@ -121,31 +121,31 @@ * */ public void addArc(float x, float y, float width, float height, float startAngle, float arcAngle) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - moved = true; - if (width == height) { - float angle = -startAngle * cast(float)Compatibility.PI / 180; - if (closed) Cairo.cairo_move_to(handle, (x + width / 2f) + width / 2f * Math.cos(angle), (y + height / 2f) + height / 2f * Math.sin(angle)); - if (arcAngle >= 0) { - Cairo.cairo_arc_negative(handle, x + width / 2f, y + height / 2f, width / 2f, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } else { - Cairo.cairo_arc(handle, x + width / 2f, y + height / 2f, width / 2f, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } - } else { - Cairo.cairo_save(handle); - Cairo.cairo_translate(handle, x + width / 2f, y + height / 2f); - Cairo.cairo_scale(handle, width / 2f, height / 2f); - float angle = -startAngle * cast(float)Compatibility.PI / 180; - if (closed) Cairo.cairo_move_to(handle, Math.cos(angle), Math.sin(angle)); - if (arcAngle >= 0) { - Cairo.cairo_arc_negative(handle, 0, 0, 1, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } else { - Cairo.cairo_arc(handle, 0, 0, 1, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); - } - Cairo.cairo_restore(handle); - } - closed = false; - if (Math.abs(arcAngle) >= 360) close(); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + moved = true; + if (width == height) { + float angle = -startAngle * cast(float)Compatibility.PI / 180; + if (closed) Cairo.cairo_move_to(handle, (x + width / 2f) + width / 2f * Math.cos(angle), (y + height / 2f) + height / 2f * Math.sin(angle)); + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(handle, x + width / 2f, y + height / 2f, width / 2f, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(handle, x + width / 2f, y + height / 2f, width / 2f, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } + } else { + Cairo.cairo_save(handle); + Cairo.cairo_translate(handle, x + width / 2f, y + height / 2f); + Cairo.cairo_scale(handle, width / 2f, height / 2f); + float angle = -startAngle * cast(float)Compatibility.PI / 180; + if (closed) Cairo.cairo_move_to(handle, Math.cos(angle), Math.sin(angle)); + if (arcAngle >= 0) { + Cairo.cairo_arc_negative(handle, 0, 0, 1, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } else { + Cairo.cairo_arc(handle, 0, 0, 1, angle, -(startAngle + arcAngle) * cast(float)Compatibility.PI / 180); + } + Cairo.cairo_restore(handle); + } + closed = false; + if (Math.abs(arcAngle) >= 360) close(); } /** @@ -162,15 +162,15 @@ * */ public void addPath(Path path) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (path.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - moved = false; - auto copy = Cairo.cairo_copy_path(path.handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_append_path(handle, copy); - Cairo.cairo_path_destroy(copy); - closed = path.closed; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (path is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (path.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + moved = false; + auto copy = Cairo.cairo_copy_path(path.handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(handle, copy); + Cairo.cairo_path_destroy(copy); + closed = path.closed; } /** @@ -186,10 +186,10 @@ * */ public void addRectangle(float x, float y, float width, float height) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - moved = false; - Cairo.cairo_rectangle(handle, x, y, width, height); - closed = true; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + moved = false; + Cairo.cairo_rectangle(handle, x, y, width, height); + closed = true; } /** @@ -210,12 +210,12 @@ * */ public void addString(char[] str, float x, float y, Font font) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (font == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - moved = false; - GC.addCairoString(handle, str, x, y, font); - closed = true; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (font == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + moved = false; + GC.addCairoString(handle, str, x, y, font); + closed = true; } /** @@ -228,10 +228,10 @@ * */ public void close() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - Cairo.cairo_close_path(handle); - moved = false; - closed = true; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Cairo.cairo_close_path(handle); + moved = false; + closed = true; } /** @@ -258,25 +258,25 @@ * */ public bool contains(float x, float y, GC gc, bool outline) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (gc == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - //TODO - see Windows - gc.initCairo(); - gc.checkGC(GC.LINE_CAP | GC.LINE_JOIN | GC.LINE_STYLE | GC.LINE_WIDTH); - bool result = false; - auto cairo = gc.data.cairo; - auto copy = Cairo.cairo_copy_path(handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_append_path(cairo, copy); - Cairo.cairo_path_destroy(copy); - if (outline) { - result = Cairo.cairo_in_stroke(cairo, x, y) != 0; - } else { - result = Cairo.cairo_in_fill(cairo, x, y) != 0; - } - Cairo.cairo_new_path(cairo); - return result; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (gc == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + //TODO - see Windows + gc.initCairo(); + gc.checkGC(GC.LINE_CAP | GC.LINE_JOIN | GC.LINE_STYLE | GC.LINE_WIDTH); + bool result = false; + auto cairo = gc.data.cairo; + auto copy = Cairo.cairo_copy_path(handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_append_path(cairo, copy); + Cairo.cairo_path_destroy(copy); + if (outline) { + result = Cairo.cairo_in_stroke(cairo, x, y) != 0; + } else { + result = Cairo.cairo_in_fill(cairo, x, y) != 0; + } + Cairo.cairo_new_path(cairo); + return result; } /** @@ -294,15 +294,15 @@ * */ public void cubicTo(float cx1, float cy1, float cx2, float cy2, float x, float y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (!moved) { - double currentX, currentY; - Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); - Cairo.cairo_move_to(handle, currentX, currentY); - moved = true; - } - Cairo.cairo_curve_to(handle, cx1, cy1, cx2, cy2, x, y); - closed = false; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (!moved) { + double currentX, currentY; + Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); + Cairo.cairo_move_to(handle, currentX, currentY); + moved = true; + } + Cairo.cairo_curve_to(handle, cx1, cy1, cx2, cy2, x, y); + closed = false; } /** @@ -321,35 +321,35 @@ * */ public void getBounds(float[] bounds) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (bounds == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (bounds.length < 4) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - auto copy = Cairo.cairo_copy_path(handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - cairo_path_t* path = new cairo_path_t(); - memmove(path, copy, cairo_path_t.sizeof); - double minX = 0, minY = 0, maxX = 0, maxY = 0; - if (path.num_data > 0) { - minX = minY = double.max; - maxX = maxY = -double.max; - int i = 0; - cairo_path_data_t* data = new cairo_path_data_t(); - while (i < path.num_data) { - *data = path.data[i]; - switch (data.header.type) { - case Cairo.CAIRO_PATH_MOVE_TO: - minX = Math.min(minX, path.data[i+1].point.x); - minY = Math.min(minY, path.data[i+1].point.y); - maxX = Math.max(maxX, path.data[i+1].point.x); - maxY = Math.max(maxY, path.data[i+1].point.y); - break; - case Cairo.CAIRO_PATH_LINE_TO: + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (bounds == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (bounds.length < 4) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + auto copy = Cairo.cairo_copy_path(handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + cairo_path_t* path = new cairo_path_t(); + memmove(path, copy, cairo_path_t.sizeof); + double minX = 0, minY = 0, maxX = 0, maxY = 0; + if (path.num_data > 0) { + minX = minY = double.max; + maxX = maxY = -double.max; + int i = 0; + cairo_path_data_t* data = new cairo_path_data_t(); + while (i < path.num_data) { + *data = path.data[i]; + switch (data.header.type) { + case Cairo.CAIRO_PATH_MOVE_TO: minX = Math.min(minX, path.data[i+1].point.x); minY = Math.min(minY, path.data[i+1].point.y); maxX = Math.max(maxX, path.data[i+1].point.x); maxY = Math.max(maxY, path.data[i+1].point.y); - break; - case Cairo.CAIRO_PATH_CURVE_TO: + break; + case Cairo.CAIRO_PATH_LINE_TO: + minX = Math.min(minX, path.data[i+1].point.x); + minY = Math.min(minY, path.data[i+1].point.y); + maxX = Math.max(maxX, path.data[i+1].point.x); + maxY = Math.max(maxY, path.data[i+1].point.y); + break; + case Cairo.CAIRO_PATH_CURVE_TO: minX = Math.min(minX, path.data[i+1].point.x); minY = Math.min(minY, path.data[i+1].point.y); maxX = Math.max(maxX, path.data[i+1].point.x); @@ -362,18 +362,18 @@ minY = Math.min(minY, path.data[i+3].point.y); maxX = Math.max(maxX, path.data[i+3].point.x); maxY = Math.max(maxY, path.data[i+3].point.y); - break; - case Cairo.CAIRO_PATH_CLOSE_PATH: break; + break; + case Cairo.CAIRO_PATH_CLOSE_PATH: break; default: - } - i += data.header.length; - } - } - bounds[0] = cast(float)minX; - bounds[1] = cast(float)minY; - bounds[2] = cast(float)(maxX - minX); - bounds[3] = cast(float)(maxY - minY); - Cairo.cairo_path_destroy(copy); + } + i += data.header.length; + } + } + bounds[0] = cast(float)minX; + bounds[1] = cast(float)minY; + bounds[2] = cast(float)(maxX - minX); + bounds[3] = cast(float)(maxY - minY); + Cairo.cairo_path_destroy(copy); } /** @@ -391,13 +391,13 @@ * */ public void getCurrentPoint(float[] point) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (point.length < 2) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - double x, y; - Cairo.cairo_get_current_point(handle, &x, &y); - point[0] = cast(float)x; - point[1] = cast(float)y; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (point.length < 2) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + double x, y; + Cairo.cairo_get_current_point(handle, &x, &y); + point[0] = cast(float)x; + point[1] = cast(float)y; } /** @@ -412,62 +412,62 @@ * @see PathData */ public PathData getPathData() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - auto copy = Cairo.cairo_copy_path(handle); - if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); - cairo_path_t* path = new cairo_path_t(); - *path = *copy; - byte[] types = new byte[path.num_data]; - float[] pts = new float[path.num_data * 6]; - int typeIndex = 0, ptsIndex = 0; - if (path.num_data > 0) { - int i = 0; - double[] points = new double[6]; - cairo_path_data_t* data = new cairo_path_data_t(); - while (i < path.num_data) { - switch (data.header.type) { - case Cairo.CAIRO_PATH_MOVE_TO: - types[typeIndex++] = SWT.PATH_MOVE_TO; - pts[ptsIndex++] = cast(float)path.data[i+1].point.x; - pts[ptsIndex++] = cast(float)path.data[i+1].point.y; - break; - case Cairo.CAIRO_PATH_LINE_TO: - types[typeIndex++] = SWT.PATH_LINE_TO; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + auto copy = Cairo.cairo_copy_path(handle); + if (copy is null) SWT.error(SWT.ERROR_NO_HANDLES); + cairo_path_t* path = new cairo_path_t(); + *path = *copy; + byte[] types = new byte[path.num_data]; + float[] pts = new float[path.num_data * 6]; + int typeIndex = 0, ptsIndex = 0; + if (path.num_data > 0) { + int i = 0; + double[] points = new double[6]; + cairo_path_data_t* data = new cairo_path_data_t(); + while (i < path.num_data) { + switch (data.header.type) { + case Cairo.CAIRO_PATH_MOVE_TO: + types[typeIndex++] = SWT.PATH_MOVE_TO; pts[ptsIndex++] = cast(float)path.data[i+1].point.x; pts[ptsIndex++] = cast(float)path.data[i+1].point.y; - break; - case Cairo.CAIRO_PATH_CURVE_TO: - types[typeIndex++] = SWT.PATH_CUBIC_TO; + break; + case Cairo.CAIRO_PATH_LINE_TO: + types[typeIndex++] = SWT.PATH_LINE_TO; + pts[ptsIndex++] = cast(float)path.data[i+1].point.x; + pts[ptsIndex++] = cast(float)path.data[i+1].point.y; + break; + case Cairo.CAIRO_PATH_CURVE_TO: + types[typeIndex++] = SWT.PATH_CUBIC_TO; pts[ptsIndex++] = cast(float)path.data[i+1].point.x; pts[ptsIndex++] = cast(float)path.data[i+1].point.y; pts[ptsIndex++] = cast(float)path.data[i+2].point.x; pts[ptsIndex++] = cast(float)path.data[i+2].point.y; pts[ptsIndex++] = cast(float)path.data[i+3].point.x; pts[ptsIndex++] = cast(float)path.data[i+3].point.y; - break; - case Cairo.CAIRO_PATH_CLOSE_PATH: - types[typeIndex++] = SWT.PATH_CLOSE; - break; + break; + case Cairo.CAIRO_PATH_CLOSE_PATH: + types[typeIndex++] = SWT.PATH_CLOSE; + break; default: - } - i += data.header.length; - } - } - if (typeIndex != types.length) { + } + i += data.header.length; + } + } + if (typeIndex != types.length) { byte[] newTypes = new byte[typeIndex]; System.arraycopy(types, 0, newTypes, 0, typeIndex); types = newTypes; - } - if (ptsIndex != pts.length) { + } + if (ptsIndex != pts.length) { float[] newPts = new float[ptsIndex]; System.arraycopy(pts, 0, newPts, 0, ptsIndex); pts = newPts; - } - Cairo.cairo_path_destroy(copy); - PathData result = new PathData(); - result.types = types; - result.points = pts; - return result; + } + Cairo.cairo_path_destroy(copy); + PathData result = new PathData(); + result.types = types; + result.points = pts; + return result; } /** @@ -482,15 +482,15 @@ * */ public void lineTo(float x, float y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (!moved) { - double currentX, currentY; - Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); - Cairo.cairo_move_to(handle, currentX, currentY); - moved = true; - } - Cairo.cairo_line_to(handle, x, y); - closed = false; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (!moved) { + double currentX, currentY; + Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); + Cairo.cairo_move_to(handle, currentX, currentY); + moved = true; + } + Cairo.cairo_line_to(handle, x, y); + closed = false; } /** @@ -506,17 +506,17 @@ * */ public void moveTo(float x, float y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - /* - * Bug in Cairo. If cairo_move_to() is not called at the - * begining of a subpath, the first cairo_line_to() or - * cairo_curve_to() segment do not output anything. The fix - * is to detect that the app did not call cairo_move_to() - * before those calls and call it explicitly. - */ - moved = true; - Cairo.cairo_move_to(handle, x, y); - closed = true; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + /* + * Bug in Cairo. If cairo_move_to() is not called at the + * begining of a subpath, the first cairo_line_to() or + * cairo_curve_to() segment do not output anything. The fix + * is to detect that the app did not call cairo_move_to() + * before those calls and call it explicitly. + */ + moved = true; + Cairo.cairo_move_to(handle, x, y); + closed = true; } /** @@ -532,21 +532,21 @@ * */ public void quadTo(float cx, float cy, float x, float y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - double currentX, currentY; - Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); - if (!moved) { - Cairo.cairo_move_to(handle, currentX, currentY); - moved = true; - } - float x0 = cast(float)currentX; - float y0 = cast(float)currentY; - float cx1 = x0 + 2 * (cx - x0) / 3; - float cy1 = y0 + 2 * (cy - y0) / 3; - float cx2 = cx1 + (x - x0) / 3; - float cy2 = cy1 + (y - y0) / 3; - Cairo.cairo_curve_to(handle, cx1, cy1, cx2, cy2, x, y); - closed = false; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + double currentX, currentY; + Cairo.cairo_get_current_point(handle, ¤tX, ¤tY); + if (!moved) { + Cairo.cairo_move_to(handle, currentX, currentY); + moved = true; + } + float x0 = cast(float)currentX; + float y0 = cast(float)currentY; + float cx1 = x0 + 2 * (cx - x0) / 3; + float cy1 = y0 + 2 * (cy - y0) / 3; + float cx2 = cx1 + (x - x0) / 3; + float cy2 = cy1 + (y - y0) / 3; + Cairo.cairo_curve_to(handle, cx1, cy1, cx2, cy2, x, y); + closed = false; } /** @@ -555,11 +555,11 @@ * they allocate. */ public void dispose() { - if (handle is null) return; - Cairo.cairo_destroy(handle); - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null) return; + Cairo.cairo_destroy(handle); + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -573,7 +573,7 @@ * @return true when the Path is disposed, and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -583,8 +583,8 @@ * @return a string representation of the receiver */ public char[] toString() { - if (isDisposed()) return "Path {*DISPOSED*}"; - return Format( "Path {{{}}", handle ); + if (isDisposed()) return "Path {*DISPOSED*}"; + return Format( "Path {{{}}", handle ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/PathData.d --- a/dwt/graphics/PathData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/PathData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -20,13 +20,13 @@ */ public final class PathData { - /** - * The type of each point. - */ - public byte[] types; + /** + * The type of each point. + */ + public byte[] types; - /** - * The points of a path. - */ - public float[] points; + /** + * The points of a path. + */ + public float[] points; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Pattern.d --- a/dwt/graphics/Pattern.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Pattern.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -38,17 +38,17 @@ */ public class Pattern : Resource { - /** - * the OS resource for the Pattern - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public cairo_pattern_t* handle; + /** + * the OS resource for the Pattern + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public cairo_pattern_t* handle; /** * Constructs a new Pattern given an image. Drawing with the resulting @@ -76,17 +76,17 @@ * @see #dispose() */ public this(Device device, Image image) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - this.device = device; - device.checkCairo(); - image.createSurface(); - handle = Cairo.cairo_pattern_create_for_surface(image.surface); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_pattern_set_extend(handle, Cairo.CAIRO_EXTEND_REPEAT); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (image.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.device = device; + device.checkCairo(); + image.createSurface(); + handle = Cairo.cairo_pattern_create_for_surface(image.surface); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_pattern_set_extend(handle, Cairo.CAIRO_EXTEND_REPEAT); + if (device.tracking) device.new_Object(this); } /** @@ -122,7 +122,7 @@ * @see #dispose() */ public this(Device device, float x1, float y1, float x2, float y2, Color color1, Color color2) { - this(device, x1, y1, x2, y2, color1, 0xFF, color2, 0xFF); + this(device, x1, y1, x2, y2, color1, 0xFF, color2, 0xFF); } /** * Constructs a new Pattern that represents a linear, two color @@ -161,20 +161,20 @@ * @since 3.2 */ public this(Device device, float x1, float y1, float x2, float y2, Color color1, int alpha1, Color color2, int alpha2) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (color1 is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (color1.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (color2 is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (color2.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - this.device = device; - device.checkCairo(); - handle = Cairo.cairo_pattern_create_linear(x1, y1, x2, y2); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - GC.setCairoPatternColor(handle, 0, color1, alpha1); - GC.setCairoPatternColor(handle, 1, color2, alpha2); - Cairo.cairo_pattern_set_extend(handle, Cairo.CAIRO_EXTEND_REPEAT); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color1 is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color1.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (color2 is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (color2.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.device = device; + device.checkCairo(); + handle = Cairo.cairo_pattern_create_linear(x1, y1, x2, y2); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + GC.setCairoPatternColor(handle, 0, color1, alpha1); + GC.setCairoPatternColor(handle, 1, color2, alpha2); + Cairo.cairo_pattern_set_extend(handle, Cairo.CAIRO_EXTEND_REPEAT); + if (device.tracking) device.new_Object(this); } /** @@ -183,12 +183,12 @@ * they allocate. */ public void dispose() { - if (handle is null) return; - if (device.isDisposed()) return; - Cairo.cairo_pattern_destroy(handle); - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null) return; + if (device.isDisposed()) return; + Cairo.cairo_pattern_destroy(handle); + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -202,7 +202,7 @@ * @return true when the Pattern is disposed, and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -212,8 +212,8 @@ * @return a string representation of the receiver */ public char[] toString() { - if (isDisposed()) return "Pattern {*DISPOSED*}"; - return Format( "Pattern {{{}}", handle ); + if (isDisposed()) return "Pattern {*DISPOSED*}"; + return Format( "Pattern {{{}}", handle ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Point.d --- a/dwt/graphics/Point.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Point.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -41,17 +41,17 @@ public final class Point : SerializableCompatibility { - /** - * the x coordinate of the point - */ - public int x; + /** + * the x coordinate of the point + */ + public int x; - /** - * the y coordinate of the point - */ - public int y; + /** + * the y coordinate of the point + */ + public int y; - //static final long serialVersionUID = 3257002163938146354L; + //static final long serialVersionUID = 3257002163938146354L; /** * Constructs a new point with the given x and y coordinates. @@ -60,8 +60,8 @@ * @param y the y coordinate of the new point */ public this (int x, int y) { - this.x = x; - this.y = y; + this.x = x; + this.y = y; } /** @@ -75,8 +75,8 @@ * @see #hashCode() */ public override int opEquals (Object object) { - if (object is this) return true; - if ( auto p = cast(Point)object ){ + if (object is this) return true; + if ( auto p = cast(Point)object ){ return (p.x == this.x) && (p.y == this.y); } return false; @@ -93,7 +93,7 @@ * @see #equals(Object) */ public hash_t toHash () { - return x ^ y; + return x ^ y; } /** @@ -103,7 +103,7 @@ * @return a string representation of the point */ public char[] toString () { - return Format( "Point {}, {}}", x, y );; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return Format( "Point {}, {}}", x, y );; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/RGB.d --- a/dwt/graphics/RGB.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/RGB.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -41,22 +41,22 @@ public final class RGB : SerializableCompatibility { - /** - * the red component of the RGB - */ - public int red; + /** + * the red component of the RGB + */ + public int red; - /** - * the green component of the RGB - */ - public int green; + /** + * the green component of the RGB + */ + public int green; - /** - * the blue component of the RGB - */ - public int blue; + /** + * the blue component of the RGB + */ + public int blue; - //static final long serialVersionUID = 3258415023461249074L; + //static final long serialVersionUID = 3258415023461249074L; /** * Constructs an instance of this class with the given @@ -71,13 +71,13 @@ * */ public this (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); - this.red = red; - this.green = green; - this.blue = blue; + if ((red > 255) || (red < 0) || + (green > 255) || (green < 0) || + (blue > 255) || (blue < 0)) + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + this.red = red; + this.green = green; + this.blue = blue; } /** @@ -96,58 +96,58 @@ * @since 3.2 */ public this (float hue, float saturation, float brightness) { - if (hue < 0 || hue > 360 || saturation < 0 || saturation > 1 || - brightness < 0 || brightness > 1) { - SWT.error(SWT.ERROR_INVALID_ARGUMENT); - } - float r, g, b; - if (saturation == 0) { - r = g = b = brightness; - } else { - if (hue == 360) hue = 0; - hue /= 60; - int i = cast(int)hue; - float f = hue - i; - float p = brightness * (1 - saturation); - float q = brightness * (1 - saturation * f); - float t = brightness * (1 - saturation * (1 - f)); - switch(i) { - case 0: - r = brightness; - g = t; - b = p; - break; - case 1: - r = q; - g = brightness; - b = p; - break; - case 2: - r = p; - g = brightness; - b = t; - break; - case 3: - r = p; - g = q; - b = brightness; - break; - case 4: - r = t; - g = p; - b = brightness; - break; - case 5: - default: - r = brightness; - g = p; - b = q; - break; - } - } - red = cast(int)(r * 255 + 0.5); - green = cast(int)(g * 255 + 0.5); - blue = cast(int)(b * 255 + 0.5); + if (hue < 0 || hue > 360 || saturation < 0 || saturation > 1 || + brightness < 0 || brightness > 1) { + SWT.error(SWT.ERROR_INVALID_ARGUMENT); + } + float r, g, b; + if (saturation == 0) { + r = g = b = brightness; + } else { + if (hue == 360) hue = 0; + hue /= 60; + int i = cast(int)hue; + float f = hue - i; + float p = brightness * (1 - saturation); + float q = brightness * (1 - saturation * f); + float t = brightness * (1 - saturation * (1 - f)); + switch(i) { + case 0: + r = brightness; + g = t; + b = p; + break; + case 1: + r = q; + g = brightness; + b = p; + break; + case 2: + r = p; + g = brightness; + b = t; + break; + case 3: + r = p; + g = q; + b = brightness; + break; + case 4: + r = t; + g = p; + b = brightness; + break; + case 5: + default: + r = brightness; + g = p; + b = q; + break; + } + } + red = cast(int)(r * 255 + 0.5); + green = cast(int)(g * 255 + 0.5); + blue = cast(int)(b * 255 + 0.5); } /** @@ -158,29 +158,29 @@ * @since 3.2 */ public float[] getHSB() { - float r = red / 255f; - float g = green / 255f; - float b = blue / 255f; - float max = Math.max(Math.max(r, g), b); - float min = Math.min(Math.min(r, g), b); - float delta = max - min; - float hue = 0; - float brightness = max; - float saturation = max == 0 ? 0 : (max - min) / max; - if (delta != 0) { - if (r == max) { - hue = (g - b) / delta; - } else { - if (g == max) { - hue = 2 + (b - r) / delta; - } else { - hue = 4 + (r - g) / delta; - } - } - hue *= 60; - if (hue < 0) hue += 360; - } - return [ hue, saturation, brightness ]; + float r = red / 255f; + float g = green / 255f; + float b = blue / 255f; + float max = Math.max(Math.max(r, g), b); + float min = Math.min(Math.min(r, g), b); + float delta = max - min; + float hue = 0; + float brightness = max; + float saturation = max == 0 ? 0 : (max - min) / max; + if (delta != 0) { + if (r == max) { + hue = (g - b) / delta; + } else { + if (g == max) { + hue = 2 + (b - r) / delta; + } else { + hue = 4 + (r - g) / delta; + } + } + hue *= 60; + if (hue < 0) hue += 360; + } + return [ hue, saturation, brightness ]; } /** @@ -194,11 +194,11 @@ * @see #hashCode() */ public override int opEquals(Object object) { - if (object is this) return true; + if (object is this) return true; if( auto rgb = cast(RGB) object ){ return (rgb.red == this.red) && (rgb.green == this.green) && (rgb.blue == this.blue); } - return false; + return false; } /** @@ -212,7 +212,7 @@ * @see #equals(Object) */ public hash_t toHash() { - return (blue << 16) | (green << 8) | red; + return (blue << 16) | (green << 8) | red; } /** @@ -222,7 +222,7 @@ * @return a String representation of the RGB */ public override char[] toString() { - return Format( "RGB {}, {}, {}}", red, green, blue ); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + return Format( "RGB {}, {}, {}}", red, green, blue ); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Rectangle.d --- a/dwt/graphics/Rectangle.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Rectangle.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -45,27 +45,27 @@ public final class Rectangle : SerializableCompatibility { - /** - * the x coordinate of the rectangle - */ - public int x; + /** + * the x coordinate of the rectangle + */ + public int x; - /** - * the y coordinate of the rectangle - */ - public int y; + /** + * the y coordinate of the rectangle + */ + public int y; - /** - * the width of the rectangle - */ - public int width; + /** + * the width of the rectangle + */ + public int width; - /** - * the height of the rectangle - */ - public int height; + /** + * the height of the rectangle + */ + public int height; - //static final long serialVersionUID = 3256439218279428914L; + //static final long serialVersionUID = 3256439218279428914L; /** * Construct a new instance of this class given the @@ -77,10 +77,10 @@ * @param height the height of the rectangle */ public this (int x, int y, int width, int height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; + this.x = x; + this.y = y; + this.width = width; + this.height = height; } /** @@ -100,16 +100,16 @@ * */ public void add (Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - int left = x < rect.x ? x : rect.x; - int top = y < rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs > rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs > rhs ? lhs : rhs; - x = left; y = top; width = right - left; height = bottom - top; + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int left = x < rect.x ? x : rect.x; + int top = y < rect.y ? y : rect.y; + int lhs = x + width; + int rhs = rect.x + rect.width; + int right = lhs > rhs ? lhs : rhs; + lhs = y + height; + rhs = rect.y + rect.height; + int bottom = lhs > rhs ? lhs : rhs; + x = left; y = top; width = right - left; height = bottom - top; } /** @@ -122,7 +122,7 @@ * @return true if the rectangle contains the point and false otherwise */ public bool contains (int x, int y) { - return (x >= this.x) && (y >= this.y) && ((x - this.x) < width) && ((y - this.y) < height); + return (x >= this.x) && (y >= this.y) && ((x - this.x) < width) && ((y - this.y) < height); } /** @@ -138,8 +138,8 @@ * */ public bool contains (Point pt) { - if (pt == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return contains(pt.x, pt.y); + if (pt == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return contains(pt.x, pt.y); } /** @@ -153,11 +153,11 @@ * @see #hashCode() */ public override int opEquals (Object object) { - if (object is this) return true; + if (object is this) return true; if( auto r = cast(Rectangle) object ){ return (r.x == this.x) && (r.y == this.y) && (r.width == this.width) && (r.height == this.height); } - return false; + return false; } /** @@ -171,7 +171,7 @@ * @see #equals(Object) */ public override hash_t toHash () { - return x ^ y ^ width ^ height; + return x ^ y ^ width ^ height; } /** @@ -188,20 +188,20 @@ * since 3.0 */ public void intersect (Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (this is rect) return; - int left = x > rect.x ? x : rect.x; - int top = y > rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs < rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs < rhs ? lhs : rhs; - x = right < left ? 0 : left; - y = bottom < top ? 0 : top; - width = right < left ? 0 : right - left; - height = bottom < top ? 0 : bottom - top; + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (this is rect) return; + int left = x > rect.x ? x : rect.x; + int top = y > rect.y ? y : rect.y; + int lhs = x + width; + int rhs = rect.x + rect.width; + int right = lhs < rhs ? lhs : rhs; + lhs = y + height; + rhs = rect.y + rect.height; + int bottom = lhs < rhs ? lhs : rhs; + x = right < left ? 0 : left; + y = bottom < top ? 0 : top; + width = right < left ? 0 : right - left; + height = bottom < top ? 0 : bottom - top; } /** @@ -220,21 +220,21 @@ * */ public Rectangle intersection (Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (this is rect) return new Rectangle (x, y, width, height); - int left = x > rect.x ? x : rect.x; - int top = y > rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs < rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs < rhs ? lhs : rhs; - return new Rectangle ( - right < left ? 0 : left, - bottom < top ? 0 : top, - right < left ? 0 : right - left, - bottom < top ? 0 : bottom - top); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (this is rect) return new Rectangle (x, y, width, height); + int left = x > rect.x ? x : rect.x; + int top = y > rect.y ? y : rect.y; + int lhs = x + width; + int rhs = rect.x + rect.width; + int right = lhs < rhs ? lhs : rhs; + lhs = y + height; + rhs = rect.y + rect.height; + int bottom = lhs < rhs ? lhs : rhs; + return new Rectangle ( + right < left ? 0 : left, + bottom < top ? 0 : top, + right < left ? 0 : right - left, + bottom < top ? 0 : bottom - top); } /** @@ -262,8 +262,8 @@ * @since 3.0 */ public bool intersects (int x, int y, int width, int height) { - return (x < this.x + this.width) && (y < this.y + this.height) && - (x + width > this.x) && (y + height > this.y); + return (x < this.x + this.width) && (y < this.y + this.height) && + (x + width > this.x) && (y + height > this.y); } /** @@ -285,8 +285,8 @@ * @see #isEmpty() */ public bool intersects (Rectangle rect) { - if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return rect == this || intersects (rect.x, rect.y, rect.width, rect.height); + if (rect == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return rect == this || intersects (rect.x, rect.y, rect.width, rect.height); } /** @@ -302,7 +302,7 @@ * @return true if the receiver is empty, and false otherwise */ public bool isEmpty () { - return (width <= 0) || (height <= 0); + return (width <= 0) || (height <= 0); } /** @@ -334,16 +334,16 @@ * @see #add(Rectangle) */ public Rectangle makeUnion (Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - int left = x < rect.x ? x : rect.x; - int top = y < rect.y ? y : rect.y; - int lhs = x + width; - int rhs = rect.x + rect.width; - int right = lhs > rhs ? lhs : rhs; - lhs = y + height; - rhs = rect.y + rect.height; - int bottom = lhs > rhs ? lhs : rhs; - return new Rectangle (left, top, right - left, bottom - top); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + int left = x < rect.x ? x : rect.x; + int top = y < rect.y ? y : rect.y; + int lhs = x + width; + int rhs = rect.x + rect.width; + int right = lhs > rhs ? lhs : rhs; + lhs = y + height; + rhs = rect.y + rect.height; + int bottom = lhs > rhs ? lhs : rhs; + return new Rectangle (left, top, right - left, bottom - top); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Region.d --- a/dwt/graphics/Region.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Region.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -31,17 +31,17 @@ *

    */ public final class Region : Resource { - /** - * the OS resource for the region - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public GdkRegion* handle; + /** + * the OS resource for the region + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public GdkRegion* handle; /** * Constructs a new empty region. @@ -51,7 +51,7 @@ * */ public this() { - this(null); + this(null); } /** @@ -74,17 +74,17 @@ * @since 3.0 */ public this(Device device) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - handle = OS.gdk_region_new(); - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + handle = OS.gdk_region_new(); + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + if (device.tracking) device.new_Object(this); } this(Device device, GdkRegion* handle) { - this.device = device; - this.handle = handle; + this.device = device; + this.handle = handle; } /** @@ -104,12 +104,12 @@ * */ public void add (int[] pointArray) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); //PORTING_FIXME: shall the pointArray be changed to be GdkPoint[] ? - auto polyRgn = OS.gdk_region_polygon(cast(GdkPoint*)pointArray.ptr, pointArray.length / 2, OS.GDK_EVEN_ODD_RULE); - OS.gdk_region_union(handle, polyRgn); - OS.gdk_region_destroy(polyRgn); + auto polyRgn = OS.gdk_region_polygon(cast(GdkPoint*)pointArray.ptr, pointArray.length / 2, OS.GDK_EVEN_ODD_RULE); + OS.gdk_region_union(handle, polyRgn); + OS.gdk_region_destroy(polyRgn); } /** @@ -127,9 +127,9 @@ * */ public void add(Rectangle rect) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - add (rect.x, rect.y, rect.width, rect.height); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + add (rect.x, rect.y, rect.width, rect.height); } /** @@ -151,14 +151,14 @@ * @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); - GdkRectangle* gdkRect = new GdkRectangle(); - gdkRect.x = x; - gdkRect.y = y; - gdkRect.width = width; - gdkRect.height = height; - OS.gdk_region_union_with_rect(handle, gdkRect); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + GdkRectangle* gdkRect = new GdkRectangle(); + gdkRect.x = x; + gdkRect.y = y; + gdkRect.width = width; + gdkRect.height = height; + OS.gdk_region_union_with_rect(handle, gdkRect); } /** @@ -177,10 +177,10 @@ * */ public void add(Region region) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - OS.gdk_region_union(handle, region.handle); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.gdk_region_union(handle, region.handle); } /** @@ -197,8 +197,8 @@ * */ public bool contains(int x, int y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return cast(bool)OS.gdk_region_point_in(handle, x, y); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return cast(bool)OS.gdk_region_point_in(handle, x, y); } /** @@ -217,8 +217,8 @@ * */ public bool contains(Point pt) { - if (pt is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return contains(pt.x, pt.y); + if (pt is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return contains(pt.x, pt.y); } /** @@ -227,12 +227,12 @@ * they allocate. */ public void dispose() { - if (handle is null) return; - if (device.isDisposed()) return; - OS.gdk_region_destroy(handle); - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null) return; + if (device.isDisposed()) return; + OS.gdk_region_destroy(handle); + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -246,8 +246,8 @@ * @see #hashCode */ public int opEquals(Object object) { - if (this is object) return true; - if ( auto region = cast(Region)object ){ + if (this is object) return true; + if ( auto region = cast(Region)object ){ return handle is region.handle; } return false; @@ -267,14 +267,14 @@ * @see Rectangle#union */ public Rectangle getBounds() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - GdkRectangle* gdkRect = new GdkRectangle(); - OS.gdk_region_get_clipbox(handle, gdkRect); - return new Rectangle(gdkRect.x, gdkRect.y, gdkRect.width, gdkRect.height); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + GdkRectangle* gdkRect = new GdkRectangle(); + OS.gdk_region_get_clipbox(handle, gdkRect); + return new Rectangle(gdkRect.x, gdkRect.y, gdkRect.width, gdkRect.height); } public static Region gtk_new(Device device, GdkRegion* handle) { - return new Region(device, handle); + return new Region(device, handle); } /** @@ -288,7 +288,7 @@ * @see #equals */ public override hash_t toHash() { - return cast(hash_t)handle; + return cast(hash_t)handle; } /** @@ -308,9 +308,9 @@ * @since 3.0 */ public void intersect(Rectangle rect) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - intersect (rect.x, rect.y, rect.width, rect.height); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + intersect (rect.x, rect.y, rect.width, rect.height); } /** @@ -332,16 +332,16 @@ * @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); - GdkRectangle* gdkRect = new GdkRectangle(); - gdkRect.x = x; - gdkRect.y = y; - gdkRect.width = width; - gdkRect.height = height; - auto rectRgn = OS.gdk_region_rectangle(gdkRect); - OS.gdk_region_intersect(handle, rectRgn); - OS.gdk_region_destroy(rectRgn); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + GdkRectangle* gdkRect = new GdkRectangle(); + gdkRect.x = x; + gdkRect.y = y; + gdkRect.width = width; + gdkRect.height = height; + auto rectRgn = OS.gdk_region_rectangle(gdkRect); + OS.gdk_region_intersect(handle, rectRgn); + OS.gdk_region_destroy(rectRgn); } /** @@ -362,10 +362,10 @@ * @since 3.0 */ public void intersect(Region region) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - OS.gdk_region_intersect(handle, region.handle); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.gdk_region_intersect(handle, region.handle); } /** @@ -386,13 +386,13 @@ * @see Rectangle#intersects(Rectangle) */ public bool intersects (int x, int y, int width, int height) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - GdkRectangle* gdkRect = new GdkRectangle(); - gdkRect.x = x; - gdkRect.y = y; - gdkRect.width = width; - gdkRect.height = height; - return OS.gdk_region_rect_in(handle, gdkRect) != OS.GDK_OVERLAP_RECTANGLE_OUT; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + GdkRectangle* gdkRect = new GdkRectangle(); + gdkRect.x = x; + gdkRect.y = y; + gdkRect.width = width; + gdkRect.height = height; + return OS.gdk_region_rect_in(handle, gdkRect) != OS.GDK_OVERLAP_RECTANGLE_OUT; } /** * Returns true if the given rectangle intersects @@ -412,8 +412,8 @@ * @see Rectangle#intersects(Rectangle) */ public bool intersects(Rectangle rect) { - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return intersects(rect.x, rect.y, rect.width, rect.height); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return intersects(rect.x, rect.y, rect.width, rect.height); } /** @@ -427,7 +427,7 @@ * @return true when the region is disposed, and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -442,8 +442,8 @@ * */ public bool isEmpty() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - return cast(bool)OS.gdk_region_empty(handle); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + return cast(bool)OS.gdk_region_empty(handle); } /** @@ -462,11 +462,11 @@ * @since 3.0 */ public void subtract (int[] pointArray) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - auto polyRgn = OS.gdk_region_polygon( cast(GdkPoint*)pointArray.ptr, pointArray.length / 2, OS.GDK_EVEN_ODD_RULE); - OS.gdk_region_subtract(handle, polyRgn); - OS.gdk_region_destroy(polyRgn); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + auto polyRgn = OS.gdk_region_polygon( cast(GdkPoint*)pointArray.ptr, pointArray.length / 2, OS.GDK_EVEN_ODD_RULE); + OS.gdk_region_subtract(handle, polyRgn); + OS.gdk_region_destroy(polyRgn); } /** @@ -486,9 +486,9 @@ * @since 3.0 */ public void subtract(Rectangle rect) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - subtract (rect.x, rect.y, rect.width, rect.height); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (rect is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + subtract (rect.x, rect.y, rect.width, rect.height); } /** @@ -510,16 +510,16 @@ * @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); - GdkRectangle* gdkRect = new GdkRectangle(); - gdkRect.x = x; - gdkRect.y = y; - gdkRect.width = width; - gdkRect.height = height; - auto rectRgn = OS.gdk_region_rectangle(gdkRect); - OS.gdk_region_subtract(handle, rectRgn); - OS.gdk_region_destroy(rectRgn); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (width < 0 || height < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + GdkRectangle* gdkRect = new GdkRectangle(); + gdkRect.x = x; + gdkRect.y = y; + gdkRect.width = width; + gdkRect.height = height; + auto rectRgn = OS.gdk_region_rectangle(gdkRect); + OS.gdk_region_subtract(handle, rectRgn); + OS.gdk_region_destroy(rectRgn); } /** @@ -540,10 +540,10 @@ * @since 3.0 */ public void subtract(Region region) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - OS.gdk_region_subtract(handle, region.handle); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (region is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (region.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.gdk_region_subtract(handle, region.handle); } /** @@ -560,8 +560,8 @@ * @since 3.1 */ public void translate (int x, int y) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - OS.gdk_region_offset (handle, x, y); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + OS.gdk_region_offset (handle, x, y); } /** @@ -580,9 +580,9 @@ * @since 3.1 */ public void translate (Point pt) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pt is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - translate (pt.x, pt.y); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pt is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + translate (pt.x, pt.y); } /** @@ -592,7 +592,7 @@ * @return a string representation of the receiver */ public override char[] toString () { - if (isDisposed()) return "Region {*DISPOSED*}"; - return Format( "Region {{{}}", handle ); + if (isDisposed()) return "Region {*DISPOSED*}"; + return Format( "Region {{{}}", handle ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Resource.d --- a/dwt/graphics/Resource.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Resource.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -39,10 +39,10 @@ */ public abstract class Resource { - /** - * the device where this resource was created - */ - Device device; + /** + * the device where this resource was created + */ + Device device; /** * Disposes of the operating system resources associated with @@ -60,9 +60,9 @@ * @since 3.2 */ public Device getDevice() { - Device device = this.device; - if (device is null || isDisposed ()) SWT.error (SWT.ERROR_GRAPHIC_DISPOSED); - return device; + Device device = this.device; + if (device is null || isDisposed ()) SWT.error (SWT.ERROR_GRAPHIC_DISPOSED); + return device; } /** diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/TextLayout.d --- a/dwt/graphics/TextLayout.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/TextLayout.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -50,25 +50,25 @@ */ public final class TextLayout : Resource { - static class StyleItem { - TextStyle style; - int start; + static class StyleItem { + TextStyle style; + int start; - public char[] toString () { - return Format( "StyleItem {{{}, {}}", start, style ); - } - } + public char[] toString () { + return Format( "StyleItem {{{}, {}}", start, style ); + } + } - Font font; - char[] text; - int ascent, descent; - int[] segments; - int[] tabs; - StyleItem[] styles; - PangoLayout* layout; + Font font; + char[] text; + int ascent, descent; + int[] segments; + int[] tabs; + StyleItem[] styles; + PangoLayout* layout; PangoContext* context; PangoAttrList* attrList; - int[] invalidOffsets; + int[] invalidOffsets; static const wchar LTR_MARK = '\u200E', RTL_MARK = '\u200F', ZWS = '\u200B', ZWNBS = '\uFEFF'; /** @@ -86,165 +86,165 @@ * @see #dispose() */ public this (Device device) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - context = OS.gdk_pango_context_get(); - if (context is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.pango_context_set_language(context, OS.gtk_get_default_language()); - OS.pango_context_set_base_dir(context, OS.PANGO_DIRECTION_LTR); - OS.gdk_pango_context_set_colormap(context, OS.gdk_colormap_get_system()); - layout = OS.pango_layout_new(context); - if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); - OS.pango_layout_set_wrap(layout, OS.PANGO_WRAP_WORD_CHAR); - OS.pango_layout_set_tabs(layout, device.emptyTab); - if (OS.GTK_VERSION >= OS.buildVERSION(2, 4, 0)) { - OS.pango_layout_set_auto_dir(layout, false); - } - text = ""; - ascent = descent = -1; - styles = new StyleItem[2]; - styles[0] = new StyleItem(); - styles[1] = new StyleItem(); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + context = OS.gdk_pango_context_get(); + if (context is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.pango_context_set_language(context, OS.gtk_get_default_language()); + OS.pango_context_set_base_dir(context, OS.PANGO_DIRECTION_LTR); + OS.gdk_pango_context_set_colormap(context, OS.gdk_colormap_get_system()); + layout = OS.pango_layout_new(context); + if (layout is null) SWT.error(SWT.ERROR_NO_HANDLES); + OS.pango_layout_set_wrap(layout, OS.PANGO_WRAP_WORD_CHAR); + OS.pango_layout_set_tabs(layout, device.emptyTab); + if (OS.GTK_VERSION >= OS.buildVERSION(2, 4, 0)) { + OS.pango_layout_set_auto_dir(layout, false); + } + text = ""; + ascent = descent = -1; + styles = new StyleItem[2]; + styles[0] = new StyleItem(); + styles[1] = new StyleItem(); + if (device.tracking) device.new_Object(this); } void checkLayout() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); } void computeRuns () { - if (attrList !is null) return; - char[] segmentsText = getSegmentsText(); - OS.pango_layout_set_text (layout, toStringz(segmentsText), segmentsText.length); - if (styles.length == 2 && styles[0].style == null && ascent == -1 && descent == -1 && segments == null) return; - auto ptr = OS.pango_layout_get_text(layout); - attrList = OS.pango_attr_list_new(); - //PangoAttribute* attribute = new PangoAttribute(); - wchar[] charsW = null; + if (attrList !is null) return; + char[] segmentsText = getSegmentsText(); + OS.pango_layout_set_text (layout, toStringz(segmentsText), segmentsText.length); + if (styles.length == 2 && styles[0].style == null && ascent == -1 && descent == -1 && segments == null) return; + auto ptr = OS.pango_layout_get_text(layout); + attrList = OS.pango_attr_list_new(); + //PangoAttribute* attribute = new PangoAttribute(); + wchar[] charsW = null; wchar[] segmentsTextW = toString16( segmentsText ); - int segementsWLength = segmentsTextW.length; - if ((ascent != -1 || descent != -1) && segementsWLength > 0) { - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - PangoRectangle* rect = new PangoRectangle(); - if (ascent != -1) rect.y = -(ascent * OS.PANGO_SCALE); - rect.height = (Math.max(0, ascent) + Math.max(0, descent)) * OS.PANGO_SCALE; - int lineCount = OS.pango_layout_get_line_count(layout); - charsW = new wchar[segementsWLength + lineCount * 2]; - int oldPos = 0, count = 0; - do { - int bytePos = OS.pango_layout_iter_get_index(iter); - /* Note: The length in bytes of ZWS and ZWNBS are both equals to 3 */ - int offset = count * 6; - PangoAttribute* attr = OS.pango_attr_shape_new (rect, rect); - attr.start_index = bytePos + offset; - attr.end_index = bytePos + offset + 3; - OS.pango_attr_list_insert(attrList, attr); - attr = OS.pango_attr_shape_new (rect, rect); - attr.start_index = bytePos + offset + 3; - attr.end_index = bytePos + offset + 6; - OS.pango_attr_list_insert(attrList, attr); - int pos = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); - charsW[pos + count * 2] = ZWS; - charsW[pos + count * 2 + 1] = ZWNBS; + int segementsWLength = segmentsTextW.length; + if ((ascent != -1 || descent != -1) && segementsWLength > 0) { + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + PangoRectangle* rect = new PangoRectangle(); + if (ascent != -1) rect.y = -(ascent * OS.PANGO_SCALE); + rect.height = (Math.max(0, ascent) + Math.max(0, descent)) * OS.PANGO_SCALE; + int lineCount = OS.pango_layout_get_line_count(layout); + charsW = new wchar[segementsWLength + lineCount * 2]; + int oldPos = 0, count = 0; + do { + int bytePos = OS.pango_layout_iter_get_index(iter); + /* Note: The length in bytes of ZWS and ZWNBS are both equals to 3 */ + int offset = count * 6; + PangoAttribute* attr = OS.pango_attr_shape_new (rect, rect); + attr.start_index = bytePos + offset; + attr.end_index = bytePos + offset + 3; + OS.pango_attr_list_insert(attrList, attr); + attr = OS.pango_attr_shape_new (rect, rect); + attr.start_index = bytePos + offset + 3; + attr.end_index = bytePos + offset + 6; + OS.pango_attr_list_insert(attrList, attr); + int pos = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); + charsW[pos + count * 2] = ZWS; + charsW[pos + count * 2 + 1] = ZWNBS; charsW[ oldPos + count*2 .. oldPos + count*2 + pos - oldPos ] = segmentsTextW[ oldPos .. pos ]; - //segmentsTextW.getChars(oldPos, pos, chars, oldPos + count * 2); - oldPos = pos; - count++; - } while (OS.pango_layout_iter_next_line(iter)); - OS.pango_layout_iter_free (iter); + //segmentsTextW.getChars(oldPos, pos, chars, oldPos + count * 2); + oldPos = pos; + count++; + } while (OS.pango_layout_iter_next_line(iter)); + OS.pango_layout_iter_free (iter); charsW[ oldPos + count*2 .. oldPos + count*2 + segementsWLength - oldPos ] = segmentsTextW[ oldPos .. segementsWLength ]; - //segmentsTextW.getChars(oldPos, segementsWLength, chars, oldPos + count * 2); - char[] buffer = .toString( charsW );// Converter.wcsToMbcs(null, chars, false); - OS.pango_layout_set_text (layout, buffer.ptr, buffer.length); - ptr = OS.pango_layout_get_text(layout); - } else { - charsW = segmentsTextW.dup; - } - int offsetCount = 0; - for (int i = 0; i < charsW.length; i++) { - wchar c = charsW[i]; - if (c == LTR_MARK || c == RTL_MARK || c == ZWNBS || c == ZWS) { - offsetCount++; - } - } - invalidOffsets = new int[offsetCount]; - offsetCount = 0; - for (int i = 0; i < charsW.length; i++) { - wchar c = charsW[i]; - if (c == LTR_MARK || c == RTL_MARK || c == ZWNBS || c == ZWS) { - invalidOffsets[offsetCount++] = i; - } - } - int slen = strlen(ptr); - for (int i = 0; i < styles.length - 1; i++) { - StyleItem styleItem = styles[i]; - TextStyle style = styleItem.style; - if (style == null) continue; - int start = translateOffset(styleItem.start); - int end = translateOffset(styles[i+1].start - 1); - int byteStart = (OS.g_utf8_offset_to_pointer(ptr, start) - ptr); - int byteEnd = (OS.g_utf8_offset_to_pointer(ptr, end + 1) - ptr); - byteStart = Math.min(byteStart, slen); - byteEnd = Math.min(byteEnd, slen); - Font font = style.font; - if (font != null && !font.isDisposed()) { - auto attr = OS.pango_attr_font_desc_new (font.handle); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - if (style.underline) { - auto attr = OS.pango_attr_underline_new(OS.PANGO_UNDERLINE_SINGLE); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - if (style.strikeout) { - auto attr = OS.pango_attr_strikethrough_new(true); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - Color foreground = style.foreground; - if (foreground != null && !foreground.isDisposed()) { - GdkColor* fg = foreground.handle; - auto attr = OS.pango_attr_foreground_new(fg.red, fg.green, fg.blue); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - Color background = style.background; - if (background != null && !background.isDisposed()) { - GdkColor* bg = background.handle; - auto attr = OS.pango_attr_background_new(bg.red, bg.green, bg.blue); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - GlyphMetrics metrics = style.metrics; - if (metrics != null) { - PangoRectangle* rect = new PangoRectangle(); - rect.y = -(metrics.ascent * OS.PANGO_SCALE); - rect.height = (metrics.ascent + metrics.descent) * OS.PANGO_SCALE; - rect.width = metrics.width * OS.PANGO_SCALE; - auto attr = OS.pango_attr_shape_new (rect, rect); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - int rise = style.rise; - if (rise != 0) { - auto attr = OS.pango_attr_rise_new (rise * OS.PANGO_SCALE); - attr.start_index = byteStart; - attr.end_index = byteEnd; - OS.pango_attr_list_insert(attrList, attr); - } - } - OS.pango_layout_set_attributes(layout, attrList); + //segmentsTextW.getChars(oldPos, segementsWLength, chars, oldPos + count * 2); + char[] buffer = .toString( charsW );// Converter.wcsToMbcs(null, chars, false); + OS.pango_layout_set_text (layout, buffer.ptr, buffer.length); + ptr = OS.pango_layout_get_text(layout); + } else { + charsW = segmentsTextW.dup; + } + int offsetCount = 0; + for (int i = 0; i < charsW.length; i++) { + wchar c = charsW[i]; + if (c == LTR_MARK || c == RTL_MARK || c == ZWNBS || c == ZWS) { + offsetCount++; + } + } + invalidOffsets = new int[offsetCount]; + offsetCount = 0; + for (int i = 0; i < charsW.length; i++) { + wchar c = charsW[i]; + if (c == LTR_MARK || c == RTL_MARK || c == ZWNBS || c == ZWS) { + invalidOffsets[offsetCount++] = i; + } + } + int slen = strlen(ptr); + for (int i = 0; i < styles.length - 1; i++) { + StyleItem styleItem = styles[i]; + TextStyle style = styleItem.style; + if (style == null) continue; + int start = translateOffset(styleItem.start); + int end = translateOffset(styles[i+1].start - 1); + int byteStart = (OS.g_utf8_offset_to_pointer(ptr, start) - ptr); + int byteEnd = (OS.g_utf8_offset_to_pointer(ptr, end + 1) - ptr); + byteStart = Math.min(byteStart, slen); + byteEnd = Math.min(byteEnd, slen); + Font font = style.font; + if (font != null && !font.isDisposed()) { + auto attr = OS.pango_attr_font_desc_new (font.handle); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + if (style.underline) { + auto attr = OS.pango_attr_underline_new(OS.PANGO_UNDERLINE_SINGLE); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + if (style.strikeout) { + auto attr = OS.pango_attr_strikethrough_new(true); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + Color foreground = style.foreground; + if (foreground != null && !foreground.isDisposed()) { + GdkColor* fg = foreground.handle; + auto attr = OS.pango_attr_foreground_new(fg.red, fg.green, fg.blue); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + Color background = style.background; + if (background != null && !background.isDisposed()) { + GdkColor* bg = background.handle; + auto attr = OS.pango_attr_background_new(bg.red, bg.green, bg.blue); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + GlyphMetrics metrics = style.metrics; + if (metrics != null) { + PangoRectangle* rect = new PangoRectangle(); + rect.y = -(metrics.ascent * OS.PANGO_SCALE); + rect.height = (metrics.ascent + metrics.descent) * OS.PANGO_SCALE; + rect.width = metrics.width * OS.PANGO_SCALE; + auto attr = OS.pango_attr_shape_new (rect, rect); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + int rise = style.rise; + if (rise != 0) { + auto attr = OS.pango_attr_rise_new (rise * OS.PANGO_SCALE); + attr.start_index = byteStart; + attr.end_index = byteEnd; + OS.pango_attr_list_insert(attrList, attr); + } + } + OS.pango_layout_set_attributes(layout, attrList); } /** @@ -252,17 +252,17 @@ * the text layout. Applications must dispose of all allocated text layouts. */ public void dispose() { - if (layout is null) return; - font = null; - text = null; - styles = null; - freeRuns(); - if (layout !is null) OS.g_object_unref(layout); - layout = null; - if (context !is null) OS.g_object_unref(context); - context = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (layout is null) return; + font = null; + text = null; + styles = null; + freeRuns(); + if (layout !is null) OS.g_object_unref(layout); + layout = null; + if (context !is null) OS.g_object_unref(context); + context = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -281,7 +281,7 @@ * */ public void draw(GC gc, int x, int y) { - draw(gc, x, y, -1, -1, null, null); + draw(gc, x, y, -1, -1, null, null); } /** @@ -304,7 +304,7 @@ * */ 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); + draw(gc, x, y, selectionStart, selectionEnd, selectionForeground, selectionBackground, 0); } /** @@ -335,160 +335,160 @@ * @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 is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (selectionForeground !is null && selectionForeground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (selectionBackground !is null && selectionBackground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - gc.checkGC(GC.FOREGROUND); - int length = text.length; - bool hasSelection = selectionStart <= selectionEnd && selectionStart != -1 && selectionEnd != -1; - GCData data = gc.data; - auto cairo = data.cairo; - if (flags != 0 && (hasSelection || (flags & SWT.LAST_LINE_SELECTION) != 0)) { - PangoLogAttr* attrs; - int nAttrs; - PangoLogAttr* logAttr = new PangoLogAttr(); - PangoRectangle* rect = new PangoRectangle(); - int lineCount = OS.pango_layout_get_line_count(layout); - auto ptr = OS.pango_layout_get_text(layout); - auto iter = OS.pango_layout_get_iter(layout); - if (selectionBackground == null) selectionBackground = device.getSystemColor(SWT.COLOR_LIST_SELECTION); - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - Cairo.cairo_save(cairo); - GdkColor* color = selectionBackground.handle; - Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / cast(float)0xFFFF, (color.green & 0xFFFF) / cast(float)0xFFFF, (color.blue & 0xFFFF) / cast(float)0xFFFF, data.alpha / cast(float)0xFF); - } else { - OS.gdk_gc_set_foreground(gc.handle, selectionBackground.handle); - } - int lineIndex = 0; - do { - int lineEnd; - OS.pango_layout_iter_get_line_extents(iter, null, rect); - if (OS.pango_layout_iter_next_line(iter)) { - int bytePos = OS.pango_layout_iter_get_index(iter); - lineEnd = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); - } else { - lineEnd = OS.g_utf8_strlen(ptr, -1); - } - bool extent = false; - if (lineIndex == lineCount - 1 && (flags & SWT.LAST_LINE_SELECTION) != 0) { - extent = true; - } else { - if (attrs is null) OS.pango_layout_get_log_attrs(layout, &attrs, &nAttrs); - *logAttr = attrs[lineEnd]; - if (!( logAttr.bitfield0 & 0x01 /* PangoLogAttr.is_line_break is Bit0 */)) { - if (selectionStart <= lineEnd && lineEnd <= selectionEnd) extent = true; - } else { - if (selectionStart <= lineEnd && lineEnd < selectionEnd && (flags & SWT.FULL_SELECTION) != 0) { - extent = true; - } - } - } - if (extent) { - int lineX = x + OS.PANGO_PIXELS(rect.x) + OS.PANGO_PIXELS(rect.width); - int lineY = y + OS.PANGO_PIXELS(rect.y); - int height = OS.PANGO_PIXELS(rect.height); - if (ascent != -1 && descent != -1) { - height = Math.max (height, ascent + descent); - } - int width = (flags & SWT.FULL_SELECTION) != 0 ? 0x7fffffff : height / 3; - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - Cairo.cairo_rectangle(cairo, lineX, lineY, width, height); - Cairo.cairo_fill(cairo); - } else { - OS.gdk_draw_rectangle(data.drawable, gc.handle, 1, lineX, lineY, width, height); - } - } - lineIndex++; - } while (lineIndex < lineCount); - OS.pango_layout_iter_free(iter); - if (attrs !is null) OS.g_free(attrs); - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - Cairo.cairo_restore(cairo); - } else { - OS.gdk_gc_set_foreground(gc.handle, data.foreground); - } - } - if (length == 0) return; - if (!hasSelection) { - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - Cairo.cairo_move_to(cairo, x, y); - OS.pango_cairo_show_layout(cairo, layout); - } else { - OS.gdk_draw_layout(data.drawable, gc.handle, x, y, layout); - } - } else { - selectionStart = Math.min(Math.max(0, selectionStart), length - 1); - selectionEnd = Math.min(Math.max(0, selectionEnd), length - 1); - length = OS.g_utf8_strlen(OS.pango_layout_get_text(layout), -1); - selectionStart = translateOffset(selectionStart); - selectionEnd = translateOffset(selectionEnd); - if (selectionForeground == null) selectionForeground = device.getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT); - if (selectionBackground == null) selectionBackground = device.getSystemColor(SWT.COLOR_LIST_SELECTION); - bool fullSelection = selectionStart == 0 && selectionEnd == length - 1; - if (fullSelection) { - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - auto ptr = OS.pango_layout_get_text(layout); - drawWithCairo(cairo, x, y, 0, strlen(ptr), fullSelection, selectionBackground.handle, selectionForeground.handle); - } else { - OS.gdk_draw_layout_with_colors(data.drawable, gc.handle, x, y, layout, selectionForeground.handle, selectionBackground.handle); - } - } else { - auto ptr = OS.pango_layout_get_text(layout); - int byteSelStart = (OS.g_utf8_offset_to_pointer(ptr, selectionStart) - ptr); - int byteSelEnd = (OS.g_utf8_offset_to_pointer(ptr, selectionEnd + 1) - ptr); - int slen = strlen(ptr); - byteSelStart = Math.min(byteSelStart, slen); - byteSelEnd = Math.min(byteSelEnd, slen); - if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { - drawWithCairo(cairo, x, y, byteSelStart, byteSelEnd, fullSelection, selectionBackground.handle, selectionForeground.handle); - } else { - Region clipping = new Region(); - gc.getClipping(clipping); - OS.gdk_draw_layout(data.drawable, gc.handle, x, y, layout); - int[] ranges = [byteSelStart, byteSelEnd]; - auto rgn = OS.gdk_pango_layout_get_clip_region(layout, x, y, ranges.ptr, ranges.length / 2); - if (rgn !is null) { - OS.gdk_gc_set_clip_region(gc.handle, rgn); - OS.gdk_region_destroy(rgn); - } - OS.gdk_draw_layout_with_colors(data.drawable, gc.handle, x, y, layout, selectionForeground.handle, selectionBackground.handle); - gc.setClipping(clipping); - clipping.dispose(); - } - } - } + checkLayout (); + computeRuns(); + if (gc is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (gc.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (selectionForeground !is null && selectionForeground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (selectionBackground !is null && selectionBackground.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + gc.checkGC(GC.FOREGROUND); + int length = text.length; + bool hasSelection = selectionStart <= selectionEnd && selectionStart != -1 && selectionEnd != -1; + GCData data = gc.data; + auto cairo = data.cairo; + if (flags != 0 && (hasSelection || (flags & SWT.LAST_LINE_SELECTION) != 0)) { + PangoLogAttr* attrs; + int nAttrs; + PangoLogAttr* logAttr = new PangoLogAttr(); + PangoRectangle* rect = new PangoRectangle(); + int lineCount = OS.pango_layout_get_line_count(layout); + auto ptr = OS.pango_layout_get_text(layout); + auto iter = OS.pango_layout_get_iter(layout); + if (selectionBackground == null) selectionBackground = device.getSystemColor(SWT.COLOR_LIST_SELECTION); + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + Cairo.cairo_save(cairo); + GdkColor* color = selectionBackground.handle; + Cairo.cairo_set_source_rgba(cairo, (color.red & 0xFFFF) / cast(float)0xFFFF, (color.green & 0xFFFF) / cast(float)0xFFFF, (color.blue & 0xFFFF) / cast(float)0xFFFF, data.alpha / cast(float)0xFF); + } else { + OS.gdk_gc_set_foreground(gc.handle, selectionBackground.handle); + } + int lineIndex = 0; + do { + int lineEnd; + OS.pango_layout_iter_get_line_extents(iter, null, rect); + if (OS.pango_layout_iter_next_line(iter)) { + int bytePos = OS.pango_layout_iter_get_index(iter); + lineEnd = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); + } else { + lineEnd = OS.g_utf8_strlen(ptr, -1); + } + bool extent = false; + if (lineIndex == lineCount - 1 && (flags & SWT.LAST_LINE_SELECTION) != 0) { + extent = true; + } else { + if (attrs is null) OS.pango_layout_get_log_attrs(layout, &attrs, &nAttrs); + *logAttr = attrs[lineEnd]; + if (!( logAttr.bitfield0 & 0x01 /* PangoLogAttr.is_line_break is Bit0 */)) { + if (selectionStart <= lineEnd && lineEnd <= selectionEnd) extent = true; + } else { + if (selectionStart <= lineEnd && lineEnd < selectionEnd && (flags & SWT.FULL_SELECTION) != 0) { + extent = true; + } + } + } + if (extent) { + int lineX = x + OS.PANGO_PIXELS(rect.x) + OS.PANGO_PIXELS(rect.width); + int lineY = y + OS.PANGO_PIXELS(rect.y); + int height = OS.PANGO_PIXELS(rect.height); + if (ascent != -1 && descent != -1) { + height = Math.max (height, ascent + descent); + } + int width = (flags & SWT.FULL_SELECTION) != 0 ? 0x7fffffff : height / 3; + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + Cairo.cairo_rectangle(cairo, lineX, lineY, width, height); + Cairo.cairo_fill(cairo); + } else { + OS.gdk_draw_rectangle(data.drawable, gc.handle, 1, lineX, lineY, width, height); + } + } + lineIndex++; + } while (lineIndex < lineCount); + OS.pango_layout_iter_free(iter); + if (attrs !is null) OS.g_free(attrs); + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + Cairo.cairo_restore(cairo); + } else { + OS.gdk_gc_set_foreground(gc.handle, data.foreground); + } + } + if (length == 0) return; + if (!hasSelection) { + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + Cairo.cairo_move_to(cairo, x, y); + OS.pango_cairo_show_layout(cairo, layout); + } else { + OS.gdk_draw_layout(data.drawable, gc.handle, x, y, layout); + } + } else { + selectionStart = Math.min(Math.max(0, selectionStart), length - 1); + selectionEnd = Math.min(Math.max(0, selectionEnd), length - 1); + length = OS.g_utf8_strlen(OS.pango_layout_get_text(layout), -1); + selectionStart = translateOffset(selectionStart); + selectionEnd = translateOffset(selectionEnd); + if (selectionForeground == null) selectionForeground = device.getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT); + if (selectionBackground == null) selectionBackground = device.getSystemColor(SWT.COLOR_LIST_SELECTION); + bool fullSelection = selectionStart == 0 && selectionEnd == length - 1; + if (fullSelection) { + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + auto ptr = OS.pango_layout_get_text(layout); + drawWithCairo(cairo, x, y, 0, strlen(ptr), fullSelection, selectionBackground.handle, selectionForeground.handle); + } else { + OS.gdk_draw_layout_with_colors(data.drawable, gc.handle, x, y, layout, selectionForeground.handle, selectionBackground.handle); + } + } else { + auto ptr = OS.pango_layout_get_text(layout); + int byteSelStart = (OS.g_utf8_offset_to_pointer(ptr, selectionStart) - ptr); + int byteSelEnd = (OS.g_utf8_offset_to_pointer(ptr, selectionEnd + 1) - ptr); + int slen = strlen(ptr); + byteSelStart = Math.min(byteSelStart, slen); + byteSelEnd = Math.min(byteSelEnd, slen); + if (cairo !is null && OS.GTK_VERSION >= OS.buildVERSION(2, 8, 0)) { + drawWithCairo(cairo, x, y, byteSelStart, byteSelEnd, fullSelection, selectionBackground.handle, selectionForeground.handle); + } else { + Region clipping = new Region(); + gc.getClipping(clipping); + OS.gdk_draw_layout(data.drawable, gc.handle, x, y, layout); + int[] ranges = [byteSelStart, byteSelEnd]; + auto rgn = OS.gdk_pango_layout_get_clip_region(layout, x, y, ranges.ptr, ranges.length / 2); + if (rgn !is null) { + OS.gdk_gc_set_clip_region(gc.handle, rgn); + OS.gdk_region_destroy(rgn); + } + OS.gdk_draw_layout_with_colors(data.drawable, gc.handle, x, y, layout, selectionForeground.handle, selectionBackground.handle); + gc.setClipping(clipping); + clipping.dispose(); + } + } + } } void drawWithCairo(cairo_t* cairo, int x, int y, int byteSelStart, int byteSelEnd, bool fullSelection, GdkColor* selectionBackground, GdkColor* selectionForeground) { - Cairo.cairo_save(cairo); - if (!fullSelection) { - Cairo.cairo_move_to(cairo, x, y); - OS.pango_cairo_show_layout(cairo, layout); - } - int[] ranges = [byteSelStart, byteSelEnd]; - auto rgn = OS.gdk_pango_layout_get_clip_region(layout, x, y, ranges.ptr, ranges.length / 2); - if (rgn !is null) { - OS.gdk_cairo_region(cairo, rgn); - Cairo.cairo_clip(cairo); - OS.gdk_cairo_set_source_color(cairo, selectionBackground); - Cairo.cairo_paint(cairo); - OS.gdk_region_destroy(rgn); - } - OS.gdk_cairo_set_source_color(cairo, selectionForeground); - Cairo.cairo_move_to(cairo, x, y); - OS.pango_cairo_show_layout(cairo, layout); - Cairo.cairo_restore(cairo); + Cairo.cairo_save(cairo); + if (!fullSelection) { + Cairo.cairo_move_to(cairo, x, y); + OS.pango_cairo_show_layout(cairo, layout); + } + int[] ranges = [byteSelStart, byteSelEnd]; + auto rgn = OS.gdk_pango_layout_get_clip_region(layout, x, y, ranges.ptr, ranges.length / 2); + if (rgn !is null) { + OS.gdk_cairo_region(cairo, rgn); + Cairo.cairo_clip(cairo); + OS.gdk_cairo_set_source_color(cairo, selectionBackground); + Cairo.cairo_paint(cairo); + OS.gdk_region_destroy(rgn); + } + OS.gdk_cairo_set_source_color(cairo, selectionForeground); + Cairo.cairo_move_to(cairo, x, y); + OS.pango_cairo_show_layout(cairo, layout); + Cairo.cairo_restore(cairo); } void freeRuns() { - if (attrList is null) return; - OS.pango_layout_set_attributes(layout, null ); - OS.pango_attr_list_unref(attrList); - attrList = null; - invalidOffsets = null; + if (attrList is null) return; + OS.pango_layout_set_attributes(layout, null ); + OS.pango_attr_list_unref(attrList); + attrList = null; + invalidOffsets = null; } /** @@ -503,14 +503,14 @@ * */ public int getAlignment() { - checkLayout(); - auto alignment = OS.pango_layout_get_alignment(layout); - switch ( cast(int)alignment) { - case OS.PANGO_ALIGN_CENTER: return SWT.CENTER; - case OS.PANGO_ALIGN_RIGHT: return SWT.RIGHT; + checkLayout(); + auto alignment = OS.pango_layout_get_alignment(layout); + switch ( cast(int)alignment) { + case OS.PANGO_ALIGN_CENTER: return SWT.CENTER; + case OS.PANGO_ALIGN_RIGHT: return SWT.RIGHT; default: - } - return SWT.LEFT; + } + return SWT.LEFT; } /** @@ -528,8 +528,8 @@ * @see #getLineMetrics(int) */ public int getAscent () { - checkLayout(); - return ascent; + checkLayout(); + return ascent; } /** @@ -542,17 +542,17 @@ * */ public Rectangle getBounds() { - checkLayout(); - computeRuns(); - int w, h; - OS.pango_layout_get_size(layout, &w, &h); - int wrapWidth = OS.pango_layout_get_width(layout); - int width = OS.PANGO_PIXELS(wrapWidth != -1 ? wrapWidth : w); - int height = OS.PANGO_PIXELS(h); - if (ascent != -1 && descent != -1) { - height = Math.max (height, ascent + descent); - } - return new Rectangle(0, 0, width, height); + checkLayout(); + computeRuns(); + int w, h; + OS.pango_layout_get_size(layout, &w, &h); + int wrapWidth = OS.pango_layout_get_width(layout); + int width = OS.PANGO_PIXELS(wrapWidth != -1 ? wrapWidth : w); + int height = OS.PANGO_PIXELS(h); + if (ascent != -1 && descent != -1) { + height = Math.max (height, ascent + descent); + } + return new Rectangle(0, 0, width, height); } /** @@ -570,58 +570,58 @@ * */ 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); - start = translateOffset(start); - end = translateOffset(end); - auto ptr = OS.pango_layout_get_text(layout); - int byteStart = (OS.g_utf8_offset_to_pointer (ptr, start) - ptr); - int byteEnd = (OS.g_utf8_offset_to_pointer (ptr, end + 1) - ptr); - int slen = strlen(ptr); - byteStart = Math.min(byteStart, slen); - byteEnd = Math.min(byteEnd, slen); - int[] ranges = [byteStart, byteEnd]; - auto clipRegion = OS.gdk_pango_layout_get_clip_region(layout, 0, 0, ranges.ptr, 1); - if (clipRegion is null) return new Rectangle(0, 0, 0, 0); - GdkRectangle* rect = new GdkRectangle(); + 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); + start = translateOffset(start); + end = translateOffset(end); + auto ptr = OS.pango_layout_get_text(layout); + int byteStart = (OS.g_utf8_offset_to_pointer (ptr, start) - ptr); + int byteEnd = (OS.g_utf8_offset_to_pointer (ptr, end + 1) - ptr); + int slen = strlen(ptr); + byteStart = Math.min(byteStart, slen); + byteEnd = Math.min(byteEnd, slen); + int[] ranges = [byteStart, byteEnd]; + auto clipRegion = OS.gdk_pango_layout_get_clip_region(layout, 0, 0, ranges.ptr, 1); + if (clipRegion is null) return new Rectangle(0, 0, 0, 0); + GdkRectangle* rect = new GdkRectangle(); - /* - * Bug in Pango. The region returned by gdk_pango_layout_get_clip_region() - * includes areas from lines outside of the requested range. The fix - * is to subtract these areas from the clip region. - */ - PangoRectangle* pangoRect = new PangoRectangle(); - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - auto linesRegion = OS.gdk_region_new(); - if (linesRegion is null) SWT.error(SWT.ERROR_NO_HANDLES); - int lineEnd = 0; - do { - OS.pango_layout_iter_get_line_extents(iter, null, pangoRect); - if (OS.pango_layout_iter_next_line(iter)) { - lineEnd = OS.pango_layout_iter_get_index(iter) - 1; - } else { - lineEnd = slen; - } - if (byteStart > lineEnd) continue; - rect.x = OS.PANGO_PIXELS(pangoRect.x); - rect.y = OS.PANGO_PIXELS(pangoRect.y); - rect.width = OS.PANGO_PIXELS(pangoRect.width); - rect.height = OS.PANGO_PIXELS(pangoRect.height); - OS.gdk_region_union_with_rect(linesRegion, rect); - } while (lineEnd + 1 <= byteEnd); - OS.gdk_region_intersect(clipRegion, linesRegion); - OS.gdk_region_destroy(linesRegion); - OS.pango_layout_iter_free(iter); + /* + * Bug in Pango. The region returned by gdk_pango_layout_get_clip_region() + * includes areas from lines outside of the requested range. The fix + * is to subtract these areas from the clip region. + */ + PangoRectangle* pangoRect = new PangoRectangle(); + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + auto linesRegion = OS.gdk_region_new(); + if (linesRegion is null) SWT.error(SWT.ERROR_NO_HANDLES); + int lineEnd = 0; + do { + OS.pango_layout_iter_get_line_extents(iter, null, pangoRect); + if (OS.pango_layout_iter_next_line(iter)) { + lineEnd = OS.pango_layout_iter_get_index(iter) - 1; + } else { + lineEnd = slen; + } + if (byteStart > lineEnd) continue; + rect.x = OS.PANGO_PIXELS(pangoRect.x); + rect.y = OS.PANGO_PIXELS(pangoRect.y); + rect.width = OS.PANGO_PIXELS(pangoRect.width); + rect.height = OS.PANGO_PIXELS(pangoRect.height); + OS.gdk_region_union_with_rect(linesRegion, rect); + } while (lineEnd + 1 <= byteEnd); + OS.gdk_region_intersect(clipRegion, linesRegion); + OS.gdk_region_destroy(linesRegion); + OS.pango_layout_iter_free(iter); - OS.gdk_region_get_clipbox(clipRegion, rect); - OS.gdk_region_destroy(clipRegion); - return new Rectangle(rect.x, rect.y, rect.width, rect.height); + OS.gdk_region_get_clipbox(clipRegion, rect); + OS.gdk_region_destroy(clipRegion); + return new Rectangle(rect.x, rect.y, rect.width, rect.height); } /** @@ -639,8 +639,8 @@ * @see #getLineMetrics(int) */ public int getDescent () { - checkLayout(); - return descent; + checkLayout(); + return descent; } /** @@ -654,8 +654,8 @@ * */ public Font getFont () { - checkLayout(); - return font; + checkLayout(); + return font; } /** @@ -670,8 +670,8 @@ * @since 3.2 */ public int getIndent () { - checkLayout(); - return OS.PANGO_PIXELS(OS.pango_layout_get_indent(layout)); + checkLayout(); + return OS.PANGO_PIXELS(OS.pango_layout_get_indent(layout)); } /** @@ -686,8 +686,8 @@ * @since 3.2 */ public bool getJustify () { - checkLayout(); - return cast(bool) OS.pango_layout_get_justify(layout); + checkLayout(); + return cast(bool) OS.pango_layout_get_justify(layout); } /** @@ -705,33 +705,33 @@ *
  • ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed
  • */ public int getLevel(int offset) { - checkLayout(); - computeRuns(); - int length = text.length; - if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); - offset = translateOffset(offset); - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - int level = 0; - PangoItem* item = new PangoItem(); - PangoLayoutRun* run = new PangoLayoutRun(); - auto ptr = OS.pango_layout_get_text(layout); - auto byteOffset = OS.g_utf8_offset_to_pointer(ptr, offset) - ptr; - int slen = strlen(ptr); - byteOffset = Math.min(byteOffset, slen); - do { - auto runPtr = OS.pango_layout_iter_get_run(iter); - if (runPtr !is null) { - memmove(run, runPtr, PangoLayoutRun.sizeof); - memmove(item, run.item, PangoItem.sizeof); - if (item.offset <= byteOffset && byteOffset < item.offset + item.length) { - level = item.analysis.level; - break; - } - } - } while (OS.pango_layout_iter_next_run(iter)); - OS.pango_layout_iter_free(iter); - return level; + checkLayout(); + computeRuns(); + int length = text.length; + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + offset = translateOffset(offset); + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + int level = 0; + PangoItem* item = new PangoItem(); + PangoLayoutRun* run = new PangoLayoutRun(); + auto ptr = OS.pango_layout_get_text(layout); + auto byteOffset = OS.g_utf8_offset_to_pointer(ptr, offset) - ptr; + int slen = strlen(ptr); + byteOffset = Math.min(byteOffset, slen); + do { + auto runPtr = OS.pango_layout_iter_get_run(iter); + if (runPtr !is null) { + memmove(run, runPtr, PangoLayoutRun.sizeof); + memmove(item, run.item, PangoItem.sizeof); + if (item.offset <= byteOffset && byteOffset < item.offset + item.length) { + level = item.analysis.level; + break; + } + } + } while (OS.pango_layout_iter_next_run(iter)); + OS.pango_layout_iter_free(iter); + return level; } /** @@ -748,24 +748,24 @@ * */ public Rectangle getLineBounds(int lineIndex) { - checkLayout(); - computeRuns(); - int lineCount = OS.pango_layout_get_line_count(layout); - if (!(0 <= lineIndex && lineIndex < lineCount)) SWT.error(SWT.ERROR_INVALID_RANGE); - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - for (int i = 0; i < lineIndex; i++) OS.pango_layout_iter_next_line(iter); - PangoRectangle* rect = new PangoRectangle(); - OS.pango_layout_iter_get_line_extents(iter, null, rect); - OS.pango_layout_iter_free(iter); - int x = OS.PANGO_PIXELS(rect.x); - int y = OS.PANGO_PIXELS(rect.y); - int width = OS.PANGO_PIXELS(rect.width); - int height = OS.PANGO_PIXELS(rect.height); - if (ascent != -1 && descent != -1) { - height = Math.max (height, ascent + descent); - } - return new Rectangle(x, y, width, height); + checkLayout(); + computeRuns(); + int lineCount = OS.pango_layout_get_line_count(layout); + if (!(0 <= lineIndex && lineIndex < lineCount)) SWT.error(SWT.ERROR_INVALID_RANGE); + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + for (int i = 0; i < lineIndex; i++) OS.pango_layout_iter_next_line(iter); + PangoRectangle* rect = new PangoRectangle(); + OS.pango_layout_iter_get_line_extents(iter, null, rect); + OS.pango_layout_iter_free(iter); + int x = OS.PANGO_PIXELS(rect.x); + int y = OS.PANGO_PIXELS(rect.y); + int width = OS.PANGO_PIXELS(rect.width); + int height = OS.PANGO_PIXELS(rect.height); + if (ascent != -1 && descent != -1) { + height = Math.max (height, ascent + descent); + } + return new Rectangle(x, y, width, height); } /** @@ -779,9 +779,9 @@ * */ public int getLineCount() { - checkLayout (); - computeRuns(); - return OS.pango_layout_get_line_count(layout); + checkLayout (); + computeRuns(); + return OS.pango_layout_get_line_count(layout); } /** @@ -799,24 +799,24 @@ * */ public int getLineIndex(int offset) { - checkLayout (); - computeRuns(); - int length = text.length; - if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - offset = translateOffset(offset); - int line = 0; - auto ptr = OS.pango_layout_get_text(layout); - auto byteOffset = OS.g_utf8_offset_to_pointer(ptr,offset) - ptr; - int slen = strlen(ptr); - byteOffset = Math.min(byteOffset, slen); - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - while (OS.pango_layout_iter_next_line(iter)) { - if (OS.pango_layout_iter_get_index(iter) > byteOffset) break; - line++; - } - OS.pango_layout_iter_free(iter); - return line; + checkLayout (); + computeRuns(); + int length = text.length; + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + offset = translateOffset(offset); + int line = 0; + auto ptr = OS.pango_layout_get_text(layout); + auto byteOffset = OS.g_utf8_offset_to_pointer(ptr,offset) - ptr; + int slen = strlen(ptr); + byteOffset = Math.min(byteOffset, slen); + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + while (OS.pango_layout_iter_next_line(iter)) { + if (OS.pango_layout_iter_get_index(iter) > byteOffset) break; + line++; + } + OS.pango_layout_iter_free(iter); + return line; } /** @@ -833,29 +833,29 @@ * */ public FontMetrics getLineMetrics (int lineIndex) { - checkLayout (); - computeRuns(); - int lineCount = OS.pango_layout_get_line_count(layout); - if (!(0 <= lineIndex && lineIndex < lineCount)) SWT.error(SWT.ERROR_INVALID_RANGE); - int ascent = 0, descent = 0; - PangoLayoutLine* line = new PangoLayoutLine(); - memmove(line, OS.pango_layout_get_line(layout, lineIndex), PangoLayoutLine.sizeof); - if (line.runs is null) { - auto font = this.font != null ? this.font.handle : device.systemFont.handle; - auto lang = OS.pango_context_get_language(context); - auto metrics = OS.pango_context_get_metrics(context, font, lang); - ascent = OS.pango_font_metrics_get_ascent(metrics); - descent = OS.pango_font_metrics_get_descent(metrics); - OS.pango_font_metrics_unref(metrics); - } else { - PangoRectangle* rect = new PangoRectangle(); - OS.pango_layout_line_get_extents(OS.pango_layout_get_line(layout, lineIndex), null, rect); - ascent = -rect.y; - descent = rect.height - ascent; - } - ascent = Math.max(this.ascent, OS.PANGO_PIXELS(ascent)); - descent = Math.max(this.descent, OS.PANGO_PIXELS(descent)); - return FontMetrics.gtk_new(ascent, descent, 0, 0, ascent + descent); + checkLayout (); + computeRuns(); + int lineCount = OS.pango_layout_get_line_count(layout); + if (!(0 <= lineIndex && lineIndex < lineCount)) SWT.error(SWT.ERROR_INVALID_RANGE); + int ascent = 0, descent = 0; + PangoLayoutLine* line = new PangoLayoutLine(); + memmove(line, OS.pango_layout_get_line(layout, lineIndex), PangoLayoutLine.sizeof); + if (line.runs is null) { + auto font = this.font != null ? this.font.handle : device.systemFont.handle; + auto lang = OS.pango_context_get_language(context); + auto metrics = OS.pango_context_get_metrics(context, font, lang); + ascent = OS.pango_font_metrics_get_ascent(metrics); + descent = OS.pango_font_metrics_get_descent(metrics); + OS.pango_font_metrics_unref(metrics); + } else { + PangoRectangle* rect = new PangoRectangle(); + OS.pango_layout_line_get_extents(OS.pango_layout_get_line(layout, lineIndex), null, rect); + ascent = -rect.y; + descent = rect.height - ascent; + } + ascent = Math.max(this.ascent, OS.PANGO_PIXELS(ascent)); + descent = Math.max(this.descent, OS.PANGO_PIXELS(descent)); + return FontMetrics.gtk_new(ascent, descent, 0, 0, ascent + descent); } /** @@ -870,22 +870,22 @@ * */ public int[] getLineOffsets() { - checkLayout(); - computeRuns(); - int lineCount = OS.pango_layout_get_line_count(layout); - int[] offsets = new int [lineCount + 1]; - auto ptr = OS.pango_layout_get_text(layout); - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - int i = 0; - do { - int bytePos = OS.pango_layout_iter_get_index(iter); - int pos = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); - offsets[i++] = untranslateOffset(pos); - } while (OS.pango_layout_iter_next_line(iter)); - OS.pango_layout_iter_free(iter); - offsets[lineCount] = text.length; - return offsets; + checkLayout(); + computeRuns(); + int lineCount = OS.pango_layout_get_line_count(layout); + int[] offsets = new int [lineCount + 1]; + auto ptr = OS.pango_layout_get_text(layout); + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + int i = 0; + do { + int bytePos = OS.pango_layout_iter_get_index(iter); + int pos = OS.g_utf8_pointer_to_offset(ptr, ptr + bytePos); + offsets[i++] = untranslateOffset(pos); + } while (OS.pango_layout_iter_next_line(iter)); + OS.pango_layout_iter_free(iter); + offsets[lineCount] = text.length; + return offsets; } /** @@ -905,20 +905,20 @@ * @see #getOffset(int, int, int[]) */ public Point getLocation(int offset, bool trailing) { - checkLayout(); - computeRuns(); - int length = text.length; - if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); - offset = translateOffset(offset); - auto ptr = OS.pango_layout_get_text(layout); - int byteOffset = (OS.g_utf8_offset_to_pointer(ptr, offset) - ptr); - int slen = strlen(ptr); - byteOffset = Math.min(byteOffset, slen); - PangoRectangle* pos = new PangoRectangle(); - OS.pango_layout_index_to_pos(layout, byteOffset, pos); - int x = trailing ? pos.x + pos.width : pos.x; - int y = pos.y; - return new Point(OS.PANGO_PIXELS(x), OS.PANGO_PIXELS(y)); + checkLayout(); + computeRuns(); + int length = text.length; + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + offset = translateOffset(offset); + auto ptr = OS.pango_layout_get_text(layout); + int byteOffset = (OS.g_utf8_offset_to_pointer(ptr, offset) - ptr); + int slen = strlen(ptr); + byteOffset = Math.min(byteOffset, slen); + PangoRectangle* pos = new PangoRectangle(); + OS.pango_layout_index_to_pos(layout, byteOffset, pos); + int x = trailing ? pos.x + pos.width : pos.x; + int y = pos.y; + return new Point(OS.PANGO_PIXELS(x), OS.PANGO_PIXELS(y)); } /** @@ -941,49 +941,49 @@ * @see #getPreviousOffset(int, int) */ public int getNextOffset (int offset, int movement) { - return _getOffset(offset, movement, true); + return _getOffset(offset, movement, true); } int _getOffset (int offset, int movement, bool forward) { - checkLayout(); - computeRuns(); - int length = text.length; - if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); - if (forward) { - if (offset == length) return length; - } else { - if (offset == 0) return 0; - } - int step = forward ? 1 : -1; - if ((movement & SWT.MOVEMENT_CHAR) != 0) return offset + step; - PangoLogAttr* attrs; - int nAttrs; - OS.pango_layout_get_log_attrs(layout, &attrs, &nAttrs); - if (attrs is null) return offset + step; - length = OS.g_utf8_strlen(OS.pango_layout_get_text(layout), -1); - offset = translateOffset(offset); - PangoLogAttr* logAttr = new PangoLogAttr(); - offset = validateOffset(offset, step); - while (0 < offset && offset < length) { - *logAttr = attrs[ offset ]; - if (((movement & SWT.MOVEMENT_CLUSTER) != 0) && ( logAttr.bitfield0 & (1<<4/*is_cursor_position*/))) break; - if ((movement & SWT.MOVEMENT_WORD) != 0) { - if (forward) { - if (logAttr.bitfield0 & (1<<6/*is_word_end*/)) break; - } else { - if (logAttr.bitfield0 & (1<<5/*is_word_start*/)) break; - } - } - if ((movement & SWT.MOVEMENT_WORD_START) != 0) { - if (logAttr.bitfield0 & (1<<5/*is_word_start*/)) break; - } - if ((movement & SWT.MOVEMENT_WORD_END) != 0) { - if (logAttr.bitfield0 & (1<<6/*is_word_end*/)) break; - } - offset = validateOffset(offset, step); - } - OS.g_free(attrs); - return Math.min(Math.max(0, untranslateOffset(offset)), text.length); + checkLayout(); + computeRuns(); + int length = text.length; + if (!(0 <= offset && offset <= length)) SWT.error(SWT.ERROR_INVALID_RANGE); + if (forward) { + if (offset == length) return length; + } else { + if (offset == 0) return 0; + } + int step = forward ? 1 : -1; + if ((movement & SWT.MOVEMENT_CHAR) != 0) return offset + step; + PangoLogAttr* attrs; + int nAttrs; + OS.pango_layout_get_log_attrs(layout, &attrs, &nAttrs); + if (attrs is null) return offset + step; + length = OS.g_utf8_strlen(OS.pango_layout_get_text(layout), -1); + offset = translateOffset(offset); + PangoLogAttr* logAttr = new PangoLogAttr(); + offset = validateOffset(offset, step); + while (0 < offset && offset < length) { + *logAttr = attrs[ offset ]; + if (((movement & SWT.MOVEMENT_CLUSTER) != 0) && ( logAttr.bitfield0 & (1<<4/*is_cursor_position*/))) break; + if ((movement & SWT.MOVEMENT_WORD) != 0) { + if (forward) { + if (logAttr.bitfield0 & (1<<6/*is_word_end*/)) break; + } else { + if (logAttr.bitfield0 & (1<<5/*is_word_start*/)) break; + } + } + if ((movement & SWT.MOVEMENT_WORD_START) != 0) { + if (logAttr.bitfield0 & (1<<5/*is_word_start*/)) break; + } + if ((movement & SWT.MOVEMENT_WORD_END) != 0) { + if (logAttr.bitfield0 & (1<<6/*is_word_end*/)) break; + } + offset = validateOffset(offset, step); + } + OS.g_free(attrs); + return Math.min(Math.max(0, untranslateOffset(offset)), text.length); } /** @@ -1010,9 +1010,9 @@ * @see #getLocation(int, bool) */ public int getOffset(Point point, int[] trailing) { - checkLayout(); - if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - return getOffset(point.x, point.y, trailing); + checkLayout(); + if (point == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + return getOffset(point.x, point.y, trailing); } /** @@ -1039,41 +1039,41 @@ * @see #getLocation(int, bool) */ public int getOffset(int x, int y, int[] trailing) { - checkLayout(); - computeRuns(); - if (trailing != null && trailing.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + checkLayout(); + computeRuns(); + if (trailing != null && trailing.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - /* - * Feature in GTK. pango_layout_xy_to_index() returns the - * logical end/start offset of a line when the coordinates are outside - * the line bounds. In SWT the correct behavior is to return the closest - * visual offset. The fix is to clamp the coordinates inside the - * line bounds. - */ - auto iter = OS.pango_layout_get_iter(layout); - if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); - PangoRectangle* rect = new PangoRectangle(); - do { - OS.pango_layout_iter_get_line_extents(iter, null, rect); - rect.y = OS.PANGO_PIXELS(rect.y); - rect.height = OS.PANGO_PIXELS(rect.height); - if (rect.y <= y && y < rect.y + rect.height) { - rect.x = OS.PANGO_PIXELS(rect.x); - rect.width = OS.PANGO_PIXELS(rect.width); - if (x >= rect.x + rect.width) x = rect.x + rect.width - 1; - if (x < rect.x) x = rect.x; - break; - } - } while (OS.pango_layout_iter_next_line(iter)); - OS.pango_layout_iter_free(iter); + /* + * Feature in GTK. pango_layout_xy_to_index() returns the + * logical end/start offset of a line when the coordinates are outside + * the line bounds. In SWT the correct behavior is to return the closest + * visual offset. The fix is to clamp the coordinates inside the + * line bounds. + */ + auto iter = OS.pango_layout_get_iter(layout); + if (iter is null) SWT.error(SWT.ERROR_NO_HANDLES); + PangoRectangle* rect = new PangoRectangle(); + do { + OS.pango_layout_iter_get_line_extents(iter, null, rect); + rect.y = OS.PANGO_PIXELS(rect.y); + rect.height = OS.PANGO_PIXELS(rect.height); + if (rect.y <= y && y < rect.y + rect.height) { + rect.x = OS.PANGO_PIXELS(rect.x); + rect.width = OS.PANGO_PIXELS(rect.width); + if (x >= rect.x + rect.width) x = rect.x + rect.width - 1; + if (x < rect.x) x = rect.x; + break; + } + } while (OS.pango_layout_iter_next_line(iter)); + OS.pango_layout_iter_free(iter); - int index; - int piTrailing; - OS.pango_layout_xy_to_index(layout, x * OS.PANGO_SCALE, y * OS.PANGO_SCALE, &index, &piTrailing); - auto ptr = OS.pango_layout_get_text(layout); - int offset = OS.g_utf8_pointer_to_offset(ptr, ptr + index); - if (trailing !is null) trailing[0] = piTrailing; - return untranslateOffset(offset); + int index; + int piTrailing; + OS.pango_layout_xy_to_index(layout, x * OS.PANGO_SCALE, y * OS.PANGO_SCALE, &index, &piTrailing); + auto ptr = OS.pango_layout_get_text(layout); + int offset = OS.g_utf8_pointer_to_offset(ptr, ptr + index); + if (trailing !is null) trailing[0] = piTrailing; + return untranslateOffset(offset); } /** @@ -1086,9 +1086,9 @@ * */ public int getOrientation() { - checkLayout(); - int baseDir = OS.pango_context_get_base_dir(context); - return baseDir == OS.PANGO_DIRECTION_RTL ? SWT.RIGHT_TO_LEFT : SWT.LEFT_TO_RIGHT; + checkLayout(); + int baseDir = OS.pango_context_get_base_dir(context); + return baseDir == OS.PANGO_DIRECTION_RTL ? SWT.RIGHT_TO_LEFT : SWT.LEFT_TO_RIGHT; } /** @@ -1111,7 +1111,7 @@ * @see #getNextOffset(int, int) */ public int getPreviousOffset (int index, int movement) { - return _getOffset(index, movement, false); + return _getOffset(index, movement, false); } /** @@ -1129,21 +1129,21 @@ * @since 3.2 */ public int[] getRanges () { - checkLayout(); - int[] result = new int[styles.length * 2]; - int count = 0; - for (int i=0; i */ public int[] getSegments() { - checkLayout(); - return segments; + checkLayout(); + return segments; } char[] getSegmentsText() { - if (segments is null) return text; - int nSegments = segments.length; - if (nSegments <= 1) return text; - int len = text.length; - if (len == 0) return text; - if (nSegments == 2) { - if (segments[0] == 0 && segments[1] == len) return text; - } - char[] oldChars = text[0..len].dup; - char[] newChars = new char[len + nSegments]; - int charCount = 0, segmentCount = 0; - wchar separator = getOrientation() == SWT.RIGHT_TO_LEFT ? RTL_MARK : LTR_MARK; - while (charCount < len) { - if (segmentCount < nSegments && charCount == segments[segmentCount]) { - newChars[charCount + segmentCount++] = separator; - } else { - newChars[charCount + segmentCount] = oldChars[charCount++]; - } - } - if (segmentCount < nSegments) { - segments[segmentCount] = charCount; - newChars[charCount + segmentCount++] = separator; - } - return newChars[ 0 .. Math.min(charCount + segmentCount, newChars.length) ]; + if (segments is null) return text; + int nSegments = segments.length; + if (nSegments <= 1) return text; + int len = text.length; + if (len == 0) return text; + if (nSegments == 2) { + if (segments[0] == 0 && segments[1] == len) return text; + } + char[] oldChars = text[0..len].dup; + char[] newChars = new char[len + nSegments]; + int charCount = 0, segmentCount = 0; + wchar separator = getOrientation() == SWT.RIGHT_TO_LEFT ? RTL_MARK : LTR_MARK; + while (charCount < len) { + if (segmentCount < nSegments && charCount == segments[segmentCount]) { + newChars[charCount + segmentCount++] = separator; + } else { + newChars[charCount + segmentCount] = oldChars[charCount++]; + } + } + if (segmentCount < nSegments) { + segments[segmentCount] = charCount; + newChars[charCount + segmentCount++] = separator; + } + return newChars[ 0 .. Math.min(charCount + segmentCount, newChars.length) ]; } /** @@ -1197,8 +1197,8 @@ * */ public int getSpacing () { - checkLayout(); - return OS.PANGO_PIXELS(OS.pango_layout_get_spacing(layout)); + checkLayout(); + return OS.PANGO_PIXELS(OS.pango_layout_get_spacing(layout)); } /** @@ -1215,16 +1215,16 @@ * */ 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 offset) { return styles[i - 1].style; } - } - return null; + } + return null; } /** @@ -1241,20 +1241,20 @@ * @since 3.2 */ public TextStyle[] getStyles () { - checkLayout(); - TextStyle[] result = new TextStyle[styles.length]; - int count = 0; - for (int i=0; i */ public int[] getTabs() { - checkLayout(); - return tabs; + checkLayout(); + return tabs; } /** @@ -1282,8 +1282,8 @@ * */ public char[] getText () { - checkLayout (); - return text; + checkLayout (); + return text; } /** @@ -1296,9 +1296,9 @@ * */ public int getWidth () { - checkLayout (); - int width = OS.pango_layout_get_width(layout); - return width != -1 ? OS.PANGO_PIXELS(width) : -1; + checkLayout (); + int width = OS.pango_layout_get_width(layout); + return width != -1 ? OS.PANGO_PIXELS(width) : -1; } /** @@ -1313,7 +1313,7 @@ * @return true when the text layout is disposed and false otherwise */ public bool isDisposed () { - return layout is null; + return layout is null; } /** @@ -1335,19 +1335,19 @@ * @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; - int al = OS.PANGO_ALIGN_LEFT; - switch (alignment) { - case SWT.CENTER: al = OS.PANGO_ALIGN_CENTER; break; - case SWT.RIGHT: al = OS.PANGO_ALIGN_RIGHT; break; + 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; + int al = OS.PANGO_ALIGN_LEFT; + switch (alignment) { + case SWT.CENTER: al = OS.PANGO_ALIGN_CENTER; break; + case SWT.RIGHT: al = OS.PANGO_ALIGN_RIGHT; break; default: - } - OS.pango_layout_set_alignment(layout, al); + } + OS.pango_layout_set_alignment(layout, al); } /** @@ -1369,11 +1369,11 @@ * @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; + checkLayout(); + if (ascent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.ascent == ascent) return; + freeRuns(); + this.ascent = ascent; } /** @@ -1395,11 +1395,11 @@ * @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; + checkLayout(); + if (descent < -1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.descent == descent) return; + freeRuns(); + this.descent = descent; } /** @@ -1419,12 +1419,12 @@ * */ public void setFont (Font font) { - checkLayout (); - if (font !is null && font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (this.font is font) return; - if (font !is null && font == this.font ) return; - this.font = font; - OS.pango_layout_set_font_description(layout, font !is null ? font.handle : null); + checkLayout (); + if (font !is null && font.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (this.font is font) return; + if (font !is null && font == this.font ) return; + this.font = font; + OS.pango_layout_set_font_description(layout, font !is null ? font.handle : null); } @@ -1441,9 +1441,9 @@ * @since 3.2 */ public void setIndent (int indent) { - checkLayout(); - if (indent < 0) return; - OS.pango_layout_set_indent(layout, indent * OS.PANGO_SCALE); + checkLayout(); + if (indent < 0) return; + OS.pango_layout_set_indent(layout, indent * OS.PANGO_SCALE); } /** @@ -1459,8 +1459,8 @@ * @since 3.2 */ public void setJustify (bool justify) { - checkLayout(); - OS.pango_layout_set_justify(layout, justify); + checkLayout(); + OS.pango_layout_set_justify(layout, justify); } /** @@ -1474,15 +1474,15 @@ * */ 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; - int baseDir = orientation == SWT.RIGHT_TO_LEFT ? OS.PANGO_DIRECTION_RTL : OS.PANGO_DIRECTION_LTR; - if (OS.pango_context_get_base_dir(context) == baseDir) return; - OS.pango_context_set_base_dir(context, baseDir); - OS.pango_layout_context_changed(layout); + 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; + int baseDir = orientation == SWT.RIGHT_TO_LEFT ? OS.PANGO_DIRECTION_RTL : OS.PANGO_DIRECTION_LTR; + if (OS.pango_context_get_base_dir(context) == baseDir) return; + OS.pango_context_set_base_dir(context, baseDir); + OS.pango_layout_context_changed(layout); } /** @@ -1499,9 +1499,9 @@ * */ public void setSpacing (int spacing) { - checkLayout(); - if (spacing < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - OS.pango_layout_set_spacing(layout, spacing * OS.PANGO_SCALE); + checkLayout(); + if (spacing < 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + OS.pango_layout_set_spacing(layout, spacing * OS.PANGO_SCALE); } /** @@ -1523,19 +1523,19 @@ * */ 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 */ 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); + 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); - /* - * Bug in Pango. Pango 1.2.2 will cause a segmentation fault if a style - * is not applied for a whole ligature. The fix is to applied the - * style for the whole ligature. - * - * NOTE that fix only LamAlef ligatures. - */ - if (start > 0 && isAlef(text[start]) && isLam(text[start - 1])) { - start--; - } - if (end < length - 1 && isLam(text[end]) && isAlef(text[end + 1])) { - end++; - } + /* + * Bug in Pango. Pango 1.2.2 will cause a segmentation fault if a style + * is not applied for a whole ligature. The fix is to applied the + * style for the whole ligature. + * + * NOTE that fix only LamAlef ligatures. + */ + if (start > 0 && isAlef(text[start]) && isLam(text[start - 1])) { + start--; + } + if (end < length - 1 && isLam(text[end]) && isAlef(text[end + 1])) { + end++; + } - 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 is start && styles[high + 1].start - 1 == end) { - if (style is null) { - if (item.style is null) return; - } else { - if (style==item.style) return; - } - } - } - freeRuns(); - int modifyStart = high; - int modifyEnd = modifyStart; - while (modifyEnd < styles.length) { - if (styles[modifyEnd + 1].start > end) break; - modifyEnd++; - } - if (modifyStart is modifyEnd) { - int styleStart = styles[modifyStart].start; - int styleEnd = styles[modifyEnd + 1].start - 1; - if (styleStart is start && styleEnd is end) { - styles[modifyStart].style = style; - return; - } - if (styleStart !is start && styleEnd !is end) { - StyleItem[] newStyles = new StyleItem[styles.length + 2]; + 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 is start && styles[high + 1].start - 1 == end) { + if (style is null) { + if (item.style is null) return; + } else { + if (style==item.style) return; + } + } + } + freeRuns(); + int modifyStart = high; + int modifyEnd = modifyStart; + while (modifyEnd < styles.length) { + if (styles[modifyEnd + 1].start > end) break; + modifyEnd++; + } + if (modifyStart is modifyEnd) { + int styleStart = styles[modifyStart].start; + int styleEnd = styles[modifyEnd + 1].start - 1; + if (styleStart is start && styleEnd is end) { + styles[modifyStart].style = style; + return; + } + if (styleStart !is start && styleEnd !is 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; + 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 is styles[modifyStart].start) modifyStart--; - if (end is styles[modifyEnd + 1].start - 1) modifyEnd++; - int newLength = styles.length + 1 - (modifyEnd - modifyStart - 1); - StyleItem[] newStyles = new StyleItem[newLength]; + styles = newStyles; + return; + } + } + if (start is styles[modifyStart].start) modifyStart--; + if (end is 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; + 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; + styles = newStyles; } /** @@ -1649,36 +1649,36 @@ * */ 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 */ public void setText (char[] text) { - checkLayout (); - if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (text==/*eq*/this.text) return; - freeRuns(); - this.text = text; - styles = new StyleItem[2]; - styles[0] = new StyleItem(); - styles[1] = new StyleItem(); - styles[styles.length - 1].start = text.length; + checkLayout (); + if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (text==/*eq*/this.text) return; + freeRuns(); + this.text = text; + styles = new StyleItem[2]; + styles[0] = new StyleItem(); + styles[1] = new StyleItem(); + styles[styles.length - 1].start = text.length; } /** @@ -1722,32 +1722,32 @@ * @see #setAlignment(int) */ public void setWidth (int width) { - checkLayout (); - if (width < -1 || width == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - freeRuns(); - OS.pango_layout_set_width(layout, width == -1 ? -1 : width * OS.PANGO_SCALE); + checkLayout (); + if (width < -1 || width == 0) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + freeRuns(); + OS.pango_layout_set_width(layout, width == -1 ? -1 : width * OS.PANGO_SCALE); } static final bool isLam(int ch) { - return ch == 0x0644; + return ch == 0x0644; } static final bool isAlef(int ch) { - switch (ch) { - case 0x0622: - case 0x0623: - case 0x0625: - case 0x0627: - case 0x0649: - case 0x0670: - case 0x0671: - case 0x0672: - case 0x0673: - case 0x0675: - return true; + switch (ch) { + case 0x0622: + case 0x0623: + case 0x0625: + case 0x0627: + case 0x0649: + case 0x0670: + case 0x0671: + case 0x0672: + case 0x0673: + case 0x0675: + return true; default: - } - return false; + } + return false; } /** @@ -1757,54 +1757,54 @@ * @return a string representation of the receiver */ public char[] toString () { - if (isDisposed()) return "TextLayout {*DISPOSED*}"; - return Format( "TextLayout {{{}}", layout ); + if (isDisposed()) return "TextLayout {*DISPOSED*}"; + return Format( "TextLayout {{{}}", layout ); } /* * Translate a client offset to an internal offset */ int translateOffset(int offset) { - int length = text.length; - if (length == 0) return offset; - if (invalidOffsets is null) return offset; - for (int i = 0; i < invalidOffsets.length; i++) { - if (offset < invalidOffsets[i]) break; - offset++; - } - return offset; + int length = text.length; + if (length == 0) return offset; + if (invalidOffsets is null) return offset; + for (int i = 0; i < invalidOffsets.length; i++) { + if (offset < invalidOffsets[i]) break; + offset++; + } + return offset; } /* * Translate an internal offset to a client offset */ int untranslateOffset(int offset) { - int length = text.length; - if (length == 0) return offset; - if (invalidOffsets is null) return offset; - for (int i = 0; i < invalidOffsets.length; i++) { - if (offset == invalidOffsets[i]) { - offset++; - continue; - } - if (offset < invalidOffsets[i]) { - return offset - i; - } - } - return offset - invalidOffsets.length; + int length = text.length; + if (length == 0) return offset; + if (invalidOffsets is null) return offset; + for (int i = 0; i < invalidOffsets.length; i++) { + if (offset == invalidOffsets[i]) { + offset++; + continue; + } + if (offset < invalidOffsets[i]) { + return offset - i; + } + } + return offset - invalidOffsets.length; } int validateOffset(int offset, int step) { - if (invalidOffsets is null) return offset + step; - int i = step > 0 ? 0 : invalidOffsets.length - 1; - do { - offset += step; - while (0 <= i && i < invalidOffsets.length) { - if (invalidOffsets[i] == offset) break; - i += step; - } - } while (0 <= i && i < invalidOffsets.length); - return offset; + if (invalidOffsets is null) return offset + step; + int i = step > 0 ? 0 : invalidOffsets.length - 1; + do { + offset += step; + while (0 <= i && i < invalidOffsets.length) { + if (invalidOffsets[i] == offset) break; + i += step; + } + } while (0 <= i && i < invalidOffsets.length); + return offset; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/TextStyle.d --- a/dwt/graphics/TextStyle.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/TextStyle.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -39,48 +39,48 @@ */ public class TextStyle { - /** - * the font of the style - */ - public Font font; + /** + * the font of the style + */ + public Font font; - /** - * the foreground of the style - */ - public Color foreground; + /** + * the foreground of the style + */ + public Color foreground; - /** - * the background of the style - */ - public Color background; + /** + * the background of the style + */ + public Color background; - /** - * the underline flag of the style - * - * @since 3.1 - */ - public bool underline; + /** + * the underline flag of the style + * + * @since 3.1 + */ + public bool underline; - /** - * the strikeout flag of the style - * - * @since 3.1 - */ - public bool strikeout; + /** + * the strikeout flag of the style + * + * @since 3.1 + */ + public bool strikeout; - /** - * the GlyphMetrics of the style - * - * @since 3.2 - */ - public GlyphMetrics metrics; + /** + * the GlyphMetrics of the style + * + * @since 3.2 + */ + public GlyphMetrics metrics; - /** - * the baseline rise of the style. - * - * @since 3.2 - */ - public int rise; + /** + * the baseline rise of the style. + * + * @since 3.2 + */ + public int rise; /** * Create a new text style with the specified font, foreground @@ -91,12 +91,12 @@ * @param background the background color of the style, null if none */ public this (Font font, Color foreground, Color background) { - if (font !is null && font.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); - if (foreground !is null && foreground.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); - if (background !is null && background.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); - this.font = font; - this.foreground = foreground; - this.background = background; + if (font !is null && font.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); + if (foreground !is null && foreground.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); + if (background !is null && background.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); + this.font = font; + this.foreground = foreground; + this.background = background; } /** @@ -110,24 +110,24 @@ * @see #hashCode() */ public override int opEquals(Object object) { - if (object is this) return true; - if (object is null) return false; - if (!(cast(TextStyle)object)) return false; - TextStyle style = cast(TextStyle)object; - if (foreground !is null) { - if ( foreground != style.foreground ) return false; - } else if (style.foreground !is null) return false; - if (background !is null) { - if ( background != style.background ) return false; - } else if (style.background !is null) return false; - if (font !is null) { - if (font != style.font) return false; - } else if (style.font != null) return false; - if (metrics != null || style.metrics !is null) return false; - if (underline !is style.underline) return false; - if (strikeout !is style.strikeout) return false; - if (rise !is style.rise) return false; - return true; + if (object is this) return true; + if (object is null) return false; + if (!(cast(TextStyle)object)) return false; + TextStyle style = cast(TextStyle)object; + if (foreground !is null) { + if ( foreground != style.foreground ) return false; + } else if (style.foreground !is null) return false; + if (background !is null) { + if ( background != style.background ) return false; + } else if (style.background !is null) return false; + if (font !is null) { + if (font != style.font) return false; + } else if (style.font != null) return false; + if (metrics != null || style.metrics !is null) return false; + if (underline !is style.underline) return false; + if (strikeout !is style.strikeout) return false; + if (rise !is style.rise) return false; + return true; } /** @@ -141,15 +141,15 @@ * @see #equals(Object) */ public override hash_t toHash() { - int hash = 0; - if (foreground !is null) hash ^= foreground.toHash(); - if (background !is null) hash ^= background.toHash(); - if (font !is null) hash ^= font.toHash(); - if (metrics !is null) hash ^= metrics.toHash(); - if (underline) hash ^= hash; - if (strikeout) hash ^= hash; - hash ^= rise; - return hash; + int hash = 0; + if (foreground !is null) hash ^= foreground.toHash(); + if (background !is null) hash ^= background.toHash(); + if (font !is null) hash ^= font.toHash(); + if (metrics !is null) hash ^= metrics.toHash(); + if (underline) hash ^= hash; + if (strikeout) hash ^= hash; + hash ^= rise; + return hash; } /** @@ -159,43 +159,43 @@ * @return a string representation of the TextStyle */ public char[] toString () { - char[] buffer = "TextStyle {"; - int startLength = buffer.length; - if (font != null) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "font="; - buffer ~= font.toString; - } - if (foreground != null) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "foreground="; - buffer ~= foreground.toString; - } - if (background != null) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "background="; - buffer ~= background.toString; - } - if (underline) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "underlined"; - } - if (strikeout) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "striked out"; - } - if (rise != 0) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "rise="; - buffer ~= to!(char[])(rise); - } - if (metrics != null) { - if (buffer.length > startLength) buffer ~= ", "; - buffer ~= "metrics="; - buffer ~= metrics.toString; - } - buffer ~= "}"; - return buffer; + char[] buffer = "TextStyle {"; + int startLength = buffer.length; + if (font != null) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "font="; + buffer ~= font.toString; + } + if (foreground != null) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "foreground="; + buffer ~= foreground.toString; + } + if (background != null) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "background="; + buffer ~= background.toString; + } + if (underline) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "underlined"; + } + if (strikeout) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "striked out"; + } + if (rise != 0) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "rise="; + buffer ~= to!(char[])(rise); + } + if (metrics != null) { + if (buffer.length > startLength) buffer ~= ", "; + buffer ~= "metrics="; + buffer ~= metrics.toString; + } + buffer ~= "}"; + return buffer; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/graphics/Transform.d --- a/dwt/graphics/Transform.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/graphics/Transform.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -34,17 +34,17 @@ * @since 3.1 */ public class Transform : Resource { - /** - * the OS resource for the Transform - * (Warning: This field is platform dependent) - *

    - * IMPORTANT: This field is not 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. - *

    - */ - public double[] handle; + /** + * the OS resource for the Transform + * (Warning: This field is platform dependent) + *

    + * IMPORTANT: This field is not 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. + *

    + */ + public double[] handle; /** * Constructs a new identity Transform. @@ -69,7 +69,7 @@ * @see #dispose() */ public this (Device device) { - this(device, 1, 0, 0, 1, 0, 0); + this(device, 1, 0, 0, 1, 0, 0); } /** @@ -98,7 +98,7 @@ * @see #dispose() */ public this(Device device, float[] elements) { - this (device, checkTransform(elements)[0], elements[1], elements[2], elements[3], elements[4], elements[5]); + this (device, checkTransform(elements)[0], elements[1], elements[2], elements[3], elements[4], elements[5]); } /** @@ -131,20 +131,20 @@ * @see #dispose() */ public this (Device device, float m11, float m12, float m21, float m22, float dx, float dy) { - if (device is null) device = Device.getDevice(); - if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - this.device = device; - device.checkCairo(); - handle = new double[6]; - if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); - Cairo.cairo_matrix_init( cast(cairo_matrix_t*)handle.ptr, m11, m12, m21, m22, dx, dy); - if (device.tracking) device.new_Object(this); + if (device is null) device = Device.getDevice(); + if (device is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + this.device = device; + device.checkCairo(); + handle = new double[6]; + if (handle is null) SWT.error(SWT.ERROR_NO_HANDLES); + Cairo.cairo_matrix_init( cast(cairo_matrix_t*)handle.ptr, m11, m12, m21, m22, dx, dy); + if (device.tracking) device.new_Object(this); } static float[] checkTransform(float[] elements) { - if (elements == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (elements.length < 6) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - return elements; + if (elements == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (elements.length < 6) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + return elements; } /** @@ -153,11 +153,11 @@ * they allocate. */ public void dispose() { - if (handle is null) return; - if (device.isDisposed()) return; - handle = null; - if (device.tracking) device.dispose_Object(this); - device = null; + if (handle is null) return; + if (device.isDisposed()) return; + handle = null; + if (device.tracking) device.dispose_Object(this); + device = null; } /** @@ -175,15 +175,15 @@ * */ public void getElements(float[] elements) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (elements is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (elements.length < 6) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - elements[0] = cast(float)handle[0]; - elements[1] = cast(float)handle[1]; - elements[2] = cast(float)handle[2]; - elements[3] = cast(float)handle[3]; - elements[4] = cast(float)handle[4]; - elements[5] = cast(float)handle[5]; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (elements is null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (elements.length < 6) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + elements[0] = cast(float)handle[0]; + elements[1] = cast(float)handle[1]; + elements[2] = cast(float)handle[2]; + elements[3] = cast(float)handle[3]; + elements[4] = cast(float)handle[4]; + elements[5] = cast(float)handle[5]; } /** @@ -196,10 +196,10 @@ * */ public void invert() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)handle.ptr) != 0) { - SWT.error(SWT.ERROR_CANNOT_INVERT_MATRIX); - } + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (Cairo.cairo_matrix_invert(cast(cairo_matrix_t*)handle.ptr) != 0) { + SWT.error(SWT.ERROR_CANNOT_INVERT_MATRIX); + } } /** @@ -213,7 +213,7 @@ * @return true when the Transform is disposed, and false otherwise */ public bool isDisposed() { - return handle is null; + return handle is null; } /** @@ -223,10 +223,10 @@ * @return true if the receiver is an identity Transform, and false otherwise */ public bool isIdentity() { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - float[] m = new float[6]; - getElements(m); - return m[0] == 1 && m[1] == 0 && m[2] == 0 && m[3] == 1 && m[4] == 0 && m[5] == 0; + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + float[] m = new float[6]; + getElements(m); + return m[0] == 1 && m[1] == 0 && m[2] == 0 && m[3] == 1 && m[4] == 0 && m[5] == 0; } /** @@ -245,10 +245,10 @@ * */ public void multiply(Transform matrix) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (matrix == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - if (matrix.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - Cairo.cairo_matrix_multiply(cast(cairo_matrix_t*)handle.ptr,cast(cairo_matrix_t*)matrix.handle.ptr, cast(cairo_matrix_t*)handle.ptr); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (matrix == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + if (matrix.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + Cairo.cairo_matrix_multiply(cast(cairo_matrix_t*)handle.ptr,cast(cairo_matrix_t*)matrix.handle.ptr, cast(cairo_matrix_t*)handle.ptr); } /** @@ -265,8 +265,8 @@ * */ public void rotate(float angle) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - Cairo.cairo_matrix_rotate(cast(cairo_matrix_t*)handle.ptr, angle * cast(float)Compatibility.PI / 180); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Cairo.cairo_matrix_rotate(cast(cairo_matrix_t*)handle.ptr, angle * cast(float)Compatibility.PI / 180); } /** @@ -281,8 +281,8 @@ * */ public void scale(float scaleX, float scaleY) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - Cairo.cairo_matrix_scale(cast(cairo_matrix_t*)handle.ptr, scaleX, scaleY); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Cairo.cairo_matrix_scale(cast(cairo_matrix_t*)handle.ptr, scaleX, scaleY); } /** @@ -301,8 +301,8 @@ * */ public void setElements(float m11, float m12, float m21, float m22, float dx, float dy) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - Cairo.cairo_matrix_init(cast(cairo_matrix_t*)handle.ptr, m11, m12, m21, m22, dx, dy); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Cairo.cairo_matrix_init(cast(cairo_matrix_t*)handle.ptr, m11, m12, m21, m22, dx, dy); } /** @@ -320,17 +320,17 @@ * */ public void transform(float[] pointArray) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); - double dx, dy; - int length = pointArray.length / 2; - for (int i = 0, j = 0; i < length; i++, j += 2) { - dx = pointArray[j]; - dy = pointArray[j + 1]; - Cairo.cairo_matrix_transform_point(cast(cairo_matrix_t*)handle.ptr, &dx, &dy); - pointArray[j] = cast(float)dx; - pointArray[j + 1] = cast(float)dy; - } + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + if (pointArray == null) SWT.error(SWT.ERROR_NULL_ARGUMENT); + double dx, dy; + int length = pointArray.length / 2; + for (int i = 0, j = 0; i < length; i++, j += 2) { + dx = pointArray[j]; + dy = pointArray[j + 1]; + Cairo.cairo_matrix_transform_point(cast(cairo_matrix_t*)handle.ptr, &dx, &dy); + pointArray[j] = cast(float)dx; + pointArray[j + 1] = cast(float)dy; + } } /** @@ -345,8 +345,8 @@ * */ public void translate(float offsetX, float offsetY) { - if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); - Cairo.cairo_matrix_translate(cast(cairo_matrix_t*)handle.ptr, offsetX, offsetY); + if (isDisposed()) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); + Cairo.cairo_matrix_translate(cast(cairo_matrix_t*)handle.ptr, offsetX, offsetY); } /** @@ -356,10 +356,10 @@ * @return a string representation of the receiver */ public char[] toString() { - if (isDisposed()) return "Transform {*DISPOSED*}"; - float[] elements = new float[6]; - getElements(elements); - return Format( "Transform {{{}}", elements ); + if (isDisposed()) return "Transform {*DISPOSED*}"; + float[] elements = new float[6]; + getElements(elements); + return Format( "Transform {{{}}", elements ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/BidiUtil.d --- a/dwt/internal/BidiUtil.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/BidiUtil.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -21,25 +21,25 @@ * emulated platforms. */ public class BidiUtil { - // Keyboard language types - public static const int KEYBOARD_NON_BIDI = 0; - public static const int KEYBOARD_BIDI = 1; + // Keyboard language types + public static const int KEYBOARD_NON_BIDI = 0; + public static const int KEYBOARD_BIDI = 1; - // bidi rendering input flag constants, not used - // on emulated platforms - public static const int CLASSIN = 1; - public static const int LINKBEFORE = 2; - public static const int LINKAFTER = 4; + // bidi rendering input flag constants, not used + // on emulated platforms + public static const int CLASSIN = 1; + public static const int LINKBEFORE = 2; + public static const int LINKAFTER = 4; - // bidi rendering/ordering constants, not used on - // emulated platforms - public static const int CLASS_HEBREW = 2; - public static const int CLASS_ARABIC = 2; - public static const int CLASS_LOCALNUMBER = 4; - public static const int CLASS_LATINNUMBER = 5; - public static const int REORDER = 0; - public static const int LIGATE = 0; - public static const int GLYPHSHAPE = 0; + // bidi rendering/ordering constants, not used on + // emulated platforms + public static const int CLASS_HEBREW = 2; + public static const int CLASS_ARABIC = 2; + public static const int CLASS_LOCALNUMBER = 4; + public static const int CLASS_LATINNUMBER = 5; + public static const int REORDER = 0; + public static const int LIGATE = 0; + public static const int GLYPHSHAPE = 0; /* * Not implemented. @@ -57,19 +57,19 @@ * */ public static bool isBidiPlatform() { - return false; + return false; } /* * Not implemented. */ public static bool isKeyboardBidi() { - return false; + return false; } /* * Not implemented. */ public static int getFontBidiAttributes(GC gc) { - return 0; + return 0; } /* * Not implemented. @@ -82,13 +82,13 @@ * */ public static char[] getRenderInfo(GC gc, char[] text, int[] order, byte[] classBuffer, int[] dx, int flags, int[] offsets) { - return null; + return null; } /* * Not implemented. Returns 0. */ public static int getKeyboardLanguage() { - return 0; + return 0; } /* * Not implemented. @@ -104,6 +104,6 @@ * Not implemented. */ public static bool setOrientation(int /*long*/ hwnd, int orientation) { - return false; + return false; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/Compatibility.d --- a/dwt/internal/Compatibility.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/Compatibility.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -72,7 +72,7 @@ * @return the integer conversion of length * cos (angle) */ public static int cos(int angle, int length) { - return cast(int)(Math.cos(angle * toRadians) * length); + return cast(int)(Math.cos(angle * toRadians) * length); } /** @@ -89,7 +89,7 @@ * @return the integer conversion of length * sin (angle) */ public static int sin(int angle, int length) { - return cast(int)(Math.sin(angle * toRadians) * length); + return cast(int)(Math.sin(angle * toRadians) * length); } /** @@ -102,7 +102,7 @@ * @return the ceiling of the rational number p / q. */ public static int ceil(int p, int q) { - return cast(int)Math.ceil(cast(float)p / q); + return cast(int)Math.ceil(cast(float)p / q); } /** @@ -115,7 +115,7 @@ * @return the floor of the rational number p / q. */ public static int floor(int p, int q) { - return cast(int)Math.floor(cast(double)p / q); + return cast(int)Math.floor(cast(double)p / q); } /** @@ -132,7 +132,7 @@ * @return the closest integer to the rational number p / q */ public static int round(int p, int q) { - return cast(int)Math.round(cast(float)p / q); + return cast(int)Math.round(cast(float)p / q); } /** @@ -146,12 +146,12 @@ * */ public static int pow2(int n) { - if (n >= 1 && n <= 30) - return 2 << (n - 1); - else if (n != 0) { - SWT.error(SWT.ERROR_INVALID_RANGE); - } - return 1; + if (n >= 1 && n <= 30) + return 2 << (n - 1); + else if (n != 0) { + SWT.error(SWT.ERROR_INVALID_RANGE); + } + return 1; } /** @@ -162,7 +162,7 @@ * @exception IOException */ public static InputStream newFileInputStream(char[] filename) { - return new FileInputStream(filename); + return new FileInputStream(filename); } /** @@ -173,7 +173,7 @@ * @exception IOException */ public static OutputStream newFileOutputStream(char[] filename) { - return new FileOutputStream(filename); + return new FileOutputStream(filename); } /** @@ -186,7 +186,7 @@ * @since 3.3 */ public static InflaterInputStream newInflaterInputStream(InputStream stream) { - return new InflaterInputStream(stream); + return new InflaterInputStream(stream); } /** @@ -196,7 +196,7 @@ * @return true when the character is a letter */ public static bool isLetter(dchar c) { - return Unicode.isLetter(c); + return Unicode.isLetter(c); } /** @@ -206,17 +206,17 @@ * @return true when the character is a letter or a digit */ public static bool isLetterOrDigit(dchar c) { - return Unicode.isLetterOrDigit(c); + return Unicode.isLetterOrDigit(c); } /** * Answers whether the character is a Unicode space character. * - * @param c the character + * @param c the character * @return true when the character is a Unicode space character */ public static bool isSpaceChar(dchar c) { - return Unicode.isSpace(c); + return Unicode.isSpace(c); } /** @@ -226,7 +226,7 @@ * @return true if the character is whitespace */ public static bool isWhitespace(dchar c) { - return Unicode.isWhitespace(c); + return Unicode.isWhitespace(c); } /** @@ -275,47 +275,47 @@ * @see SWT#getMessage(String) */ public static String getMessage(String key) { - String answer = key; + String answer = key; - if (key == null) { - SWT.error (SWT.ERROR_NULL_ARGUMENT); - } - if (msgs == null) { - try { - msgs = ResourceBundle.getBundle("dwt.internal.SWTMessages"); //$NON-NLS-1$ - } catch (MissingResourceException ex) { - answer = key + " (no resource bundle)"; //$NON-NLS-1$ - } - } - if (msgs != null) { - try { - answer = msgs.getString(key); - } catch (MissingResourceException ex2) {} - } - return answer; + if (key == null) { + SWT.error (SWT.ERROR_NULL_ARGUMENT); + } + if (msgs == null) { + try { + msgs = ResourceBundle.getBundle("dwt.internal.SWTMessages"); //$NON-NLS-1$ + } catch (MissingResourceException ex) { + answer = key + " (no resource bundle)"; //$NON-NLS-1$ + } + } + if (msgs != null) { + try { + answer = msgs.getString(key); + } catch (MissingResourceException ex2) {} + } + return answer; } public static String getMessage(String key, Object[] args) { - String answer = key; + String answer = key; - if (key == null || args == null) { - SWT.error (SWT.ERROR_NULL_ARGUMENT); - } - if (msgs == null) { - try { - msgs = ResourceBundle.getBundle("dwt.internal.SWTMessages"); //$NON-NLS-1$ - } catch (MissingResourceException ex) { - answer = key + " (no resource bundle)"; //$NON-NLS-1$ - } - } - if (msgs != null) { - try { - MessageFormat formatter = new MessageFormat(""); - formatter.applyPattern(msgs.getString(key)); - answer = formatter.format(args); - } catch (MissingResourceException ex2) {} - } - return answer; + if (key == null || args == null) { + SWT.error (SWT.ERROR_NULL_ARGUMENT); + } + if (msgs == null) { + try { + msgs = ResourceBundle.getBundle("dwt.internal.SWTMessages"); //$NON-NLS-1$ + } catch (MissingResourceException ex) { + answer = key + " (no resource bundle)"; //$NON-NLS-1$ + } + } + if (msgs != null) { + try { + MessageFormat formatter = new MessageFormat(""); + formatter.applyPattern(msgs.getString(key)); + answer = formatter.format(args); + } catch (MissingResourceException ex2) {} + } + return answer; } ++/ @@ -328,7 +328,7 @@ */ public static void interrupt() { //PORTING_FIXME: how to implement?? - //Thread.currentThread().interrupt(); + //Thread.currentThread().interrupt(); } /** @@ -348,7 +348,7 @@ } char[] s1c = Unicode.toFold( s1, s1b ); char[] s2c = Unicode.toFold( s2, s2b ); - return s1c == s2c; + return s1c == s2c; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/Converter.d --- a/dwt/internal/Converter.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/Converter.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -38,9 +38,9 @@ *

    */ public final class Converter { - public static const char [] NullByteArray = "\0"; - public static const char [] EmptyByteArray = ""; - public static const wchar [] EmptyCharArray = ""; + public static const char [] NullByteArray = "\0"; + public static const char [] EmptyByteArray = ""; + public static const wchar [] EmptyCharArray = ""; /** * Returns the default code page for the platform where the @@ -49,46 +49,46 @@ * @return the default code page */ public static char[] defaultCodePage () { - return "UTF8"; + return "UTF8"; } public static wchar [] mbcsToWcs (char[] codePage, char [] buffer) { - int items_written; - wchar* ptr = g_utf8_to_utf16 (toStringz(buffer), buffer.length, null, &items_written, null); - if (!ptr){ + int items_written; + wchar* ptr = g_utf8_to_utf16 (toStringz(buffer), buffer.length, null, &items_written, null); + if (!ptr){ return EmptyCharArray; } wchar[] chars = ptr[ 0 .. items_written].dup; - g_free (ptr); - return chars; + g_free (ptr); + return chars; } /+ // only difference with String vs. char[] arg, so no diff in dwt public static char [] wcsToMbcs (char[] codePage, String str, bool terminate) { - int length = str.length (); - wchar [] buffer = new wchar [length]; - string.getChars (0, length, buffer, 0); - return wcsToMbcs (codePage, buffer, terminate); + int length = str.length (); + wchar [] buffer = new wchar [length]; + string.getChars (0, length, buffer, 0); + return wcsToMbcs (codePage, buffer, terminate); } +/ public static char [] wcsToMbcs (char[] codePage, wchar [] buffer, bool terminate) { - int items_read, items_written; - /* - * Note that g_utf16_to_utf8() stops converting - * when it finds the first NULL. - */ - char* ptr = g_utf16_to_utf8 (toString16z(buffer), buffer.length, & items_read, & items_written, null); - if (!ptr) { + int items_read, items_written; + /* + * Note that g_utf16_to_utf8() stops converting + * when it finds the first NULL. + */ + char* ptr = g_utf16_to_utf8 (toString16z(buffer), buffer.length, & items_read, & items_written, null); + if (!ptr) { return terminate ? NullByteArray : EmptyByteArray; } - char [] bytes = new char [items_written + (terminate ? 1 : 0)]; + char [] bytes = new char [items_written + (terminate ? 1 : 0)]; bytes[ 0 .. items_written ] = ptr[ 0 .. items_written ]; if( terminate ){ bytes[ items_written ] = 0; } - g_free (ptr); - return bytes; + g_free (ptr); + return bytes; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/LONG.d --- a/dwt/internal/LONG.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/LONG.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -11,23 +11,23 @@ module dwt.internal.LONG; public class LONG { - public int /*long*/ value; + public int /*long*/ value; - public this (int /*long*/ value) { - this.value = value; - } + public this (int /*long*/ value) { + this.value = value; + } - public int opEquals (Object object) { - if (object is this){ + public int opEquals (Object object) { + if (object is this){ return true; } - if ( auto obj = cast(LONG)object ) { + if ( auto obj = cast(LONG)object ) { return obj.value == this.value; } return false; - } + } - public int hashCode () { - return /*64*/value; - } + public int hashCode () { + return /*64*/value; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/Library.d --- a/dwt/internal/Library.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/Library.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -14,27 +14,27 @@ public class Library { - /* SWT Version - Mmmm (M=major, mmm=minor) */ + /* SWT Version - Mmmm (M=major, mmm=minor) */ - /** - * SWT Major version number (must be >= 0) - */ + /** + * SWT Major version number (must be >= 0) + */ static const int MAJOR_VERSION = 3; - /** - * SWT Minor version number (must be in the range 0..999) - */ + /** + * SWT Minor version number (must be in the range 0..999) + */ static const int MINOR_VERSION = 346; - /** - * SWT revision number (must be >= 0) - */ - static const int REVISION = 0; + /** + * SWT revision number (must be >= 0) + */ + static const int REVISION = 0; - /** - * The JAVA and SWT versions - */ - //public static const int JAVA_VERSION; + /** + * The JAVA and SWT versions + */ + //public static const int JAVA_VERSION; public static /*const*/ int SWT_VERSION; version( linux ){ @@ -46,33 +46,33 @@ public static void static_this() { - //SEPARATOR = System.getProperty("file.separator"); - //JAVA_VERSION = parseVersion(System.getProperty("java.version")); - SWT_VERSION = buildSWT_VERSION(MAJOR_VERSION, MINOR_VERSION); + //SEPARATOR = System.getProperty("file.separator"); + //JAVA_VERSION = parseVersion(System.getProperty("java.version")); + SWT_VERSION = buildSWT_VERSION(MAJOR_VERSION, MINOR_VERSION); } static int parseVersion(char[] aVersion) { - if (aVersion == null) return 0; - int major = 0, minor = 0, micro = 0; - int length = aVersion.length, index = 0, start = 0; + if (aVersion == null) return 0; + int major = 0, minor = 0, micro = 0; + int length = aVersion.length, index = 0, start = 0; bool isDigit( char c ){ return c >= '0' && c <= '9'; } - while (index < length && isDigit(aVersion[index])) index++; - try { - if (start < length) major = to!(int)( aVersion[start .. index] ); - } catch (ConversionException e) {} - start = ++index; - while (index < length && isDigit(aVersion[index])) index++; - try { - if (start < length) minor = to!(int)(aVersion[start .. index]); - } catch (ConversionException e) {} - start = ++index; - while (index < length && isDigit(aVersion[index])) index++; - try { - if (start < length) micro = to!(int)(aVersion[start .. index]); - } catch (ConversionException e) {} - return buildJAVA_VERSION(major, minor, micro); + while (index < length && isDigit(aVersion[index])) index++; + try { + if (start < length) major = to!(int)( aVersion[start .. index] ); + } catch (ConversionException e) {} + start = ++index; + while (index < length && isDigit(aVersion[index])) index++; + try { + if (start < length) minor = to!(int)(aVersion[start .. index]); + } catch (ConversionException e) {} + start = ++index; + while (index < length && isDigit(aVersion[index])) index++; + try { + if (start < length) micro = to!(int)(aVersion[start .. index]); + } catch (ConversionException e) {} + return buildJAVA_VERSION(major, minor, micro); } /** @@ -84,7 +84,7 @@ * @return the version */ public static int buildJAVA_VERSION (int major, int minor, int micro) { - return (major << 16) + (minor << 8) + micro; + return (major << 16) + (minor << 8) + micro; } /** @@ -95,55 +95,55 @@ * @return the version */ public static int buildSWT_VERSION (int major, int minor) { - return major * 1000 + minor; + return major * 1000 + minor; } /+ PORTING_LEFT static bool extract (char[] fileName, char[] mappedName) { - FileOutputStream os = null; - InputStream is = null; - File file = new File(fileName); - try { - if (!file.exists ()) { - is = Library.class.getResourceAsStream ("/" + mappedName); //$NON-NLS-1$ - if (is != null) { - int read; - byte [] buffer = new byte [4096]; - os = new FileOutputStream (fileName); - while ((read = is.read (buffer)) != -1) { - os.write(buffer, 0, read); - } - os.close (); - is.close (); - if (!Platform.PLATFORM.equals ("win32")) { //$NON-NLS-1$ - try { - Runtime.getRuntime ().exec (new String []{"chmod", "755", fileName}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (Throwable e) {} - } - if (load (fileName)) return true; - } - } - } catch (Throwable e) { - try { - if (os != null) os.close (); - } catch (IOException e1) {} - try { - if (is != null) is.close (); - } catch (IOException e1) {} - } - if (file.exists ()) file.delete (); - return false; + FileOutputStream os = null; + InputStream is = null; + File file = new File(fileName); + try { + if (!file.exists ()) { + is = Library.class.getResourceAsStream ("/" + mappedName); //$NON-NLS-1$ + if (is != null) { + int read; + byte [] buffer = new byte [4096]; + os = new FileOutputStream (fileName); + while ((read = is.read (buffer)) != -1) { + os.write(buffer, 0, read); + } + os.close (); + is.close (); + if (!Platform.PLATFORM.equals ("win32")) { //$NON-NLS-1$ + try { + Runtime.getRuntime ().exec (new String []{"chmod", "755", fileName}).waitFor(); //$NON-NLS-1$ //$NON-NLS-2$ + } catch (Throwable e) {} + } + if (load (fileName)) return true; + } + } + } catch (Throwable e) { + try { + if (os != null) os.close (); + } catch (IOException e1) {} + try { + if (is != null) is.close (); + } catch (IOException e1) {} + } + if (file.exists ()) file.delete (); + return false; } static bool load (char[] libName) { - try { - if (libName.indexOf (SEPARATOR) != -1) { - System.load (libName); - } else { - System.loadLibrary (libName); - } - return true; - } catch (UnsatisfiedLinkError e) {} - return false; + try { + if (libName.indexOf (SEPARATOR) != -1) { + System.load (libName); + } else { + System.loadLibrary (libName); + } + return true; + } catch (UnsatisfiedLinkError e) {} + return false; } /** @@ -158,7 +158,7 @@ * @param name the name of the library to load */ public static void loadLibrary (char[] name) { - loadLibrary (name, true); + loadLibrary (name, true); } /** @@ -175,58 +175,58 @@ */ public static void loadLibrary (char[] name, boolean mapName) { - /* Compute the library name and mapped name */ - String libName1, libName2, mappedName1, mappedName2; - if (mapName) { - String version = System.getProperty ("swt.version"); //$NON-NLS-1$ - if (version == null) { - version = "" + MAJOR_VERSION; //$NON-NLS-1$ - /* Force 3 digits in minor version number */ - if (MINOR_VERSION < 10) { - version += "00"; //$NON-NLS-1$ - } else { - if (MINOR_VERSION < 100) version += "0"; //$NON-NLS-1$ - } - version += MINOR_VERSION; - /* No "r" until first revision */ - if (REVISION > 0) version += "r" + REVISION; //$NON-NLS-1$ - } - libName1 = name + "-" + Platform.PLATFORM + "-" + version; //$NON-NLS-1$ //$NON-NLS-2$ - libName2 = name + "-" + Platform.PLATFORM; //$NON-NLS-1$ - mappedName1 = System.mapLibraryName (libName1); - mappedName2 = System.mapLibraryName (libName2); - } else { - libName1 = libName2 = mappedName1 = mappedName2 = name; - } + /* Compute the library name and mapped name */ + String libName1, libName2, mappedName1, mappedName2; + if (mapName) { + String version = System.getProperty ("swt.version"); //$NON-NLS-1$ + if (version == null) { + version = "" + MAJOR_VERSION; //$NON-NLS-1$ + /* Force 3 digits in minor version number */ + if (MINOR_VERSION < 10) { + version += "00"; //$NON-NLS-1$ + } else { + if (MINOR_VERSION < 100) version += "0"; //$NON-NLS-1$ + } + version += MINOR_VERSION; + /* No "r" until first revision */ + if (REVISION > 0) version += "r" + REVISION; //$NON-NLS-1$ + } + libName1 = name + "-" + Platform.PLATFORM + "-" + version; //$NON-NLS-1$ //$NON-NLS-2$ + libName2 = name + "-" + Platform.PLATFORM; //$NON-NLS-1$ + mappedName1 = System.mapLibraryName (libName1); + mappedName2 = System.mapLibraryName (libName2); + } else { + libName1 = libName2 = mappedName1 = mappedName2 = name; + } - /* Try loading library from swt library path */ - String path = System.getProperty ("swt.library.path"); //$NON-NLS-1$ - if (path != null) { - path = new File (path).getAbsolutePath (); - if (load (path + SEPARATOR + mappedName1)) return; - if (mapName && load (path + SEPARATOR + mappedName2)) return; - } + /* Try loading library from swt library path */ + String path = System.getProperty ("swt.library.path"); //$NON-NLS-1$ + if (path != null) { + path = new File (path).getAbsolutePath (); + if (load (path + SEPARATOR + mappedName1)) return; + if (mapName && load (path + SEPARATOR + mappedName2)) return; + } - /* Try loading library from java library path */ - if (load (libName1)) return; - if (mapName && load (libName2)) return; + /* Try loading library from java library path */ + if (load (libName1)) return; + if (mapName && load (libName2)) return; - /* Try loading library from the tmp directory if swt library path is not specified */ - if (path == null) { - path = System.getProperty ("java.io.tmpdir"); //$NON-NLS-1$ - path = new File (path).getAbsolutePath (); - if (load (path + SEPARATOR + mappedName1)) return; - if (mapName && load (path + SEPARATOR + mappedName2)) return; - } + /* Try loading library from the tmp directory if swt library path is not specified */ + if (path == null) { + path = System.getProperty ("java.io.tmpdir"); //$NON-NLS-1$ + path = new File (path).getAbsolutePath (); + if (load (path + SEPARATOR + mappedName1)) return; + if (mapName && load (path + SEPARATOR + mappedName2)) return; + } - /* Try extracting and loading library from jar */ - if (path != null) { - if (extract (path + SEPARATOR + mappedName1, mappedName1)) return; - if (mapName && extract (path + SEPARATOR + mappedName2, mappedName2)) return; - } + /* Try extracting and loading library from jar */ + if (path != null) { + if (extract (path + SEPARATOR + mappedName1, mappedName1)) return; + if (mapName && extract (path + SEPARATOR + mappedName2, mappedName2)) return; + } - /* Failed to find the library */ - throw new UnsatisfiedLinkError ("no " + libName1 + " or " + libName2 + " in swt.library.path, java.library.path or the jar file"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + /* Failed to find the library */ + throw new UnsatisfiedLinkError ("no " + libName1 + " or " + libName2 + " in swt.library.path, java.library.path or the jar file"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } +/ } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/Lock.d --- a/dwt/internal/Lock.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/Lock.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -18,8 +18,8 @@ * Instance of this represent a recursive monitor. */ public class Lock { - int count, waitCount; - Thread owner; + int count, waitCount; + Thread owner; Mutex mutex; Condition cond; @@ -35,22 +35,22 @@ * @return the lock count */ public int lock() { - synchronized (mutex) { - Thread current = Thread.getThis(); - if (owner !is current) { - waitCount++; - while (count > 0) { - try { - cond.wait(); - } catch (SyncException e) { - /* Wait forever, just like synchronized blocks */ - } - } - --waitCount; - owner = current; - } - return ++count; - } + synchronized (mutex) { + Thread current = Thread.getThis(); + if (owner !is current) { + waitCount++; + while (count > 0) { + try { + cond.wait(); + } catch (SyncException e) { + /* Wait forever, just like synchronized blocks */ + } + } + --waitCount; + owner = current; + } + return ++count; + } } /** @@ -58,14 +58,14 @@ * the monitor owner, do nothing. */ public void unlock() { - synchronized (mutex) { - Thread current = Thread.getThis(); - if (owner is current) { - if (--count is 0) { - owner = null; - if (waitCount > 0) cond.notifyAll(); - } - } - } + synchronized (mutex) { + Thread current = Thread.getThis(); + if (owner is current) { + if (--count is 0) { + owner = null; + if (waitCount > 0) cond.notifyAll(); + } + } + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/Platform.d --- a/dwt/internal/Platform.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/Platform.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. All rights reserved. * The contents of this file are made available under the terms * of the GNU Lesser General Public License (LGPL) Version 2.1 that @@ -17,8 +17,8 @@ import dwt.internal.Lock; public class Platform { - public static const char[] PLATFORM = "gtk"; //$NON-NLS-1$ - public static /*const*/ Lock lock; + public static const char[] PLATFORM = "gtk"; //$NON-NLS-1$ + public static /*const*/ Lock lock; public static void static_this() { lock = new Lock(); } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/SWTEventObject.d --- a/dwt/internal/SWTEventObject.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/SWTEventObject.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -50,7 +50,7 @@ */ public class SWTEventObject : EventObject { - //static final long serialVersionUID = 3258125873411470903L; + //static final long serialVersionUID = 3258125873411470903L; /** * Constructs a new instance of this class. @@ -58,6 +58,6 @@ * @param source the object which fired the event */ public this(Object source) { - super(source); + super(source); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/accessibility/gtk/ATK.d --- a/dwt/internal/accessibility/gtk/ATK.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/accessibility/gtk/ATK.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. All rights reserved. * The contents of this file are made available under the terms * of the GNU Lesser General Public License (LGPL) Version 2.1 that @@ -87,67 +87,67 @@ public class ATK : OS { - /** Constants */ - public static const int ATK_RELATION_LABELLED_BY = 4; - public static const int ATK_ROLE_CHECK_BOX = 7; - public static const int ATK_ROLE_COMBO_BOX = 11; - public static const int ATK_ROLE_DIALOG = 16; - public static const int ATK_ROLE_DRAWING_AREA = 18; - public static const int ATK_ROLE_WINDOW = 68; - public static const int ATK_ROLE_LABEL = 28; - public static const int ATK_ROLE_LIST = 30; - public static const int ATK_ROLE_LIST_ITEM = 31; - public static const int ATK_ROLE_MENU = 32; - public static const int ATK_ROLE_MENU_BAR = 33; - public static const int ATK_ROLE_MENU_ITEM = 34; - public static const int ATK_ROLE_PAGE_TAB = 36; - public static const int ATK_ROLE_PAGE_TAB_LIST = 37; - public static const int ATK_ROLE_PROGRESS_BAR = 41; - public static const int ATK_ROLE_PUSH_BUTTON = 42; - public static const int ATK_ROLE_RADIO_BUTTON = 43; - public static const int ATK_ROLE_SCROLL_BAR = 47; - public static const int ATK_ROLE_SEPARATOR = 49; - public static const int ATK_ROLE_SLIDER = 50; - public static const int ATK_ROLE_TABLE = 54; - public static const int ATK_ROLE_TABLE_CELL = 55; - public static const int ATK_ROLE_TABLE_COLUMN_HEADER = 56; - public static const int ATK_ROLE_TABLE_ROW_HEADER = 57; - public static const int ATK_ROLE_TEXT = 60; - public static const int ATK_ROLE_TOOL_BAR = 62; - public static const int ATK_ROLE_TOOL_TIP = 63; - public static const int ATK_ROLE_TREE = 64; - public static const int ATK_STATE_ARMED = 2; - public static const int ATK_STATE_BUSY = 3; - public static const int ATK_STATE_CHECKED = 4; - public static const int ATK_STATE_DEFUNCT = 5; - public static const int ATK_STATE_EDITABLE = 6; - public static const int ATK_STATE_ENABLED = 7; - public static const int ATK_STATE_EXPANDED = 9; - public static const int ATK_STATE_FOCUSABLE = 10; - public static const int ATK_STATE_FOCUSED = 11; - public static const int ATK_STATE_MULTISELECTABLE = 16; - public static const int ATK_STATE_PRESSED = 18; - public static const int ATK_STATE_RESIZABLE = 19; - public static const int ATK_STATE_SELECTABLE = 20; - public static const int ATK_STATE_SELECTED = 21; - public static const int ATK_STATE_SHOWING = 23; - public static const int ATK_STATE_TRANSIENT = 26; - public static const int ATK_STATE_VISIBLE = 28; - public static const int ATK_TEXT_BOUNDARY_CHAR = 0; - public static const int ATK_TEXT_BOUNDARY_WORD_START = 1; - public static const int ATK_TEXT_BOUNDARY_WORD_END = 2; - public static const int ATK_TEXT_BOUNDARY_SENTENCE_START = 3; - public static const int ATK_TEXT_BOUNDARY_SENTENCE_END = 4; - public static const int ATK_TEXT_BOUNDARY_LINE_START = 5; - public static const int ATK_TEXT_BOUNDARY_LINE_END = 6; - public static const int ATK_XY_WINDOW = 1; + /** Constants */ + public static const int ATK_RELATION_LABELLED_BY = 4; + public static const int ATK_ROLE_CHECK_BOX = 7; + public static const int ATK_ROLE_COMBO_BOX = 11; + public static const int ATK_ROLE_DIALOG = 16; + public static const int ATK_ROLE_DRAWING_AREA = 18; + public static const int ATK_ROLE_WINDOW = 68; + public static const int ATK_ROLE_LABEL = 28; + public static const int ATK_ROLE_LIST = 30; + public static const int ATK_ROLE_LIST_ITEM = 31; + public static const int ATK_ROLE_MENU = 32; + public static const int ATK_ROLE_MENU_BAR = 33; + public static const int ATK_ROLE_MENU_ITEM = 34; + public static const int ATK_ROLE_PAGE_TAB = 36; + public static const int ATK_ROLE_PAGE_TAB_LIST = 37; + public static const int ATK_ROLE_PROGRESS_BAR = 41; + public static const int ATK_ROLE_PUSH_BUTTON = 42; + public static const int ATK_ROLE_RADIO_BUTTON = 43; + public static const int ATK_ROLE_SCROLL_BAR = 47; + public static const int ATK_ROLE_SEPARATOR = 49; + public static const int ATK_ROLE_SLIDER = 50; + public static const int ATK_ROLE_TABLE = 54; + public static const int ATK_ROLE_TABLE_CELL = 55; + public static const int ATK_ROLE_TABLE_COLUMN_HEADER = 56; + public static const int ATK_ROLE_TABLE_ROW_HEADER = 57; + public static const int ATK_ROLE_TEXT = 60; + public static const int ATK_ROLE_TOOL_BAR = 62; + public static const int ATK_ROLE_TOOL_TIP = 63; + public static const int ATK_ROLE_TREE = 64; + public static const int ATK_STATE_ARMED = 2; + public static const int ATK_STATE_BUSY = 3; + public static const int ATK_STATE_CHECKED = 4; + public static const int ATK_STATE_DEFUNCT = 5; + public static const int ATK_STATE_EDITABLE = 6; + public static const int ATK_STATE_ENABLED = 7; + public static const int ATK_STATE_EXPANDED = 9; + public static const int ATK_STATE_FOCUSABLE = 10; + public static const int ATK_STATE_FOCUSED = 11; + public static const int ATK_STATE_MULTISELECTABLE = 16; + public static const int ATK_STATE_PRESSED = 18; + public static const int ATK_STATE_RESIZABLE = 19; + public static const int ATK_STATE_SELECTABLE = 20; + public static const int ATK_STATE_SELECTED = 21; + public static const int ATK_STATE_SHOWING = 23; + public static const int ATK_STATE_TRANSIENT = 26; + public static const int ATK_STATE_VISIBLE = 28; + public static const int ATK_TEXT_BOUNDARY_CHAR = 0; + public static const int ATK_TEXT_BOUNDARY_WORD_START = 1; + public static const int ATK_TEXT_BOUNDARY_WORD_END = 2; + public static const int ATK_TEXT_BOUNDARY_SENTENCE_START = 3; + public static const int ATK_TEXT_BOUNDARY_SENTENCE_END = 4; + public static const int ATK_TEXT_BOUNDARY_LINE_START = 5; + public static const int ATK_TEXT_BOUNDARY_LINE_END = 6; + public static const int ATK_XY_WINDOW = 1; - /** Signals */ - public static const char[] selection_changed = "selection_changed"; - public static const char[] text_changed_insert = "text_changed::insert"; - public static const char[] text_changed_delete = "text_changed::delete"; - public static const char[] text_caret_moved = "text_caret_moved"; - public static const char[] text_selection_changed = "text_selection_changed"; + /** Signals */ + public static const char[] selection_changed = "selection_changed"; + public static const char[] text_changed_insert = "text_changed::insert"; + public static const char[] text_changed_delete = "text_changed::delete"; + public static const char[] text_caret_moved = "text_caret_moved"; + public static const char[] text_selection_changed = "text_selection_changed"; mixin ForwardGtkAtkCFunc!(.ATK_ACTION_GET_IFACE ); mixin ForwardGtkAtkCFunc!(.ATK_COMPONENT_GET_IFACE); diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/cairo/Cairo.d --- a/dwt/internal/cairo/Cairo.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/cairo/Cairo.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/* ***** BEGIN LICENSE BLOCK ***** +/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version @@ -71,52 +71,52 @@ public class Cairo : Platform { - /** Constants */ - public static const int CAIRO_ANTIALIAS_DEFAULT = 0; - public static const int CAIRO_ANTIALIAS_NONE = 1; - public static const int CAIRO_ANTIALIAS_GRAY = 2; - public static const int CAIRO_ANTIALIAS_SUBPIXEL = 3; - public static const int CAIRO_FORMAT_ARGB32 = 0; - public static const int CAIRO_FORMAT_RGB24 = 1; - public static const int CAIRO_FORMAT_A8 = 2; - public static const int CAIRO_FORMAT_A1 = 3; - public static const int CAIRO_OPERATOR_CLEAR = 0; - public static const int CAIRO_OPERATOR_SRC = 1; - public static const int CAIRO_OPERATOR_DST = 2; - public static const int CAIRO_OPERATOR_OVER = 3; - public static const int CAIRO_OPERATOR_OVER_REVERSE = 4; - public static const int CAIRO_OPERATOR_IN = 5; - public static const int CAIRO_OPERATOR_IN_REVERSE = 6; - public static const int CAIRO_OPERATOR_OUT = 7; - public static const int CAIRO_OPERATOR_OUT_REVERSE = 8; - public static const int CAIRO_OPERATOR_ATOP = 9; - public static const int CAIRO_OPERATOR_ATOP_REVERSE = 10; - public static const int CAIRO_OPERATOR_XOR = 11; - public static const int CAIRO_OPERATOR_ADD = 12; - public static const int CAIRO_OPERATOR_SATURATE = 13; - public static const int CAIRO_FILL_RULE_WINDING = 0; - public static const int CAIRO_FILL_RULE_EVEN_ODD = 1; - public static const int CAIRO_LINE_CAP_BUTT = 0; - public static const int CAIRO_LINE_CAP_ROUND = 1; - public static const int CAIRO_LINE_CAP_SQUARE = 2; - public static const int CAIRO_LINE_JOIN_MITER = 0; - public static const int CAIRO_LINE_JOIN_ROUND = 1; - public static const int CAIRO_LINE_JOIN_BEVEL = 2; - public static const int CAIRO_FONT_SLANT_NORMAL = 0; - public static const int CAIRO_FONT_SLANT_ITALIC = 1; - public static const int CAIRO_FONT_SLANT_OBLIQUE = 2; - public static const int CAIRO_FONT_WEIGHT_NORMAL = 0; - public static const int CAIRO_FONT_WEIGHT_BOLD = 1; - public static const int CAIRO_STATUS_SUCCESS = 0; - public static const int CAIRO_STATUS_NO_MEMORY = 1; - public static const int CAIRO_STATUS_INVALID_RESTORE = 2; - public static const int CAIRO_STATUS_INVALID_POP_GROUP = 3; - public static const int CAIRO_STATUS_NO_CURRENT_POINT = 4; - public static const int CAIRO_STATUS_INVALID_MATRIX = 5; - public static const int CAIRO_STATUS_NO_TARGET_SURFACE = 6; - public static const int CAIRO_STATUS_NULL_POINTER =7; - public static const int CAIRO_SURFACE_TYPE_IMAGE = 0; - public static const int CAIRO_SURFACE_TYPE_PDF = 1; + /** Constants */ + public static const int CAIRO_ANTIALIAS_DEFAULT = 0; + public static const int CAIRO_ANTIALIAS_NONE = 1; + public static const int CAIRO_ANTIALIAS_GRAY = 2; + public static const int CAIRO_ANTIALIAS_SUBPIXEL = 3; + public static const int CAIRO_FORMAT_ARGB32 = 0; + public static const int CAIRO_FORMAT_RGB24 = 1; + public static const int CAIRO_FORMAT_A8 = 2; + public static const int CAIRO_FORMAT_A1 = 3; + public static const int CAIRO_OPERATOR_CLEAR = 0; + public static const int CAIRO_OPERATOR_SRC = 1; + public static const int CAIRO_OPERATOR_DST = 2; + public static const int CAIRO_OPERATOR_OVER = 3; + public static const int CAIRO_OPERATOR_OVER_REVERSE = 4; + public static const int CAIRO_OPERATOR_IN = 5; + public static const int CAIRO_OPERATOR_IN_REVERSE = 6; + public static const int CAIRO_OPERATOR_OUT = 7; + public static const int CAIRO_OPERATOR_OUT_REVERSE = 8; + public static const int CAIRO_OPERATOR_ATOP = 9; + public static const int CAIRO_OPERATOR_ATOP_REVERSE = 10; + public static const int CAIRO_OPERATOR_XOR = 11; + public static const int CAIRO_OPERATOR_ADD = 12; + public static const int CAIRO_OPERATOR_SATURATE = 13; + public static const int CAIRO_FILL_RULE_WINDING = 0; + public static const int CAIRO_FILL_RULE_EVEN_ODD = 1; + public static const int CAIRO_LINE_CAP_BUTT = 0; + public static const int CAIRO_LINE_CAP_ROUND = 1; + public static const int CAIRO_LINE_CAP_SQUARE = 2; + public static const int CAIRO_LINE_JOIN_MITER = 0; + public static const int CAIRO_LINE_JOIN_ROUND = 1; + public static const int CAIRO_LINE_JOIN_BEVEL = 2; + public static const int CAIRO_FONT_SLANT_NORMAL = 0; + public static const int CAIRO_FONT_SLANT_ITALIC = 1; + public static const int CAIRO_FONT_SLANT_OBLIQUE = 2; + public static const int CAIRO_FONT_WEIGHT_NORMAL = 0; + public static const int CAIRO_FONT_WEIGHT_BOLD = 1; + public static const int CAIRO_STATUS_SUCCESS = 0; + public static const int CAIRO_STATUS_NO_MEMORY = 1; + public static const int CAIRO_STATUS_INVALID_RESTORE = 2; + public static const int CAIRO_STATUS_INVALID_POP_GROUP = 3; + public static const int CAIRO_STATUS_NO_CURRENT_POINT = 4; + public static const int CAIRO_STATUS_INVALID_MATRIX = 5; + public static const int CAIRO_STATUS_NO_TARGET_SURFACE = 6; + public static const int CAIRO_STATUS_NULL_POINTER =7; + public static const int CAIRO_SURFACE_TYPE_IMAGE = 0; + public static const int CAIRO_SURFACE_TYPE_PDF = 1; public static const int CAIRO_SURFACE_TYPE_PS = 2; public static const int CAIRO_SURFACE_TYPE_XLIB = 3; public static const int CAIRO_SURFACE_TYPE_XCB = 4; @@ -126,20 +126,20 @@ public static const int CAIRO_SURFACE_TYPE_BEOS = 8; public static const int CAIRO_SURFACE_TYPE_DIRECTFB = 9; public static const int CAIRO_SURFACE_TYPE_SVG = 10; - public static const int CAIRO_FILTER_FAST = 0; - public static const int CAIRO_FILTER_GOOD = 1; - public static const int CAIRO_FILTER_BEST = 2; - public static const int CAIRO_FILTER_NEAREST = 3; - public static const int CAIRO_FILTER_BILINEAR = 4; - public static const int CAIRO_FILTER_GAUSSIAN = 5; - public static const int CAIRO_EXTEND_NONE = 0; - public static const int CAIRO_EXTEND_REPEAT = 1; - public static const int CAIRO_EXTEND_REFLECT = 2; - public static const int CAIRO_EXTEND_PAD = 3; - public static const int CAIRO_PATH_MOVE_TO = 0; - public static const int CAIRO_PATH_LINE_TO = 1; - public static const int CAIRO_PATH_CURVE_TO = 2; - public static const int CAIRO_PATH_CLOSE_PATH = 3; + public static const int CAIRO_FILTER_FAST = 0; + public static const int CAIRO_FILTER_GOOD = 1; + public static const int CAIRO_FILTER_BEST = 2; + public static const int CAIRO_FILTER_NEAREST = 3; + public static const int CAIRO_FILTER_BILINEAR = 4; + public static const int CAIRO_FILTER_GAUSSIAN = 5; + public static const int CAIRO_EXTEND_NONE = 0; + public static const int CAIRO_EXTEND_REPEAT = 1; + public static const int CAIRO_EXTEND_REFLECT = 2; + public static const int CAIRO_EXTEND_PAD = 3; + public static const int CAIRO_PATH_MOVE_TO = 0; + public static const int CAIRO_PATH_LINE_TO = 1; + public static const int CAIRO_PATH_CURVE_TO = 2; + public static const int CAIRO_PATH_CLOSE_PATH = 3; mixin ForwardGtkCairoCFunc!(.CAIRO_VERSION_ENCODE); mixin ForwardGtkCairoCFunc!(.cairo_append_path); diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/gtk/OS.d --- a/dwt/internal/gtk/OS.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/gtk/OS.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. All rights reserved. * The contents of this file are made available under the terms * of the GNU Lesser General Public License (LGPL) Version 2.1 that @@ -245,470 +245,470 @@ public class OS : Platform { /** OS Constants */ - public static /*const*/ bool IsAIX, IsSunOS, IsLinux, IsHPUX; - public static void static_this() { - /* Initialize the OS flags and locale constants */ - char[] osName = "Linux";//System.getProperty ("os.name"); - bool isAIX = false, isSunOS = false, isLinux = false, isHPUX = false; - if (osName == "Linux") isLinux = true; - if (osName == "AIX") isAIX = true; - if (osName == "Solaris") isSunOS = true; - if (osName == "SunOS") isSunOS = true; - if (osName == "HP-UX") isHPUX = true; - IsAIX = isAIX; IsSunOS = isSunOS; IsLinux = isLinux; IsHPUX = isHPUX; + public static /*const*/ bool IsAIX, IsSunOS, IsLinux, IsHPUX; + public static void static_this() { + /* Initialize the OS flags and locale constants */ + char[] osName = "Linux";//System.getProperty ("os.name"); + bool isAIX = false, isSunOS = false, isLinux = false, isHPUX = false; + if (osName == "Linux") isLinux = true; + if (osName == "AIX") isAIX = true; + if (osName == "Solaris") isSunOS = true; + if (osName == "SunOS") isSunOS = true; + if (osName == "HP-UX") isHPUX = true; + IsAIX = isAIX; IsSunOS = isSunOS; IsLinux = isLinux; IsHPUX = isHPUX; //PORTING_LEFT GTK_VERSION = buildVERSION(gtk_major_version(), gtk_minor_version(), gtk_micro_version()); - } + } - /** Constants */ - public static const int ATK_RELATION_LABELLED_BY = 4; - public static const int G_SIGNAL_MATCH_DATA = 1 << 4; - public static const int G_SIGNAL_MATCH_ID = 1 << 0; - public static const int GDK_2BUTTON_PRESS = 0x5; - public static const int GDK_3BUTTON_PRESS = 0x6; - public static const int GDK_ACTION_COPY = 1 << 1; - public static const int GDK_ACTION_MOVE = 1 << 2; - public static const int GDK_ACTION_LINK = 1 << 3; - public static const int GDK_Alt_L = 0xffe9; - public static const int GDK_Alt_R = 0xffea; - public static const int GDK_AND = 4; - public static const int GDK_BackSpace = 0xff08; - public static const int GDK_BOTTOM_LEFT_CORNER = 0xc; - public static const int GDK_BOTTOM_RIGHT_CORNER = 0xe; - public static const int GDK_BOTTOM_SIDE = 0x10; - public static const int GDK_BUTTON1_MASK = 0x100; - public static const int GDK_BUTTON2_MASK = 0x200; - public static const int GDK_BUTTON3_MASK = 0x400; - public static const int GDK_BUTTON_MOTION_MASK = 1 << 4; - public static const int GDK_BUTTON1_MOTION_MASK = 1 << 5; - public static const int GDK_BUTTON2_MOTION_MASK = 1 << 6; - public static const int GDK_BUTTON3_MOTION_MASK = 1 << 7; - public static const int GDK_BUTTON_PRESS = 0x4; - public static const int GDK_BUTTON_PRESS_MASK = 0x100; - public static const int GDK_BUTTON_RELEASE = 0x7; - public static const int GDK_BUTTON_RELEASE_MASK = 0x200; - public static const int GDK_CAP_BUTT = 0x1; - public static const int GDK_CAP_PROJECTING = 3; - public static const int GDK_CAP_ROUND = 0x2; - public static const int GDK_COLORSPACE_RGB = 0; - public static const int GDK_CONFIGURE = 13; - public static const int GDK_CONTROL_MASK = 0x4; - public static const int GDK_COPY = 0x0; - public static const int GDK_CROSS = 0x1e; - public static const int GDK_CROSSING_NORMAL = 0; - public static const int GDK_CROSSING_GRAB = 1; - public static const int GDK_CROSSING_UNGRAB = 2; - public static const int GDK_Break = 0xff6b; - public static const int GDK_Cancel = 0xff69; - public static const int GDK_Caps_Lock = 0xffE5; - public static const int GDK_Clear = 0xff0B; - public static const int GDK_Control_L = 0xffe3; - public static const int GDK_Control_R = 0xffe4; - public static const int GDK_CURRENT_TIME = 0x0; - public static const int GDK_DECOR_BORDER = 0x2; - public static const int GDK_DECOR_MAXIMIZE = 0x40; - public static const int GDK_DECOR_MENU = 0x10; - public static const int GDK_DECOR_MINIMIZE = 0x20; - public static const int GDK_DECOR_RESIZEH = 0x4; - public static const int GDK_DECOR_TITLE = 0x8; - public static const int GDK_DOUBLE_ARROW = 0x2a; - public static const int GDK_Delete = 0xffff; - public static const int GDK_Down = 0xff54; - public static const int GDK_ENTER_NOTIFY_MASK = 0x1000; - public static const int GDK_ENTER_NOTIFY = 10; - public static const int GDK_EVEN_ODD_RULE = 0; - public static const int GTK_EXPANDER_COLAPSED = 0; - public static const int GTK_EXPANDER_SEMI_COLLAPSED = 1; - public static const int GTK_EXPANDER_SEMI_EXPANDED = 2; - public static const int GTK_EXPANDER_EXPANDED = 3; - public static const int GDK_EXPOSE = 2; - public static const int GDK_EXPOSURE_MASK = 0x2; - public static const int GDK_End = 0xff57; - public static const int GDK_Escape = 0xff1b; - public static const int GDK_F1 = 0xffbe; - public static const int GDK_F10 = 0xffc7; - public static const int GDK_F11 = 0xffc8; - public static const int GDK_F12 = 0xffc9; - public static const int GDK_F13 = 0xffca; - public static const int GDK_F14 = 0xffcb; - public static const int GDK_F15 = 0xffcc; - public static const int GDK_F2 = 0xffbf; - public static const int GDK_F3 = 0xffc0; - public static const int GDK_F4 = 0xffc1; - public static const int GDK_F5 = 0xffc2; - public static const int GDK_F6 = 0xffc3; - public static const int GDK_F7 = 0xffc4; - public static const int GDK_F8 = 0xffc5; - public static const int GDK_F9 = 0xffc6; - public static const int GDK_FLEUR = 0x34; - public static const int GDK_FOCUS_CHANGE = 0xc; - public static const int GDK_FOCUS_CHANGE_MASK = 0x4000; - public static const int GDK_GC_CLIP_MASK = 0x80; - public static const int GDK_GC_CLIP_X_ORIGIN = 0x800; - public static const int GDK_GC_CLIP_Y_ORIGIN = 0x1000; - public static const int GDK_GRAB_SUCCESS = 0x0; - public static const int GDK_HAND2 = 0x3c; - public static const int GDK_Help = 0xFF6A; - public static const int GDK_HINT_MIN_SIZE = 1 << 1; - public static const int GDK_Home = 0xff50; - public static const int GDK_INCLUDE_INFERIORS = 0x1; - public static const int GDK_INPUT_ONLY = 1; - public static const int GDK_INTERP_BILINEAR = 0x2; - public static const int GDK_Insert = 0xff63; - public static const int GDK_ISO_Left_Tab = 0xfe20; - public static const int GDK_JOIN_MITER = 0x0; - public static const int GDK_JOIN_ROUND = 0x1; - public static const int GDK_JOIN_BEVEL = 0x2; - public static const int GDK_KEY_PRESS = 0x8; - public static const int GDK_KEY_PRESS_MASK = 0x400; - public static const int GDK_KEY_RELEASE = 0x9; - public static const int GDK_KEY_RELEASE_MASK = 0x800; - public static const int GDK_KP_0 = 0xffb0; - public static const int GDK_KP_1 = 0xffb1; - public static const int GDK_KP_2 = 0xffb2; - public static const int GDK_KP_3 = 0xffb3; - public static const int GDK_KP_4 = 0xffb4; - public static const int GDK_KP_5 = 0xffb5; - public static const int GDK_KP_6 = 0xffb6; - public static const int GDK_KP_7 = 0xffb7; - public static const int GDK_KP_8 = 0xffb8; - public static const int GDK_KP_9 = 0xffb9; - public static const int GDK_KP_Add = 0xffab; - public static const int GDK_KP_Decimal = 0xffae; - public static const int GDK_KP_Delete = 0xFF9F; - public static const int GDK_KP_Divide = 0xffaf; - public static const int GDK_KP_Down = 0xFF99; - public static const int GDK_KP_End = 0xFF9C; - public static const int GDK_KP_Enter = 0xff8d; - public static const int GDK_KP_Equal = 0xffbd; - public static const int GDK_KP_Home = 0xFF95; - public static const int GDK_KP_Insert = 0xFF9E; - public static const int GDK_KP_Left = 0xFF96; - public static const int GDK_KP_Multiply = 0xffaa; - public static const int GDK_KP_Page_Down = 0xFF9B; - public static const int GDK_KP_Page_Up = 0xFF9A; - public static const int GDK_KP_Right = 0xFF98; - public static const int GDK_KP_Subtract = 0xffad; - public static const int GDK_KP_Up = 0xFF97; - public static const int GDK_LEAVE_NOTIFY = 11; - public static const int GDK_LEAVE_NOTIFY_MASK = 0x2000; - public static const int GDK_LEFT_PTR = 0x44; - public static const int GDK_LEFT_SIDE = 0x46; - public static const int GDK_LINE_ON_OFF_DASH = 0x1; - public static const int GDK_LINE_SOLID = 0x0; - public static const int GDK_Linefeed = 0xff0A; - public static const int GDK_LSB_FIRST = 0x0; - public static const int GDK_Left = 0xff51; - public static const int GDK_Meta_L = 0xFFE7; - public static const int GDK_Meta_R = 0xFFE8; - public static const int GDK_MAP = 14; - public static const int GDK_MOD1_MASK = 0x8; - public static const int GDK_MOTION_NOTIFY = 0x3; - public static const int GDK_NO_EXPOSE = 30; - public static const int GDK_NONE = 0; - public static const int GDK_NOTIFY_INFERIOR = 2; - public static const int GDK_Num_Lock = 0xFF7F; - public static const int GDK_OVERLAP_RECTANGLE_OUT = 0x1; - public static const int GDK_PIXBUF_ALPHA_BILEVEL = 0x0; - public static const int GDK_POINTER_MOTION_HINT_MASK = 0x8; - public static const int GDK_POINTER_MOTION_MASK = 0x4; - public static const int GDK_PROPERTY_NOTIFY = 16; - public static const int GDK_Page_Down = 0xff56; - public static const int GDK_Page_Up = 0xff55; - public static const int GDK_Pause = 0xff13; - public static const int GDK_Print = 0xff61; - public static const int GDK_QUESTION_ARROW = 0x5c; - public static const int GDK_RGB_DITHER_NORMAL = 0x1; - public static const int GDK_RIGHT_SIDE = 0x60; - public static const int GDK_Return = 0xff0d; - public static const int GDK_Right = 0xff53; - public static const int GDK_space = 0x20; - public static const int GDK_SB_H_DOUBLE_ARROW = 0x6c; - public static const int GDK_SB_UP_ARROW = 0x72; - public static const int GDK_SB_V_DOUBLE_ARROW = 0x74; - public static const int GDK_SCROLL_UP = 0; - public static const int GDK_SCROLL_DOWN = 1; - public static const int GDK_SCROLL_LEFT = 2; - public static const int GDK_SCROLL_RIGHT = 3; - public static const int GDK_SELECTION_CLEAR = 17; - public static const int GDK_SELECTION_NOTIFY = 19; - public static const int GDK_SELECTION_REQUEST = 18; - public static const int GDK_SHIFT_MASK = 0x1; - public static const int GDK_SIZING = 0x78; - public static const int GDK_STIPPLED = 0x2; - public static const int GDK_TILED = 0x1; - public static const int GDK_Shift_L = 0xffe1; - public static const int GDK_Shift_R = 0xffe2; - public static const int GDK_SCROLL = 31; - public static const int GDK_Scroll_Lock = 0xff14; - public static const int GDK_TOP_LEFT_CORNER = 0x86; - public static const int GDK_TOP_RIGHT_CORNER = 0x88; - public static const int GDK_TOP_SIDE = 0x8a; - public static const int GDK_Tab = 0xff09; - public static const int GDK_Up = 0xff52; - public static const int GDK_WATCH = 0x96; - public static const int GDK_XOR = 0x2; - public static const int GDK_XTERM = 0x98; - public static const int GDK_X_CURSOR = 0x0; - public static const int GDK_VISIBILITY_FULLY_OBSCURED = 2; - public static const int GDK_VISIBILITY_NOTIFY_MASK = 1 << 17; - public static const int GDK_WINDOW_CHILD = 2; - public static const int GDK_WINDOW_STATE_ICONIFIED = 1 << 1; - public static const int GDK_WINDOW_STATE_MAXIMIZED = 1 << 2; - public static const int GTK_ACCEL_VISIBLE = 0x1; - public static const int GTK_ARROW_DOWN = 0x1; - public static const int GTK_ARROW_LEFT = 0x2; - public static const int GTK_ARROW_RIGHT = 0x3; - public static const int GTK_ARROW_UP = 0x0; - public static const int GTK_CALENDAR_SHOW_HEADING = 1 << 0; - public static const int GTK_CALENDAR_SHOW_DAY_NAMES = 1 << 1; - public static const int GTK_CALENDAR_NO_MONTH_CHANGE = 1 << 2; - public static const int GTK_CALENDAR_SHOW_WEEK_NUMBERS = 1 << 3; - public static const int GTK_CALENDAR_WEEK_START_MONDAY = 1 << 4; - public static const int GTK_CAN_DEFAULT = 0x2000; - public static const int GTK_CAN_FOCUS = 0x800; - public static const int GTK_CELL_RENDERER_MODE_ACTIVATABLE = 1; - public static const int GTK_CELL_RENDERER_SELECTED = 1 << 0; - public static const int GTK_CELL_RENDERER_FOCUSED = 1 << 4; - public static const int GTK_CLIST_SHOW_TITLES = 0x4; - public static const int GTK_CORNER_TOP_LEFT = 0x0; - public static const int GTK_CORNER_TOP_RIGHT = 0x2; - public static const int GTK_DIALOG_DESTROY_WITH_PARENT = 1 << 1; - public static const int GTK_DIALOG_MODAL = 1 << 0; - public static const int GTK_DIR_TAB_FORWARD = 0; - public static const int GTK_DIR_TAB_BACKWARD = 1; - public static const int GTK_FILE_CHOOSER_ACTION_OPEN = 0; - public static const int GTK_FILE_CHOOSER_ACTION_SAVE = 1; - public static const int GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER = 2; - public static const int GTK_HAS_FOCUS = 1 << 12; - public static const int GTK_ICON_SIZE_MENU = 1; - public static const int GTK_ICON_SIZE_SMALL_TOOLBAR = 2; - public static const int GTK_ICON_SIZE_LARGE_TOOLBAR = 3; - public static const int GTK_ICON_SIZE_DIALOG = 6; - public static const int GTK_JUSTIFY_CENTER = 0x2; - public static const int GTK_JUSTIFY_LEFT = 0x0; - public static const int GTK_JUSTIFY_RIGHT = 0x1; - public static const int GTK_MAPPED = 1 << 7; - public static const int GTK_MESSAGE_INFO = 0; - public static const int GTK_MESSAGE_WARNING = 1; - public static const int GTK_MESSAGE_QUESTION = 2; - public static const int GTK_MESSAGE_ERROR = 3; - public static const int GTK_NO_WINDOW = 1 << 5; - public static const int GTK_ORIENTATION_HORIZONTAL = 0x0; - public static const int GTK_ORIENTATION_VERTICAL = 0x1; - public static const int GTK_PACK_END = 1; - public static const int GTK_PACK_START = 0; - public static const int GTK_POLICY_ALWAYS = 0x0; - public static const int GTK_POLICY_AUTOMATIC = 0x1; - public static const int GTK_POLICY_NEVER = 0x2; - public static const int GTK_POS_TOP = 0x2; - public static const int GTK_POS_BOTTOM = 0x3; - public static const int GTK_PRINT_CAPABILITY_PAGE_SET = 1 << 0; - public static const int GTK_PRINT_CAPABILITY_COPIES = 1 << 1; - public static const int GTK_PRINT_CAPABILITY_COLLATE = 1 << 2; - public static const int GTK_PRINT_CAPABILITY_REVERSE = 1 << 3; - public static const int GTK_PRINT_CAPABILITY_SCALE = 1 << 4; - public static const int GTK_PRINT_CAPABILITY_GENERATE_PDF = 1 << 5; - public static const int GTK_PRINT_CAPABILITY_GENERATE_PS = 1 << 6; - public static const int GTK_PRINT_CAPABILITY_PREVIEW = 1 << 7; - public static const int GTK_PRINT_PAGES_ALL = 0; - public static const int GTK_PRINT_PAGES_CURRENT = 1; - public static const int GTK_PRINT_PAGES_RANGES = 2; - public static const int GTK_PROGRESS_CONTINUOUS = 0x0; - public static const int GTK_PROGRESS_DISCRETE = 0x1; - public static const int GTK_PROGRESS_LEFT_TO_RIGHT = 0x0; - public static const int GTK_PROGRESS_BOTTOM_TO_TOP = 0x2; - public static const int GTK_REALIZED = 1 << 6; - public static const int GTK_RELIEF_NONE = 0x2; - public static const int GTK_RELIEF_NORMAL = 0; - public static const int GTK_RC_BG = 1 << 1; - public static const int GTK_RC_FG = 1 << 0; - public static const int GTK_RC_TEXT = 1 << 2; - public static const int GTK_RC_BASE = 1 << 3; - public static const int GTK_RESPONSE_APPLY = 0xfffffff6; - public static const int GTK_RESPONSE_CANCEL = 0xfffffffa; - public static const int GTK_RESPONSE_OK = 0xfffffffb; - public static const int GTK_SCROLL_NONE = 0; - public static const int GTK_SCROLL_JUMP = 1; - public static const int GTK_SCROLL_STEP_BACKWARD = 2; - public static const int GTK_SCROLL_STEP_FORWARD = 3; - public static const int GTK_SCROLL_PAGE_BACKWARD = 4; - public static const int GTK_SCROLL_PAGE_FORWARD = 5; - public static const int GTK_SCROLL_STEP_UP = 6; - public static const int GTK_SCROLL_STEP_DOWN = 7; - public static const int GTK_SCROLL_PAGE_UP = 8; - public static const int GTK_SCROLL_PAGE_DOWN = 9; - public static const int GTK_SCROLL_STEP_LEFT = 10; - public static const int GTK_SCROLL_STEP_RIGHT = 11; - public static const int GTK_SCROLL_PAGE_LEFT = 12; - public static const int GTK_SCROLL_PAGE_RIGHT = 13; - public static const int GTK_SCROLL_START = 14; - public static const int GTK_SCROLL_END = 15; - public static const int GTK_SELECTION_BROWSE = 0x2; - public static const int GTK_SELECTION_MULTIPLE = 0x3; - public static const int GTK_SENSITIVE = 0x200; - public static const int GTK_SHADOW_ETCHED_IN = 0x3; - public static const int GTK_SHADOW_ETCHED_OUT = 0x4; - public static const int GTK_SHADOW_IN = 0x1; - public static const int GTK_SHADOW_NONE = 0x0; - public static const int GTK_SHADOW_OUT = 0x2; - public static const int GTK_STATE_ACTIVE = 0x1; - public static const int GTK_STATE_INSENSITIVE = 0x4; - public static const int GTK_STATE_NORMAL = 0x0; - public static const int GTK_STATE_PRELIGHT = 0x2; - public static const int GTK_STATE_SELECTED = 0x3; - public static const int GTK_TEXT_DIR_LTR = 1; - public static const int GTK_TEXT_DIR_NONE = 0 ; - public static const int GTK_TEXT_DIR_RTL = 2; - public static const int GTK_TEXT_WINDOW_TEXT = 2; - public static const int GTK_TOOLBAR_CHILD_BUTTON = 0x1; - public static const int GTK_TOOLBAR_CHILD_RADIOBUTTON = 0x3; - public static const int GTK_TOOLBAR_CHILD_TOGGLEBUTTON = 0x2; - public static const int GTK_TREE_VIEW_COLUMN_GROW_ONLY = 0; - public static const int GTK_TREE_VIEW_COLUMN_AUTOSIZE = 1; - public static const int GTK_TREE_VIEW_COLUMN_FIXED = 2; - public static const int GTK_TREE_VIEW_DROP_BEFORE = 0; - public static const int GTK_TREE_VIEW_DROP_AFTER = 1; - public static const int GTK_TREE_VIEW_DROP_INTO_OR_BEFORE = 2; - public static const int GTK_TREE_VIEW_DROP_INTO_OR_AFTER = 3; - public static const int GDK_UNMAP = 15; - public static const int GTK_UNIT_PIXEL = 0; - public static const int GTK_UNIT_POINTS = 1; - public static const int GTK_UNIT_INCH = 2; - public static const int GTK_UNIT_MM = 3; - public static const int GTK_VISIBILITY_FULL = 0x2; - public static const int GTK_VISIBILITY_NONE = 0x0; - public static const int GTK_VISIBLE = 0x100; - public static const int GDK_WA_X = 1 << 2; - public static const int GDK_WA_Y = 1 << 3; - public static const int GDK_WA_VISUAL = 1 << 6; - public static const int GTK_WINDOW_POPUP = 0x1; - public static const int GTK_WINDOW_TOPLEVEL = 0x0; - public static const int GDK_WINDOW_TYPE_HINT_DIALOG = 1; - public static const int GTK_WRAP_NONE = 0; - public static const int GTK_WRAP_WORD = 2; - public static const int G_LOG_FLAG_FATAL = 0x2; - public static const int G_LOG_FLAG_RECURSION = 0x1; - public static const int G_LOG_LEVEL_MASK = 0xfffffffc; - public static const int None = 0; - public static const int PANGO_ALIGN_LEFT = 0; - public static const int PANGO_ALIGN_CENTER = 1; - public static const int PANGO_ALIGN_RIGHT = 2; - public static const int PANGO_DIRECTION_LTR = 0; - public static const int PANGO_DIRECTION_RTL = 1; - public static const int PANGO_SCALE = 1024; - public static const int PANGO_STRETCH_NORMAL = 0x4; - public static const int PANGO_STYLE_ITALIC = 0x2; - public static const int PANGO_STYLE_NORMAL = 0x0; - public static const int PANGO_STYLE_OBLIQUE = 0x1; - public static const int PANGO_TAB_LEFT = 0; - public static const int PANGO_UNDERLINE_LOW = 3; - public static const int PANGO_UNDERLINE_SINGLE = 1; - public static const int PANGO_WEIGHT_BOLD = 0x2bc; - public static const int PANGO_WEIGHT_NORMAL = 0x190; - public static const int PANGO_WRAP_WORD = 0; - public static const int PANGO_WRAP_WORD_CHAR = 2; - public static const int RTLD_LAZY = 1; - public static const int XA_CARDINAL = 6; - public static const int XA_WINDOW = 33; + /** Constants */ + public static const int ATK_RELATION_LABELLED_BY = 4; + public static const int G_SIGNAL_MATCH_DATA = 1 << 4; + public static const int G_SIGNAL_MATCH_ID = 1 << 0; + public static const int GDK_2BUTTON_PRESS = 0x5; + public static const int GDK_3BUTTON_PRESS = 0x6; + public static const int GDK_ACTION_COPY = 1 << 1; + public static const int GDK_ACTION_MOVE = 1 << 2; + public static const int GDK_ACTION_LINK = 1 << 3; + public static const int GDK_Alt_L = 0xffe9; + public static const int GDK_Alt_R = 0xffea; + public static const int GDK_AND = 4; + public static const int GDK_BackSpace = 0xff08; + public static const int GDK_BOTTOM_LEFT_CORNER = 0xc; + public static const int GDK_BOTTOM_RIGHT_CORNER = 0xe; + public static const int GDK_BOTTOM_SIDE = 0x10; + public static const int GDK_BUTTON1_MASK = 0x100; + public static const int GDK_BUTTON2_MASK = 0x200; + public static const int GDK_BUTTON3_MASK = 0x400; + public static const int GDK_BUTTON_MOTION_MASK = 1 << 4; + public static const int GDK_BUTTON1_MOTION_MASK = 1 << 5; + public static const int GDK_BUTTON2_MOTION_MASK = 1 << 6; + public static const int GDK_BUTTON3_MOTION_MASK = 1 << 7; + public static const int GDK_BUTTON_PRESS = 0x4; + public static const int GDK_BUTTON_PRESS_MASK = 0x100; + public static const int GDK_BUTTON_RELEASE = 0x7; + public static const int GDK_BUTTON_RELEASE_MASK = 0x200; + public static const int GDK_CAP_BUTT = 0x1; + public static const int GDK_CAP_PROJECTING = 3; + public static const int GDK_CAP_ROUND = 0x2; + public static const int GDK_COLORSPACE_RGB = 0; + public static const int GDK_CONFIGURE = 13; + public static const int GDK_CONTROL_MASK = 0x4; + public static const int GDK_COPY = 0x0; + public static const int GDK_CROSS = 0x1e; + public static const int GDK_CROSSING_NORMAL = 0; + public static const int GDK_CROSSING_GRAB = 1; + public static const int GDK_CROSSING_UNGRAB = 2; + public static const int GDK_Break = 0xff6b; + public static const int GDK_Cancel = 0xff69; + public static const int GDK_Caps_Lock = 0xffE5; + public static const int GDK_Clear = 0xff0B; + public static const int GDK_Control_L = 0xffe3; + public static const int GDK_Control_R = 0xffe4; + public static const int GDK_CURRENT_TIME = 0x0; + public static const int GDK_DECOR_BORDER = 0x2; + public static const int GDK_DECOR_MAXIMIZE = 0x40; + public static const int GDK_DECOR_MENU = 0x10; + public static const int GDK_DECOR_MINIMIZE = 0x20; + public static const int GDK_DECOR_RESIZEH = 0x4; + public static const int GDK_DECOR_TITLE = 0x8; + public static const int GDK_DOUBLE_ARROW = 0x2a; + public static const int GDK_Delete = 0xffff; + public static const int GDK_Down = 0xff54; + public static const int GDK_ENTER_NOTIFY_MASK = 0x1000; + public static const int GDK_ENTER_NOTIFY = 10; + public static const int GDK_EVEN_ODD_RULE = 0; + public static const int GTK_EXPANDER_COLAPSED = 0; + public static const int GTK_EXPANDER_SEMI_COLLAPSED = 1; + public static const int GTK_EXPANDER_SEMI_EXPANDED = 2; + public static const int GTK_EXPANDER_EXPANDED = 3; + public static const int GDK_EXPOSE = 2; + public static const int GDK_EXPOSURE_MASK = 0x2; + public static const int GDK_End = 0xff57; + public static const int GDK_Escape = 0xff1b; + public static const int GDK_F1 = 0xffbe; + public static const int GDK_F10 = 0xffc7; + public static const int GDK_F11 = 0xffc8; + public static const int GDK_F12 = 0xffc9; + public static const int GDK_F13 = 0xffca; + public static const int GDK_F14 = 0xffcb; + public static const int GDK_F15 = 0xffcc; + public static const int GDK_F2 = 0xffbf; + public static const int GDK_F3 = 0xffc0; + public static const int GDK_F4 = 0xffc1; + public static const int GDK_F5 = 0xffc2; + public static const int GDK_F6 = 0xffc3; + public static const int GDK_F7 = 0xffc4; + public static const int GDK_F8 = 0xffc5; + public static const int GDK_F9 = 0xffc6; + public static const int GDK_FLEUR = 0x34; + public static const int GDK_FOCUS_CHANGE = 0xc; + public static const int GDK_FOCUS_CHANGE_MASK = 0x4000; + public static const int GDK_GC_CLIP_MASK = 0x80; + public static const int GDK_GC_CLIP_X_ORIGIN = 0x800; + public static const int GDK_GC_CLIP_Y_ORIGIN = 0x1000; + public static const int GDK_GRAB_SUCCESS = 0x0; + public static const int GDK_HAND2 = 0x3c; + public static const int GDK_Help = 0xFF6A; + public static const int GDK_HINT_MIN_SIZE = 1 << 1; + public static const int GDK_Home = 0xff50; + public static const int GDK_INCLUDE_INFERIORS = 0x1; + public static const int GDK_INPUT_ONLY = 1; + public static const int GDK_INTERP_BILINEAR = 0x2; + public static const int GDK_Insert = 0xff63; + public static const int GDK_ISO_Left_Tab = 0xfe20; + public static const int GDK_JOIN_MITER = 0x0; + public static const int GDK_JOIN_ROUND = 0x1; + public static const int GDK_JOIN_BEVEL = 0x2; + public static const int GDK_KEY_PRESS = 0x8; + public static const int GDK_KEY_PRESS_MASK = 0x400; + public static const int GDK_KEY_RELEASE = 0x9; + public static const int GDK_KEY_RELEASE_MASK = 0x800; + public static const int GDK_KP_0 = 0xffb0; + public static const int GDK_KP_1 = 0xffb1; + public static const int GDK_KP_2 = 0xffb2; + public static const int GDK_KP_3 = 0xffb3; + public static const int GDK_KP_4 = 0xffb4; + public static const int GDK_KP_5 = 0xffb5; + public static const int GDK_KP_6 = 0xffb6; + public static const int GDK_KP_7 = 0xffb7; + public static const int GDK_KP_8 = 0xffb8; + public static const int GDK_KP_9 = 0xffb9; + public static const int GDK_KP_Add = 0xffab; + public static const int GDK_KP_Decimal = 0xffae; + public static const int GDK_KP_Delete = 0xFF9F; + public static const int GDK_KP_Divide = 0xffaf; + public static const int GDK_KP_Down = 0xFF99; + public static const int GDK_KP_End = 0xFF9C; + public static const int GDK_KP_Enter = 0xff8d; + public static const int GDK_KP_Equal = 0xffbd; + public static const int GDK_KP_Home = 0xFF95; + public static const int GDK_KP_Insert = 0xFF9E; + public static const int GDK_KP_Left = 0xFF96; + public static const int GDK_KP_Multiply = 0xffaa; + public static const int GDK_KP_Page_Down = 0xFF9B; + public static const int GDK_KP_Page_Up = 0xFF9A; + public static const int GDK_KP_Right = 0xFF98; + public static const int GDK_KP_Subtract = 0xffad; + public static const int GDK_KP_Up = 0xFF97; + public static const int GDK_LEAVE_NOTIFY = 11; + public static const int GDK_LEAVE_NOTIFY_MASK = 0x2000; + public static const int GDK_LEFT_PTR = 0x44; + public static const int GDK_LEFT_SIDE = 0x46; + public static const int GDK_LINE_ON_OFF_DASH = 0x1; + public static const int GDK_LINE_SOLID = 0x0; + public static const int GDK_Linefeed = 0xff0A; + public static const int GDK_LSB_FIRST = 0x0; + public static const int GDK_Left = 0xff51; + public static const int GDK_Meta_L = 0xFFE7; + public static const int GDK_Meta_R = 0xFFE8; + public static const int GDK_MAP = 14; + public static const int GDK_MOD1_MASK = 0x8; + public static const int GDK_MOTION_NOTIFY = 0x3; + public static const int GDK_NO_EXPOSE = 30; + public static const int GDK_NONE = 0; + public static const int GDK_NOTIFY_INFERIOR = 2; + public static const int GDK_Num_Lock = 0xFF7F; + public static const int GDK_OVERLAP_RECTANGLE_OUT = 0x1; + public static const int GDK_PIXBUF_ALPHA_BILEVEL = 0x0; + public static const int GDK_POINTER_MOTION_HINT_MASK = 0x8; + public static const int GDK_POINTER_MOTION_MASK = 0x4; + public static const int GDK_PROPERTY_NOTIFY = 16; + public static const int GDK_Page_Down = 0xff56; + public static const int GDK_Page_Up = 0xff55; + public static const int GDK_Pause = 0xff13; + public static const int GDK_Print = 0xff61; + public static const int GDK_QUESTION_ARROW = 0x5c; + public static const int GDK_RGB_DITHER_NORMAL = 0x1; + public static const int GDK_RIGHT_SIDE = 0x60; + public static const int GDK_Return = 0xff0d; + public static const int GDK_Right = 0xff53; + public static const int GDK_space = 0x20; + public static const int GDK_SB_H_DOUBLE_ARROW = 0x6c; + public static const int GDK_SB_UP_ARROW = 0x72; + public static const int GDK_SB_V_DOUBLE_ARROW = 0x74; + public static const int GDK_SCROLL_UP = 0; + public static const int GDK_SCROLL_DOWN = 1; + public static const int GDK_SCROLL_LEFT = 2; + public static const int GDK_SCROLL_RIGHT = 3; + public static const int GDK_SELECTION_CLEAR = 17; + public static const int GDK_SELECTION_NOTIFY = 19; + public static const int GDK_SELECTION_REQUEST = 18; + public static const int GDK_SHIFT_MASK = 0x1; + public static const int GDK_SIZING = 0x78; + public static const int GDK_STIPPLED = 0x2; + public static const int GDK_TILED = 0x1; + public static const int GDK_Shift_L = 0xffe1; + public static const int GDK_Shift_R = 0xffe2; + public static const int GDK_SCROLL = 31; + public static const int GDK_Scroll_Lock = 0xff14; + public static const int GDK_TOP_LEFT_CORNER = 0x86; + public static const int GDK_TOP_RIGHT_CORNER = 0x88; + public static const int GDK_TOP_SIDE = 0x8a; + public static const int GDK_Tab = 0xff09; + public static const int GDK_Up = 0xff52; + public static const int GDK_WATCH = 0x96; + public static const int GDK_XOR = 0x2; + public static const int GDK_XTERM = 0x98; + public static const int GDK_X_CURSOR = 0x0; + public static const int GDK_VISIBILITY_FULLY_OBSCURED = 2; + public static const int GDK_VISIBILITY_NOTIFY_MASK = 1 << 17; + public static const int GDK_WINDOW_CHILD = 2; + public static const int GDK_WINDOW_STATE_ICONIFIED = 1 << 1; + public static const int GDK_WINDOW_STATE_MAXIMIZED = 1 << 2; + public static const int GTK_ACCEL_VISIBLE = 0x1; + public static const int GTK_ARROW_DOWN = 0x1; + public static const int GTK_ARROW_LEFT = 0x2; + public static const int GTK_ARROW_RIGHT = 0x3; + public static const int GTK_ARROW_UP = 0x0; + public static const int GTK_CALENDAR_SHOW_HEADING = 1 << 0; + public static const int GTK_CALENDAR_SHOW_DAY_NAMES = 1 << 1; + public static const int GTK_CALENDAR_NO_MONTH_CHANGE = 1 << 2; + public static const int GTK_CALENDAR_SHOW_WEEK_NUMBERS = 1 << 3; + public static const int GTK_CALENDAR_WEEK_START_MONDAY = 1 << 4; + public static const int GTK_CAN_DEFAULT = 0x2000; + public static const int GTK_CAN_FOCUS = 0x800; + public static const int GTK_CELL_RENDERER_MODE_ACTIVATABLE = 1; + public static const int GTK_CELL_RENDERER_SELECTED = 1 << 0; + public static const int GTK_CELL_RENDERER_FOCUSED = 1 << 4; + public static const int GTK_CLIST_SHOW_TITLES = 0x4; + public static const int GTK_CORNER_TOP_LEFT = 0x0; + public static const int GTK_CORNER_TOP_RIGHT = 0x2; + public static const int GTK_DIALOG_DESTROY_WITH_PARENT = 1 << 1; + public static const int GTK_DIALOG_MODAL = 1 << 0; + public static const int GTK_DIR_TAB_FORWARD = 0; + public static const int GTK_DIR_TAB_BACKWARD = 1; + public static const int GTK_FILE_CHOOSER_ACTION_OPEN = 0; + public static const int GTK_FILE_CHOOSER_ACTION_SAVE = 1; + public static const int GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER = 2; + public static const int GTK_HAS_FOCUS = 1 << 12; + public static const int GTK_ICON_SIZE_MENU = 1; + public static const int GTK_ICON_SIZE_SMALL_TOOLBAR = 2; + public static const int GTK_ICON_SIZE_LARGE_TOOLBAR = 3; + public static const int GTK_ICON_SIZE_DIALOG = 6; + public static const int GTK_JUSTIFY_CENTER = 0x2; + public static const int GTK_JUSTIFY_LEFT = 0x0; + public static const int GTK_JUSTIFY_RIGHT = 0x1; + public static const int GTK_MAPPED = 1 << 7; + public static const int GTK_MESSAGE_INFO = 0; + public static const int GTK_MESSAGE_WARNING = 1; + public static const int GTK_MESSAGE_QUESTION = 2; + public static const int GTK_MESSAGE_ERROR = 3; + public static const int GTK_NO_WINDOW = 1 << 5; + public static const int GTK_ORIENTATION_HORIZONTAL = 0x0; + public static const int GTK_ORIENTATION_VERTICAL = 0x1; + public static const int GTK_PACK_END = 1; + public static const int GTK_PACK_START = 0; + public static const int GTK_POLICY_ALWAYS = 0x0; + public static const int GTK_POLICY_AUTOMATIC = 0x1; + public static const int GTK_POLICY_NEVER = 0x2; + public static const int GTK_POS_TOP = 0x2; + public static const int GTK_POS_BOTTOM = 0x3; + public static const int GTK_PRINT_CAPABILITY_PAGE_SET = 1 << 0; + public static const int GTK_PRINT_CAPABILITY_COPIES = 1 << 1; + public static const int GTK_PRINT_CAPABILITY_COLLATE = 1 << 2; + public static const int GTK_PRINT_CAPABILITY_REVERSE = 1 << 3; + public static const int GTK_PRINT_CAPABILITY_SCALE = 1 << 4; + public static const int GTK_PRINT_CAPABILITY_GENERATE_PDF = 1 << 5; + public static const int GTK_PRINT_CAPABILITY_GENERATE_PS = 1 << 6; + public static const int GTK_PRINT_CAPABILITY_PREVIEW = 1 << 7; + public static const int GTK_PRINT_PAGES_ALL = 0; + public static const int GTK_PRINT_PAGES_CURRENT = 1; + public static const int GTK_PRINT_PAGES_RANGES = 2; + public static const int GTK_PROGRESS_CONTINUOUS = 0x0; + public static const int GTK_PROGRESS_DISCRETE = 0x1; + public static const int GTK_PROGRESS_LEFT_TO_RIGHT = 0x0; + public static const int GTK_PROGRESS_BOTTOM_TO_TOP = 0x2; + public static const int GTK_REALIZED = 1 << 6; + public static const int GTK_RELIEF_NONE = 0x2; + public static const int GTK_RELIEF_NORMAL = 0; + public static const int GTK_RC_BG = 1 << 1; + public static const int GTK_RC_FG = 1 << 0; + public static const int GTK_RC_TEXT = 1 << 2; + public static const int GTK_RC_BASE = 1 << 3; + public static const int GTK_RESPONSE_APPLY = 0xfffffff6; + public static const int GTK_RESPONSE_CANCEL = 0xfffffffa; + public static const int GTK_RESPONSE_OK = 0xfffffffb; + public static const int GTK_SCROLL_NONE = 0; + public static const int GTK_SCROLL_JUMP = 1; + public static const int GTK_SCROLL_STEP_BACKWARD = 2; + public static const int GTK_SCROLL_STEP_FORWARD = 3; + public static const int GTK_SCROLL_PAGE_BACKWARD = 4; + public static const int GTK_SCROLL_PAGE_FORWARD = 5; + public static const int GTK_SCROLL_STEP_UP = 6; + public static const int GTK_SCROLL_STEP_DOWN = 7; + public static const int GTK_SCROLL_PAGE_UP = 8; + public static const int GTK_SCROLL_PAGE_DOWN = 9; + public static const int GTK_SCROLL_STEP_LEFT = 10; + public static const int GTK_SCROLL_STEP_RIGHT = 11; + public static const int GTK_SCROLL_PAGE_LEFT = 12; + public static const int GTK_SCROLL_PAGE_RIGHT = 13; + public static const int GTK_SCROLL_START = 14; + public static const int GTK_SCROLL_END = 15; + public static const int GTK_SELECTION_BROWSE = 0x2; + public static const int GTK_SELECTION_MULTIPLE = 0x3; + public static const int GTK_SENSITIVE = 0x200; + public static const int GTK_SHADOW_ETCHED_IN = 0x3; + public static const int GTK_SHADOW_ETCHED_OUT = 0x4; + public static const int GTK_SHADOW_IN = 0x1; + public static const int GTK_SHADOW_NONE = 0x0; + public static const int GTK_SHADOW_OUT = 0x2; + public static const int GTK_STATE_ACTIVE = 0x1; + public static const int GTK_STATE_INSENSITIVE = 0x4; + public static const int GTK_STATE_NORMAL = 0x0; + public static const int GTK_STATE_PRELIGHT = 0x2; + public static const int GTK_STATE_SELECTED = 0x3; + public static const int GTK_TEXT_DIR_LTR = 1; + public static const int GTK_TEXT_DIR_NONE = 0 ; + public static const int GTK_TEXT_DIR_RTL = 2; + public static const int GTK_TEXT_WINDOW_TEXT = 2; + public static const int GTK_TOOLBAR_CHILD_BUTTON = 0x1; + public static const int GTK_TOOLBAR_CHILD_RADIOBUTTON = 0x3; + public static const int GTK_TOOLBAR_CHILD_TOGGLEBUTTON = 0x2; + public static const int GTK_TREE_VIEW_COLUMN_GROW_ONLY = 0; + public static const int GTK_TREE_VIEW_COLUMN_AUTOSIZE = 1; + public static const int GTK_TREE_VIEW_COLUMN_FIXED = 2; + public static const int GTK_TREE_VIEW_DROP_BEFORE = 0; + public static const int GTK_TREE_VIEW_DROP_AFTER = 1; + public static const int GTK_TREE_VIEW_DROP_INTO_OR_BEFORE = 2; + public static const int GTK_TREE_VIEW_DROP_INTO_OR_AFTER = 3; + public static const int GDK_UNMAP = 15; + public static const int GTK_UNIT_PIXEL = 0; + public static const int GTK_UNIT_POINTS = 1; + public static const int GTK_UNIT_INCH = 2; + public static const int GTK_UNIT_MM = 3; + public static const int GTK_VISIBILITY_FULL = 0x2; + public static const int GTK_VISIBILITY_NONE = 0x0; + public static const int GTK_VISIBLE = 0x100; + public static const int GDK_WA_X = 1 << 2; + public static const int GDK_WA_Y = 1 << 3; + public static const int GDK_WA_VISUAL = 1 << 6; + public static const int GTK_WINDOW_POPUP = 0x1; + public static const int GTK_WINDOW_TOPLEVEL = 0x0; + public static const int GDK_WINDOW_TYPE_HINT_DIALOG = 1; + public static const int GTK_WRAP_NONE = 0; + public static const int GTK_WRAP_WORD = 2; + public static const int G_LOG_FLAG_FATAL = 0x2; + public static const int G_LOG_FLAG_RECURSION = 0x1; + public static const int G_LOG_LEVEL_MASK = 0xfffffffc; + public static const int None = 0; + public static const int PANGO_ALIGN_LEFT = 0; + public static const int PANGO_ALIGN_CENTER = 1; + public static const int PANGO_ALIGN_RIGHT = 2; + public static const int PANGO_DIRECTION_LTR = 0; + public static const int PANGO_DIRECTION_RTL = 1; + public static const int PANGO_SCALE = 1024; + public static const int PANGO_STRETCH_NORMAL = 0x4; + public static const int PANGO_STYLE_ITALIC = 0x2; + public static const int PANGO_STYLE_NORMAL = 0x0; + public static const int PANGO_STYLE_OBLIQUE = 0x1; + public static const int PANGO_TAB_LEFT = 0; + public static const int PANGO_UNDERLINE_LOW = 3; + public static const int PANGO_UNDERLINE_SINGLE = 1; + public static const int PANGO_WEIGHT_BOLD = 0x2bc; + public static const int PANGO_WEIGHT_NORMAL = 0x190; + public static const int PANGO_WRAP_WORD = 0; + public static const int PANGO_WRAP_WORD_CHAR = 2; + public static const int RTLD_LAZY = 1; + public static const int XA_CARDINAL = 6; + public static const int XA_WINDOW = 33; - /** Signals */ - public static const char[] activate = "activate"; - public static const char[] button_press_event = "button-press-event"; - public static const char[] button_release_event = "button-release-event"; - public static const char[] changed = "changed"; - public static const char[] change_current_page = "change-current-page"; - public static const char[] change_value = "change-value"; - public static const char[] clicked = "clicked"; - public static const char[] commit = "commit"; - public static const char[] configure_event = "configure-event"; - public static const char[] delete_event = "delete-event"; - public static const char[] day_selected = "day-selected"; - public static const char[] delete_range = "delete-range"; - public static const char[] delete_text = "delete-text"; - public static const char[] drag_data_delete = "drag_data_delete"; - public static const char[] drag_data_get = "drag_data_get"; - public static const char[] drag_data_received = "drag_data_received"; - public static const char[] drag_drop = "drag_drop"; - public static const char[] drag_end = "drag_end"; - public static const char[] drag_leave = "drag_leave"; - public static const char[] drag_motion = "drag_motion"; - public static const char[] enter_notify_event = "enter-notify-event"; - public static const char[] event = "event"; - public static const char[] event_after = "event-after"; - public static const char[] expand_collapse_cursor_row = "expand-collapse-cursor-row"; - public static const char[] expose_event = "expose-event"; - public static const char[] focus = "focus"; - public static const char[] focus_in_event = "focus-in-event"; - public static const char[] focus_out_event = "focus-out-event"; - public static const char[] grab_focus = "grab-focus"; - public static const char[] hide = "hide"; - public static const char[] input = "input"; - public static const char[] insert_text = "insert-text"; - public static const char[] key_press_event = "key-press-event"; - public static const char[] key_release_event = "key-release-event"; - public static const char[] leave_notify_event = "leave-notify-event"; - public static const char[] map = "map"; - public static const char[] map_event = "map-event"; - public static const char[] mnemonic_activate = "mnemonic-activate"; - public static const char[] month_changed = "month-changed"; - public static const char[] motion_notify_event = "motion-notify-event"; - public static const char[] move_focus = "move-focus"; - public static const char[] output = "output"; - public static const char[] popup_menu = "popup-menu"; - public static const char[] preedit_changed = "preedit-changed"; - public static const char[] realize = "realize"; - public static const char[] row_activated = "row-activated"; - public static const char[] row_changed = "row-changed"; - public static const char[] scroll_child = "scroll-child"; - public static const char[] scroll_event = "scroll-event"; - public static const char[] select = "select"; - public static const char[] show = "show"; - public static const char[] show_help = "show-help"; - public static const char[] size_allocate = "size-allocate"; - public static const char[] size_request = "size-request"; - public static const char[] style_set = "style-set"; - public static const char[] switch_page = "switch-page"; - public static const char[] test_collapse_row = "test-collapse-row"; - public static const char[] test_expand_row = "test-expand-row"; - public static const char[] toggled = "toggled"; - public static const char[] unmap = "unmap"; - public static const char[] unmap_event = "unmap-event"; - public static const char[] unrealize = "unrealize"; - public static const char[] value_changed = "value-changed"; - public static const char[] visibility_notify_event = "visibility-notify-event"; - public static const char[] window_state_event = "window-state-event"; + /** Signals */ + public static const char[] activate = "activate"; + public static const char[] button_press_event = "button-press-event"; + public static const char[] button_release_event = "button-release-event"; + public static const char[] changed = "changed"; + public static const char[] change_current_page = "change-current-page"; + public static const char[] change_value = "change-value"; + public static const char[] clicked = "clicked"; + public static const char[] commit = "commit"; + public static const char[] configure_event = "configure-event"; + public static const char[] delete_event = "delete-event"; + public static const char[] day_selected = "day-selected"; + public static const char[] delete_range = "delete-range"; + public static const char[] delete_text = "delete-text"; + public static const char[] drag_data_delete = "drag_data_delete"; + public static const char[] drag_data_get = "drag_data_get"; + public static const char[] drag_data_received = "drag_data_received"; + public static const char[] drag_drop = "drag_drop"; + public static const char[] drag_end = "drag_end"; + public static const char[] drag_leave = "drag_leave"; + public static const char[] drag_motion = "drag_motion"; + public static const char[] enter_notify_event = "enter-notify-event"; + public static const char[] event = "event"; + public static const char[] event_after = "event-after"; + public static const char[] expand_collapse_cursor_row = "expand-collapse-cursor-row"; + public static const char[] expose_event = "expose-event"; + public static const char[] focus = "focus"; + public static const char[] focus_in_event = "focus-in-event"; + public static const char[] focus_out_event = "focus-out-event"; + public static const char[] grab_focus = "grab-focus"; + public static const char[] hide = "hide"; + public static const char[] input = "input"; + public static const char[] insert_text = "insert-text"; + public static const char[] key_press_event = "key-press-event"; + public static const char[] key_release_event = "key-release-event"; + public static const char[] leave_notify_event = "leave-notify-event"; + public static const char[] map = "map"; + public static const char[] map_event = "map-event"; + public static const char[] mnemonic_activate = "mnemonic-activate"; + public static const char[] month_changed = "month-changed"; + public static const char[] motion_notify_event = "motion-notify-event"; + public static const char[] move_focus = "move-focus"; + public static const char[] output = "output"; + public static const char[] popup_menu = "popup-menu"; + public static const char[] preedit_changed = "preedit-changed"; + public static const char[] realize = "realize"; + public static const char[] row_activated = "row-activated"; + public static const char[] row_changed = "row-changed"; + public static const char[] scroll_child = "scroll-child"; + public static const char[] scroll_event = "scroll-event"; + public static const char[] select = "select"; + public static const char[] show = "show"; + public static const char[] show_help = "show-help"; + public static const char[] size_allocate = "size-allocate"; + public static const char[] size_request = "size-request"; + public static const char[] style_set = "style-set"; + public static const char[] switch_page = "switch-page"; + public static const char[] test_collapse_row = "test-collapse-row"; + public static const char[] test_expand_row = "test-expand-row"; + public static const char[] toggled = "toggled"; + public static const char[] unmap = "unmap"; + public static const char[] unmap_event = "unmap-event"; + public static const char[] unrealize = "unrealize"; + public static const char[] value_changed = "value-changed"; + public static const char[] visibility_notify_event = "visibility-notify-event"; + public static const char[] window_state_event = "window-state-event"; - /** Properties */ - public static const char[] active = "active"; - public static const char[] background_gdk = "background-gdk"; - public static const char[] button_relief = "button-relief"; - public static const char[] cell_background_gdk = "cell-background-gdk"; - public static const char[] default_border = "default-border"; - public static const char[] expander_size = "expander-size"; - public static const char[] fixed_height_mode = "fixed-height-mode"; - public static const char[] focus_line_width = "focus-line-width"; - public static const char[] font_desc = "font-desc"; - public static const char[] foreground_gdk = "foreground-gdk"; - public static const char[] gtk_cursor_blink = "gtk-cursor-blink"; - public static const char[] gtk_cursor_blink_time = "gtk-cursor-blink-time"; - public static const char[] gtk_double_click_time = "gtk-double-click-time"; - public static const char[] gtk_entry_select_on_focus = "gtk-entry-select-on-focus"; - public static const char[] horizontal_separator = "horizontal-separator"; - public static const char[] inconsistent = "inconsistent"; - public static const char[] interior_focus = "interior-focus"; - public static const char[] mode = "mode"; - public static const char[] pixbuf = "pixbuf"; - public static const char[] text = "text"; - public static const char[] xalign = "xalign"; - public static const char[] ypad = "ypad"; - public static const char[] GTK_PRINT_SETTINGS_OUTPUT_URI = "output-uri"; + /** Properties */ + public static const char[] active = "active"; + public static const char[] background_gdk = "background-gdk"; + public static const char[] button_relief = "button-relief"; + public static const char[] cell_background_gdk = "cell-background-gdk"; + public static const char[] default_border = "default-border"; + public static const char[] expander_size = "expander-size"; + public static const char[] fixed_height_mode = "fixed-height-mode"; + public static const char[] focus_line_width = "focus-line-width"; + public static const char[] font_desc = "font-desc"; + public static const char[] foreground_gdk = "foreground-gdk"; + public static const char[] gtk_cursor_blink = "gtk-cursor-blink"; + public static const char[] gtk_cursor_blink_time = "gtk-cursor-blink-time"; + public static const char[] gtk_double_click_time = "gtk-double-click-time"; + public static const char[] gtk_entry_select_on_focus = "gtk-entry-select-on-focus"; + public static const char[] horizontal_separator = "horizontal-separator"; + public static const char[] inconsistent = "inconsistent"; + public static const char[] interior_focus = "interior-focus"; + public static const char[] mode = "mode"; + public static const char[] pixbuf = "pixbuf"; + public static const char[] text = "text"; + public static const char[] xalign = "xalign"; + public static const char[] ypad = "ypad"; + public static const char[] GTK_PRINT_SETTINGS_OUTPUT_URI = "output-uri"; - public static /*const*/ int GTK_VERSION;// see static ctor = buildVERSION(gtk_major_version(), gtk_minor_version(), gtk_micro_version()); + public static /*const*/ int GTK_VERSION;// see static ctor = buildVERSION(gtk_major_version(), gtk_minor_version(), gtk_micro_version()); public static int buildVERSION(int major, int minor, int micro) { - return (major << 16) + (minor << 8) + micro; + return (major << 16) + (minor << 8) + micro; } /++ @@ -908,7 +908,7 @@ mixin ForwardGtkOsCFunc!(.g_malloc); mixin ForwardGtkOsCFunc!(.g_object_get1); mixin ForwardGtkOsCFunc!(.g_object_get_qdata); - mixin ForwardGtkOsCFunc!(.g_object_new ); + mixin ForwardGtkOsCFunc!(.g_object_new); mixin ForwardGtkOsCFunc!(.g_object_ref); mixin ForwardGtkOsCFunc!(.g_object_set); mixin ForwardGtkOsCFunc!(.g_object_set); @@ -2084,7 +2084,7 @@ { lock.lock(); scope(exit) lock.unlock(); - return cast(bool)g_type_check_instance_is_a( arg0, gtk_button_get_type() ); + return cast(bool)g_type_check_instance_is_a( arg0, gtk_button_get_type() ); } static bool GTK_IS_WINDOW( GTypeInstance* arg0 ) diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/gtk/runtime/Loader.d --- a/dwt/internal/gtk/runtime/Loader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/gtk/runtime/Loader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,20 +1,20 @@ -/***************************************************************************** +/***************************************************************************** - license: + license: - version: + version: - Dynamic loader for gtk symbol names + Dynamic loader for gtk symbol names - History: 2004-12-11 initial version by John Reimer - 2005-02-21 class and symbol names change; versioning modification - 2005-05-05 linux fixes - 2007-12-23 source cleanup - 2007-12-30 merge Paths.d into Loader.d + History: 2004-12-11 initial version by John Reimer + 2005-02-21 class and symbol names change; versioning modification + 2005-05-05 linux fixes + 2007-12-23 source cleanup + 2007-12-30 merge Paths.d into Loader.d 2008-01-05 Tango only version using tango.sys.SharedLib - Note: Design inspired by Kris Bell's ICU.d, the dynamic loader from - an early version of mango + Note: Design inspired by Kris Bell's ICU.d, the dynamic loader from + an early version of mango ******************************************************************************/ @@ -29,26 +29,26 @@ enum LIBRARY { - ATK, - CAIRO, - GDK, - GDKPIXBUF, - GLIB, - GMODULE, - GOBJECT, - GTHREAD, - GTK, - PANGO, - GLGDK, - GLGTK, - GL, - GLU, - GLEXT, - GDA, - GLADE, - GSV, - GSTREAMER, - GSTINTERFACES + ATK, + CAIRO, + GDK, + GDKPIXBUF, + GLIB, + GMODULE, + GOBJECT, + GTHREAD, + GTK, + PANGO, + GLGDK, + GLGTK, + GL, + GLU, + GLEXT, + GDA, + GLADE, + GSV, + GSTREAMER, + GSTINTERFACES } /***************************************************************************** @@ -57,27 +57,27 @@ version (Windows) { - const char[][LIBRARY.max+1] importLibs = [ - LIBRARY.ATK: "libatk-1.0-0.dll", - LIBRARY.CAIRO: "libcairo-2.dll", - LIBRARY.GDK: "libgdk-win32-2.0-0.dll", - LIBRARY.GDKPIXBUF: "libgdk_pixbuf-2.0-0.dll", - LIBRARY.GLIB: "libglib-2.0-0.dll", - LIBRARY.GMODULE: "libgmodule-2.0-0.dll", - LIBRARY.GOBJECT: "libgobject-2.0-0.dll", - LIBRARY.GTHREAD: "libgthread-2.0-0.dll", - LIBRARY.GTK: "libgtk-win32-2.0-0.dll", - LIBRARY.PANGO: "libpango-1.0-0.dll", - LIBRARY.GLGDK: "libgdkglext-win32-1.0-0.dll", - LIBRARY.GLGTK: "libgtkglext-win32-1.0-0.dll", - LIBRARY.GL: "opengl32.dll", - LIBRARY.GLU: "glu32.dll", - LIBRARY.GDA: "libgda-2.dll", - LIBRARY.GLADE: "libglade-2.0.dll", - LIBRARY.GSV: "libgtksourceview-1.0-0.dll", - LIBRARY.GSTREAMER: "libgstreamer-0.10.dll", - LIBRARY.GSTINTERFACES: "libgstinterfaces-0.10.dll" - ]; + const char[][LIBRARY.max+1] importLibs = [ + LIBRARY.ATK: "libatk-1.0-0.dll", + LIBRARY.CAIRO: "libcairo-2.dll", + LIBRARY.GDK: "libgdk-win32-2.0-0.dll", + LIBRARY.GDKPIXBUF: "libgdk_pixbuf-2.0-0.dll", + LIBRARY.GLIB: "libglib-2.0-0.dll", + LIBRARY.GMODULE: "libgmodule-2.0-0.dll", + LIBRARY.GOBJECT: "libgobject-2.0-0.dll", + LIBRARY.GTHREAD: "libgthread-2.0-0.dll", + LIBRARY.GTK: "libgtk-win32-2.0-0.dll", + LIBRARY.PANGO: "libpango-1.0-0.dll", + LIBRARY.GLGDK: "libgdkglext-win32-1.0-0.dll", + LIBRARY.GLGTK: "libgtkglext-win32-1.0-0.dll", + LIBRARY.GL: "opengl32.dll", + LIBRARY.GLU: "glu32.dll", + LIBRARY.GDA: "libgda-2.dll", + LIBRARY.GLADE: "libglade-2.0.dll", + LIBRARY.GSV: "libgtksourceview-1.0-0.dll", + LIBRARY.GSTREAMER: "libgstreamer-0.10.dll", + LIBRARY.GSTINTERFACES: "libgstinterfaces-0.10.dll" + ]; } /***************************************************************************** @@ -86,28 +86,28 @@ version(linux) { - const char[][LIBRARY.max+1] importLibs = [ - LIBRARY.ATK: "libatk-1.0.so", - LIBRARY.CAIRO: "libcairo.so.2", - LIBRARY.GDK: "libgdk-x11-2.0.so", - LIBRARY.GDKPIXBUF: "libgdk_pixbuf-2.0.so", - LIBRARY.GLIB: "libglib-2.0.so", - LIBRARY.GMODULE: "libgmodule-2.0.so", - LIBRARY.GOBJECT: "libgobject-2.0.so", - LIBRARY.GTHREAD: "libgthread-2.0.so", - LIBRARY.GTK: "libgtk-x11-2.0.so", - LIBRARY.PANGO: "libpango-1.0.so", - LIBRARY.GLGDK: "libgdkglext-x11-1.0.so", - LIBRARY.GLGTK: "libgtkglext-x11-1.0.so", - LIBRARY.GL: "libGL.so", - LIBRARY.GLU: "libGLU.so", - LIBRARY.GLEXT: "libGL.so", - LIBRARY.GDA: "libgda-2.so.3", - LIBRARY.GLADE: "libglade-2.0.so", - LIBRARY.GSV: "libgtksourceview-1.0.so", - LIBRARY.GSTREAMER: "libgstreamer-0.10.so", - LIBRARY.GSTINTERFACES: "libgstinterfaces-0.10.so" - ]; + const char[][LIBRARY.max+1] importLibs = [ + LIBRARY.ATK: "libatk-1.0.so", + LIBRARY.CAIRO: "libcairo.so.2", + LIBRARY.GDK: "libgdk-x11-2.0.so", + LIBRARY.GDKPIXBUF: "libgdk_pixbuf-2.0.so", + LIBRARY.GLIB: "libglib-2.0.so", + LIBRARY.GMODULE: "libgmodule-2.0.so", + LIBRARY.GOBJECT: "libgobject-2.0.so", + LIBRARY.GTHREAD: "libgthread-2.0.so", + LIBRARY.GTK: "libgtk-x11-2.0.so", + LIBRARY.PANGO: "libpango-1.0.so", + LIBRARY.GLGDK: "libgdkglext-x11-1.0.so", + LIBRARY.GLGTK: "libgtkglext-x11-1.0.so", + LIBRARY.GL: "libGL.so", + LIBRARY.GLU: "libGLU.so", + LIBRARY.GLEXT: "libGL.so", + LIBRARY.GDA: "libgda-2.so.3", + LIBRARY.GLADE: "libglade-2.0.so", + LIBRARY.GSV: "libgtksourceview-1.0.so", + LIBRARY.GSTREAMER: "libgstreamer-0.10.so", + LIBRARY.GSTINTERFACES: "libgstinterfaces-0.10.so" + ]; } /***************************************************************************** @@ -119,206 +119,206 @@ version(Windows) { - char[] getLibraryPath() - { - return "\\Program Files\\GTK2-Runtime\\lib\\"; - } + char[] getLibraryPath() + { + return "\\Program Files\\GTK2-Runtime\\lib\\"; + } } /***************************************************************************** - getLibraryPath is empty for linux because default path is known by ld + getLibraryPath is empty for linux because default path is known by ld ******************************************************************************/ version(linux) { - char[] getLibraryPath() { return ""; } + char[] getLibraryPath() { return ""; } } /***************************************************************************** - ProcLink is used to record the library, function, and function name - that will be loaded by the dynamic loader. + ProcLink is used to record the library, function, and function name + that will be loaded by the dynamic loader. ******************************************************************************/ public struct Symbol { - char[] name; - void** pointer; + char[] name; + void** pointer; } /***************************************************************************** - The Linker class: handles loading of the library and exported functions + The Linker class: handles loading of the library and exported functions ******************************************************************************/ public class Linker { - static char[][][char[]] loadFailures; + static char[][][char[]] loadFailures; - /************************************************************************* + /************************************************************************* - Gets all the failed loads for a specific library. This is filled in - only if the default onFailure method is used during load. + Gets all the failed loads for a specific library. This is filled in + only if the default onFailure method is used during load. - returns: an array of the names that failed to load for a specific - library or null if none was found. + returns: an array of the names that failed to load for a specific + library or null if none was found. - **************************************************************************/ + **************************************************************************/ - public static char[][] getLoadFailures(char[] libName) - { - if ( libName in loadFailures ) - { - return loadFailures[libName]; - } - else - { - return null; - } - } + public static char[][] getLoadFailures(char[] libName) + { + if ( libName in loadFailures ) + { + return loadFailures[libName]; + } + else + { + return null; + } + } - /************************************************************************* + /************************************************************************* - Loads all libraries. This is filled in only if the default onFailure - method is used during load. + Loads all libraries. This is filled in only if the default onFailure + method is used during load. - returns: an array of the library names. + returns: an array of the library names. - **************************************************************************/ + **************************************************************************/ - public static char[][] getLoadLibraries() - { - return loadFailures.keys; - } + public static char[][] getLoadLibraries() + { + return loadFailures.keys; + } - /************************************************************************* + /************************************************************************* - isPerfectLoad -- Checks if any symbol failed to load. - Returns: true if ALL symbols loaded. + isPerfectLoad -- Checks if any symbol failed to load. + Returns: true if ALL symbols loaded. - **************************************************************************/ + **************************************************************************/ - public static bool isPerfectLoad() - { - return loadFailures.keys.length == 0; - } + public static bool isPerfectLoad() + { + return loadFailures.keys.length == 0; + } - /************************************************************************* + /************************************************************************* - **************************************************************************/ + **************************************************************************/ - public static void dumpFailedLoads() - { - foreach ( char[] lib ; Linker.getLoadLibraries() ) - { - foreach ( char[] symbol ; Linker.getLoadFailures(lib) ) - { - version(Tango) - Stdout.formatln("failed ({}) {}", lib, symbol).newline; - } - } - } + public static void dumpFailedLoads() + { + foreach ( char[] lib ; Linker.getLoadLibraries() ) + { + foreach ( char[] symbol ; Linker.getLoadFailures(lib) ) + { + version(Tango) + Stdout.formatln("failed ({}) {}", lib, symbol).newline; + } + } + } - /************************************************************************* + /************************************************************************* - **************************************************************************/ + **************************************************************************/ - private SharedLib primaryLib; - private SharedLib alternateLib; + private SharedLib primaryLib; + private SharedLib alternateLib; - private char[] libraryName; - private char[] alternateLibraryName; + private char[] libraryName; + private char[] alternateLibraryName; - alias void function( char[] libraryName, char[] symbolName, char[] message=null) FailureCallback; + alias void function( char[] libraryName, char[] symbolName, char[] message=null) FailureCallback; - private FailureCallback onLoadFailure; + private FailureCallback onLoadFailure; - /************************************************************************* + /************************************************************************* - **************************************************************************/ + **************************************************************************/ - this( char[] libraryName, char[] alternateLibraryName=null ) - { - this(libraryName, alternateLibraryName, &(Linker.defaultFail)); - } + this( char[] libraryName, char[] alternateLibraryName=null ) + { + this(libraryName, alternateLibraryName, &(Linker.defaultFail)); + } - /************************************************************************* + /************************************************************************* - **************************************************************************/ + **************************************************************************/ - this (char[] libraryName, char[] alternateLibraryName, FailureCallback fn ) - { - this.libraryName = libraryName; - this.alternateLibraryName = alternateLibraryName; - onLoadFailure = fn; + this (char[] libraryName, char[] alternateLibraryName, FailureCallback fn ) + { + this.libraryName = libraryName; + this.alternateLibraryName = alternateLibraryName; + onLoadFailure = fn; SharedLib.throwExceptions = false; - primaryLib = SharedLib.load( this.libraryName ); + primaryLib = SharedLib.load( this.libraryName ); version(linux) { if (this.primaryLib is null) primaryLib = SharedLib.load( this.libraryName ~ ".0\0" ); } - + if ( alternateLibraryName !is null ) - { - alternateLib = SharedLib.load( this.alternateLibraryName ); - } - - if (primaryLib is null) - { - throw new Exception("Library load failed: " ~ libraryName); - } - } + { + alternateLib = SharedLib.load( this.alternateLibraryName ); + } + + if (primaryLib is null) + { + throw new Exception("Library load failed: " ~ libraryName); + } + } - /************************************************************************* + /************************************************************************* - Default load failure callback. Logs the symbols that failed to load. + Default load failure callback. Logs the symbols that failed to load. - **************************************************************************/ + **************************************************************************/ - static void defaultFail( char[] libraryName, char[] symbolName, char[] message=null ) - { - if ( !(libraryName in loadFailures) ) - { - char[][] cc; - loadFailures[libraryName] = cc; - } + static void defaultFail( char[] libraryName, char[] symbolName, char[] message=null ) + { + if ( !(libraryName in loadFailures) ) + { + char[][] cc; + loadFailures[libraryName] = cc; + } - loadFailures[libraryName] ~= symbolName.dup; - } + loadFailures[libraryName] ~= symbolName.dup; + } - /************************************************************************* + /************************************************************************* - Loads all the symbols for this library. + Loads all the symbols for this library. - **************************************************************************/ + **************************************************************************/ - void link( inout Symbol[] symbols ) - { - foreach( Symbol link; symbols ) - { - *link.pointer = primaryLib.getSymbol ( (link.name~"\0").ptr); + void link( inout Symbol[] symbols ) + { + foreach( Symbol link; symbols ) + { + *link.pointer = primaryLib.getSymbol ( (link.name~"\0").ptr); - if (*link.pointer is null) - { - if ( alternateLib !is null ) - { - *link.pointer = alternateLib.getSymbol( (link.name~"\0").ptr); + if (*link.pointer is null) + { + if ( alternateLib !is null ) + { + *link.pointer = alternateLib.getSymbol( (link.name~"\0").ptr); Stdout("Loader.Linker.link trying alternate lib: ", link.name).newline; } - if (*link.pointer is null) - { - onLoadFailure( libraryName, link.name ); - } - } - } - } + if (*link.pointer is null) + { + onLoadFailure( libraryName, link.name ); + } + } + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/FileFormat.d --- a/dwt/internal/image/FileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/FileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -37,14 +37,14 @@ * */ public abstract class FileFormat { - static const char[] FORMAT_PACKAGE = "dwt.internal.image"; //$NON-NLS-1$ - static const char[] FORMAT_SUFFIX = "FileFormat"; //$NON-NLS-1$ - static const char[][] FORMATS = [ "WinBMP"[], "WinBMP", "GIF", "WinICO", "JPEG", "PNG", "TIFF", "OS2BMP" ]; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$//$NON-NLS-5$ //$NON-NLS-6$//$NON-NLS-7$//$NON-NLS-8$ + static const char[] FORMAT_PACKAGE = "dwt.internal.image"; //$NON-NLS-1$ + static const char[] FORMAT_SUFFIX = "FileFormat"; //$NON-NLS-1$ + static const char[][] FORMATS = [ "WinBMP"[], "WinBMP", "GIF", "WinICO", "JPEG", "PNG", "TIFF", "OS2BMP" ]; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$//$NON-NLS-5$ //$NON-NLS-6$//$NON-NLS-7$//$NON-NLS-8$ alias Tuple!( WinBMPFileFormat, WinBMPFileFormat, GIFFileFormat, WinICOFileFormat, JPEGFileFormat, PNGFileFormat, TIFFFileFormat, OS2BMPFileFormat ) TFormats; - LEDataInputStream inputStream; - LEDataOutputStream outputStream; - ImageLoader loader; - int compression; + LEDataInputStream inputStream; + LEDataOutputStream outputStream; + ImageLoader loader; + int compression; /** * Return whether or not the specified input stream @@ -59,16 +59,16 @@ * device independent image array represented by the stream. */ public ImageData[] loadFromStream(LEDataInputStream stream) { - try { - inputStream = stream; - return loadFromByteStream(); + try { + inputStream = stream; + return loadFromByteStream(); } catch (IOException e) { SWT.error(SWT.ERROR_IO, e); return null; } catch (TracedException e) { SWT.error(SWT.ERROR_INVALID_IMAGE, e); - return null; - } + return null; + } } /** @@ -76,9 +76,9 @@ * return the device independent image array represented by the stream. */ public static ImageData[] load(InputStream istr, ImageLoader loader) { - FileFormat fileFormat = null; - LEDataInputStream stream = new LEDataInputStream(istr); - bool isSupported = false; + FileFormat fileFormat = null; + LEDataInputStream stream = new LEDataInputStream(istr); + bool isSupported = false; foreach( TFormat; TFormats ){ try{ fileFormat = new TFormat(); @@ -89,9 +89,9 @@ } catch (TracedException e) { } } - if (!isSupported) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - fileFormat.loader = loader; - return fileFormat.loadFromStream(stream); + if (!isSupported) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + fileFormat.loader = loader; + return fileFormat.loadFromStream(stream); } /** @@ -99,29 +99,29 @@ * to the specified output stream using the specified file format. */ public static void save(OutputStream os, int format, ImageLoader loader) { - if (format < 0 || format >= FORMATS.length) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - if (FORMATS[format] == null) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - if (loader.data == null || loader.data.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (format < 0 || format >= FORMATS.length) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + if (FORMATS[format] == null) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + if (loader.data == null || loader.data.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - LEDataOutputStream stream = new LEDataOutputStream(os); - FileFormat fileFormat = null; - try { + LEDataOutputStream stream = new LEDataOutputStream(os); + FileFormat fileFormat = null; + try { foreach( idx, TFormat; TFormats ){ if( idx == format ){ fileFormat = new TFormat(); } } - } catch (TracedException e) { - SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - } - if (format == SWT.IMAGE_BMP_RLE) { - switch (loader.data[0].depth) { - case 8: fileFormat.compression = 1; break; - case 4: fileFormat.compression = 2; break; + } catch (TracedException e) { + SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + } + if (format == SWT.IMAGE_BMP_RLE) { + switch (loader.data[0].depth) { + case 8: fileFormat.compression = 1; break; + case 4: fileFormat.compression = 2; break; default: - } - } - fileFormat.unloadIntoStream(loader, stream); + } + } + fileFormat.unloadIntoStream(loader, stream); } abstract void unloadIntoByteStream(ImageLoader loader); @@ -131,13 +131,13 @@ * to the specified output stream. */ public void unloadIntoStream(ImageLoader loader, LEDataOutputStream stream) { - try { - outputStream = stream; - unloadIntoByteStream(loader); - outputStream.flush(); - } catch (TracedException e) { - try {outputStream.flush();} catch (Exception f) {} - SWT.error(SWT.ERROR_IO, e); - } + try { + outputStream = stream; + unloadIntoByteStream(loader); + outputStream.flush(); + } catch (TracedException e) { + try {outputStream.flush();} catch (Exception f) {} + SWT.error(SWT.ERROR_IO, e); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/GIFFileFormat.d --- a/dwt/internal/image/GIFFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/GIFFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -25,597 +25,597 @@ class Image{} final class GIFFileFormat : FileFormat { - char[] signature; - int screenWidth, screenHeight, backgroundPixel, bitsPerPixel, defaultDepth; - int disposalMethod = 0; - int delayTime = 0; - int transparentPixel = -1; - int repeatCount = 1; + char[] signature; + int screenWidth, screenHeight, backgroundPixel, bitsPerPixel, defaultDepth; + int disposalMethod = 0; + int delayTime = 0; + int transparentPixel = -1; + int repeatCount = 1; - static final int GIF_APPLICATION_EXTENSION_BLOCK_ID = 0xFF; - static final int GIF_GRAPHICS_CONTROL_BLOCK_ID = 0xF9; - static final int GIF_PLAIN_TEXT_BLOCK_ID = 0x01; - static final int GIF_COMMENT_BLOCK_ID = 0xFE; - static final int GIF_EXTENSION_BLOCK_ID = 0x21; - static final int GIF_IMAGE_BLOCK_ID = 0x2C; - static final int GIF_TRAILER_ID = 0x3B; - static final byte[] GIF89a = cast(byte[])"GIF89a"; - static final byte[] NETSCAPE2_0 = cast(byte[])"NETSCAPE2.0"; + static final int GIF_APPLICATION_EXTENSION_BLOCK_ID = 0xFF; + static final int GIF_GRAPHICS_CONTROL_BLOCK_ID = 0xF9; + static final int GIF_PLAIN_TEXT_BLOCK_ID = 0x01; + static final int GIF_COMMENT_BLOCK_ID = 0xFE; + static final int GIF_EXTENSION_BLOCK_ID = 0x21; + static final int GIF_IMAGE_BLOCK_ID = 0x2C; + static final int GIF_TRAILER_ID = 0x3B; + static final byte[] GIF89a = cast(byte[])"GIF89a"; + static final byte[] NETSCAPE2_0 = cast(byte[])"NETSCAPE2.0"; - /** - * Answer a palette containing numGrays - * shades of gray, ranging from black to white. - */ - static PaletteData grayRamp(int numGrays) { - int n = numGrays - 1; - RGB[] colors = new RGB[numGrays]; - for (int i = 0; i < numGrays; i++) { - int intensity = cast(byte)((i * 3) * 256 / n); - colors[i] = new RGB(intensity, intensity, intensity); - } - return new PaletteData(colors); - } + /** + * Answer a palette containing numGrays + * shades of gray, ranging from black to white. + */ + static PaletteData grayRamp(int numGrays) { + int n = numGrays - 1; + RGB[] colors = new RGB[numGrays]; + for (int i = 0; i < numGrays; i++) { + int intensity = cast(byte)((i * 3) * 256 / n); + colors[i] = new RGB(intensity, intensity, intensity); + } + return new PaletteData(colors); + } - bool isFileFormat(LEDataInputStream stream) { - try { - byte[3] signature; - stream.read(signature); - stream.unread(signature); - return signature == cast(byte[])"GIF"; //$NON-NLS-1$ - } catch (Exception e) { - return false; - } - } + bool isFileFormat(LEDataInputStream stream) { + try { + byte[3] signature; + stream.read(signature); + stream.unread(signature); + return signature == cast(byte[])"GIF"; //$NON-NLS-1$ + } catch (Exception e) { + return false; + } + } - /** - * Load the GIF image(s) stored in the input stream. - * Return an array of ImageData representing the image(s). - */ - ImageData[] loadFromByteStream() { - byte[3] signatureBytes; - byte[3] versionBytes; - byte[7] block; - try { - inputStream.read(signatureBytes); - signature = cast(char[])signatureBytes.dup; - if (signature != "GIF") //$NON-NLS-1$ - SWT.error(SWT.ERROR_INVALID_IMAGE); + /** + * Load the GIF image(s) stored in the input stream. + * Return an array of ImageData representing the image(s). + */ + ImageData[] loadFromByteStream() { + byte[3] signatureBytes; + byte[3] versionBytes; + byte[7] block; + try { + inputStream.read(signatureBytes); + signature = cast(char[])signatureBytes.dup; + if (signature != "GIF") //$NON-NLS-1$ + SWT.error(SWT.ERROR_INVALID_IMAGE); - inputStream.read(versionBytes); + inputStream.read(versionBytes); - inputStream.read(block); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - screenWidth = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8); - loader.logicalScreenWidth = screenWidth; - screenHeight = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8); - loader.logicalScreenHeight = screenHeight; - byte bitField = block[4]; - backgroundPixel = block[5] & 0xFF; - //aspect = block[6] & 0xFF; - bitsPerPixel = ((bitField >> 4) & 0x07) + 1; - defaultDepth = (bitField & 0x7) + 1; - PaletteData palette = null; - if ((bitField & 0x80) != 0) { - // Global palette. - //sorted = (bitField & 0x8) != 0; - palette = readPalette(1 << defaultDepth); - } else { - // No global palette. - //sorted = false; - backgroundPixel = -1; - defaultDepth = bitsPerPixel; - } - loader.backgroundPixel = backgroundPixel; + inputStream.read(block); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + screenWidth = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8); + loader.logicalScreenWidth = screenWidth; + screenHeight = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8); + loader.logicalScreenHeight = screenHeight; + byte bitField = block[4]; + backgroundPixel = block[5] & 0xFF; + //aspect = block[6] & 0xFF; + bitsPerPixel = ((bitField >> 4) & 0x07) + 1; + defaultDepth = (bitField & 0x7) + 1; + PaletteData palette = null; + if ((bitField & 0x80) != 0) { + // Global palette. + //sorted = (bitField & 0x8) != 0; + palette = readPalette(1 << defaultDepth); + } else { + // No global palette. + //sorted = false; + backgroundPixel = -1; + defaultDepth = bitsPerPixel; + } + loader.backgroundPixel = backgroundPixel; - getExtensions(); - int id = readID(); - ImageData[] images = new ImageData[0]; - while (id == GIF_IMAGE_BLOCK_ID) { - ImageData image = readImageBlock(palette); - if (loader.hasListeners()) { - loader.notifyListeners(new ImageLoaderEvent(loader, image, 3, true)); - } + getExtensions(); + int id = readID(); + ImageData[] images = new ImageData[0]; + while (id == GIF_IMAGE_BLOCK_ID) { + ImageData image = readImageBlock(palette); + if (loader.hasListeners()) { + loader.notifyListeners(new ImageLoaderEvent(loader, image, 3, true)); + } ImageData[] oldImages = images; images = new ImageData[oldImages.length + 1]; System.arraycopy(oldImages, 0, images, 0, oldImages.length); images[images.length - 1] = image; //images ~= image; - try { - /* Read the 0-byte terminator at the end of the image. */ - id = inputStream.read(); - if (id > 0) { - /* We read the terminator earlier. */ + try { + /* Read the 0-byte terminator at the end of the image. */ + id = inputStream.read(); + if (id > 0) { + /* We read the terminator earlier. */ byte[1] arr; arr[0] = id; - inputStream.unread( arr ); - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - getExtensions(); - id = readID(); - } - return images; - } + inputStream.unread( arr ); + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + getExtensions(); + id = readID(); + } + return images; + } - /** - * Read and return the next block or extension identifier from the file. - */ - int readID() { - try { - return inputStream.read(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return -1; - } + /** + * Read and return the next block or extension identifier from the file. + */ + int readID() { + try { + return inputStream.read(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return -1; + } - /** - * Read extensions until an image descriptor appears. - * In the future, if we care about the extensions, they - * should be properly grouped with the image data before - * which they appeared. Right now, the interesting parts - * of some extensions are kept, but the rest is discarded. - * Throw an error if an error occurs. - */ - void getExtensions() { - int id = readID(); - while (id != GIF_IMAGE_BLOCK_ID && id != GIF_TRAILER_ID && id > 0) { - if (id == GIF_EXTENSION_BLOCK_ID) { - readExtension(); - } else { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - id = readID(); - } - if (id == GIF_IMAGE_BLOCK_ID || id == GIF_TRAILER_ID) { - try { + /** + * Read extensions until an image descriptor appears. + * In the future, if we care about the extensions, they + * should be properly grouped with the image data before + * which they appeared. Right now, the interesting parts + * of some extensions are kept, but the rest is discarded. + * Throw an error if an error occurs. + */ + void getExtensions() { + int id = readID(); + while (id != GIF_IMAGE_BLOCK_ID && id != GIF_TRAILER_ID && id > 0) { + if (id == GIF_EXTENSION_BLOCK_ID) { + readExtension(); + } else { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + id = readID(); + } + if (id == GIF_IMAGE_BLOCK_ID || id == GIF_TRAILER_ID) { + try { byte[1] arr; arr[0] = id; - inputStream.unread(arr); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - } + inputStream.unread(arr); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + } - /** - * Read a control extension. - * Return the extension block data. - */ - byte[] readExtension() { - int extensionID = readID(); - if (extensionID == GIF_COMMENT_BLOCK_ID) - return readCommentExtension(); - if (extensionID == GIF_PLAIN_TEXT_BLOCK_ID) - return readPlainTextExtension(); - if (extensionID == GIF_GRAPHICS_CONTROL_BLOCK_ID) - return readGraphicsControlExtension(); - if (extensionID == GIF_APPLICATION_EXTENSION_BLOCK_ID) - return readApplicationExtension(); - // Otherwise, we don't recognize the block. If the - // field size is correct, we can just skip over - // the block contents. - try { - int extSize = inputStream.read(); - if (extSize < 0) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - byte[] ext = new byte[extSize]; - inputStream.read(ext, 0, extSize); - return ext; - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } + /** + * Read a control extension. + * Return the extension block data. + */ + byte[] readExtension() { + int extensionID = readID(); + if (extensionID == GIF_COMMENT_BLOCK_ID) + return readCommentExtension(); + if (extensionID == GIF_PLAIN_TEXT_BLOCK_ID) + return readPlainTextExtension(); + if (extensionID == GIF_GRAPHICS_CONTROL_BLOCK_ID) + return readGraphicsControlExtension(); + if (extensionID == GIF_APPLICATION_EXTENSION_BLOCK_ID) + return readApplicationExtension(); + // Otherwise, we don't recognize the block. If the + // field size is correct, we can just skip over + // the block contents. + try { + int extSize = inputStream.read(); + if (extSize < 0) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + byte[] ext = new byte[extSize]; + inputStream.read(ext, 0, extSize); + return ext; + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } - /** - * We have just read the Comment extension identifier - * from the input stream. Read in the rest of the comment - * and return it. GIF comment blocks are variable size. - */ - byte[] readCommentExtension() { - try { - byte[] comment = new byte[0]; - byte[] block = new byte[255]; - int size = inputStream.read(); - while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { + /** + * We have just read the Comment extension identifier + * from the input stream. Read in the rest of the comment + * and return it. GIF comment blocks are variable size. + */ + byte[] readCommentExtension() { + try { + byte[] comment = new byte[0]; + byte[] block = new byte[255]; + int size = inputStream.read(); + while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { byte[] oldComment = comment; comment = new byte[oldComment.length + size]; System.arraycopy(oldComment, 0, comment, 0, oldComment.length); System.arraycopy(block, 0, comment, oldComment.length, size); //comment ~= block[ 0 .. size ]; - size = inputStream.read(); - } - return comment; - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } + size = inputStream.read(); + } + return comment; + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } - /** - * We have just read the PlainText extension identifier - * from the input stream. Read in the plain text info and text, - * and return the text. GIF plain text blocks are variable size. - */ - byte[] readPlainTextExtension() { - try { - // Read size of block = 0x0C. - inputStream.read(); - // Read the text information (x, y, width, height, colors). - byte[] info = new byte[12]; - inputStream.read(info); - // Read the text. - byte[] text = new byte[0]; - byte[] block = new byte[255]; - int size = inputStream.read(); - while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { + /** + * We have just read the PlainText extension identifier + * from the input stream. Read in the plain text info and text, + * and return the text. GIF plain text blocks are variable size. + */ + byte[] readPlainTextExtension() { + try { + // Read size of block = 0x0C. + inputStream.read(); + // Read the text information (x, y, width, height, colors). + byte[] info = new byte[12]; + inputStream.read(info); + // Read the text. + byte[] text = new byte[0]; + byte[] block = new byte[255]; + int size = inputStream.read(); + while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { byte[] oldText = text; text = new byte[oldText.length + size]; System.arraycopy(oldText, 0, text, 0, oldText.length); System.arraycopy(block, 0, text, oldText.length, size); //text ~= block[ 0 .. size ]; - size = inputStream.read(); - } - return text; - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } + size = inputStream.read(); + } + return text; + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } - /** - * We have just read the GraphicsControl extension identifier - * from the input stream. Read in the control information, store - * it, and return it. - */ - byte[] readGraphicsControlExtension() { - try { - // Read size of block = 0x04. - inputStream.read(); - // Read the control block. - byte[] controlBlock = new byte[4]; - inputStream.read(controlBlock); - byte bitField = controlBlock[0]; - // Store the user input field. - //userInput = (bitField & 0x02) != 0; - // Store the disposal method. - disposalMethod = (bitField >> 2) & 0x07; - // Store the delay time. - delayTime = (controlBlock[1] & 0xFF) | ((controlBlock[2] & 0xFF) << 8); - // Store the transparent color. - if ((bitField & 0x01) != 0) { - transparentPixel = controlBlock[3] & 0xFF; - } else { - transparentPixel = -1; - } - // Read block terminator. - inputStream.read(); - return controlBlock; - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } + /** + * We have just read the GraphicsControl extension identifier + * from the input stream. Read in the control information, store + * it, and return it. + */ + byte[] readGraphicsControlExtension() { + try { + // Read size of block = 0x04. + inputStream.read(); + // Read the control block. + byte[] controlBlock = new byte[4]; + inputStream.read(controlBlock); + byte bitField = controlBlock[0]; + // Store the user input field. + //userInput = (bitField & 0x02) != 0; + // Store the disposal method. + disposalMethod = (bitField >> 2) & 0x07; + // Store the delay time. + delayTime = (controlBlock[1] & 0xFF) | ((controlBlock[2] & 0xFF) << 8); + // Store the transparent color. + if ((bitField & 0x01) != 0) { + transparentPixel = controlBlock[3] & 0xFF; + } else { + transparentPixel = -1; + } + // Read block terminator. + inputStream.read(); + return controlBlock; + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } - /** - * We have just read the Application extension identifier - * from the input stream. Read in the rest of the extension, - * look for and store 'number of repeats', and return the data. - */ - byte[] readApplicationExtension() { - try { - // Read size of block = 0x0B. - inputStream.read(); - // Read application identifier. - byte[] applicationBytes = new byte[8]; - inputStream.read(applicationBytes); - char[] application = cast(char[])(applicationBytes.dup); - // Read authentication code. - byte[] authenticationBytes = new byte[3]; - inputStream.read(authenticationBytes); - char[] authentication = cast(char[])(authenticationBytes.dup); - // Read application data. - byte[] data = new byte[0]; - byte[] block = new byte[255]; - int size = inputStream.read(); - while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { + /** + * We have just read the Application extension identifier + * from the input stream. Read in the rest of the extension, + * look for and store 'number of repeats', and return the data. + */ + byte[] readApplicationExtension() { + try { + // Read size of block = 0x0B. + inputStream.read(); + // Read application identifier. + byte[] applicationBytes = new byte[8]; + inputStream.read(applicationBytes); + char[] application = cast(char[])(applicationBytes.dup); + // Read authentication code. + byte[] authenticationBytes = new byte[3]; + inputStream.read(authenticationBytes); + char[] authentication = cast(char[])(authenticationBytes.dup); + // Read application data. + byte[] data = new byte[0]; + byte[] block = new byte[255]; + int size = inputStream.read(); + while ((size > 0) && (inputStream.read(block, 0, size) != -1)) { byte[] oldData = data; data = new byte[oldData.length + size]; System.arraycopy(oldData, 0, data, 0, oldData.length); System.arraycopy(block, 0, data, oldData.length, size); //data ~= block[ 0 .. size ]; - size = inputStream.read(); - } - // Look for the NETSCAPE 'repeat count' field for an animated GIF. - if (application=="NETSCAPE" && authentication=="2.0" && data[0] == 01) { //$NON-NLS-1$ //$NON-NLS-2$ - repeatCount = (data[1] & 0xFF) | ((data[2] & 0xFF) << 8); - loader.repeatCount = repeatCount; - } - return data; - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } + size = inputStream.read(); + } + // Look for the NETSCAPE 'repeat count' field for an animated GIF. + if (application=="NETSCAPE" && authentication=="2.0" && data[0] == 01) { //$NON-NLS-1$ //$NON-NLS-2$ + repeatCount = (data[1] & 0xFF) | ((data[2] & 0xFF) << 8); + loader.repeatCount = repeatCount; + } + return data; + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } - /** - * Return a DeviceIndependentImage representing the - * image block at the current position in the input stream. - * Throw an error if an error occurs. - */ - ImageData readImageBlock(PaletteData defaultPalette) { - int depth; - PaletteData palette; - byte[] block = new byte[9]; - try { - inputStream.read(block); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - int left = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8); - int top = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8); - int width = (block[4] & 0xFF) | ((block[5] & 0xFF) << 8); - int height = (block[6] & 0xFF) | ((block[7] & 0xFF) << 8); - byte bitField = block[8]; - bool interlaced = (bitField & 0x40) != 0; - //bool sorted = (bitField & 0x20) != 0; - if ((bitField & 0x80) != 0) { - // Local palette. - depth = (bitField & 0x7) + 1; - palette = readPalette(1 << depth); - } else { - // No local palette. - depth = defaultDepth; - palette = defaultPalette; - } - /* Work around: Ignore the case where a GIF specifies an - * invalid index for the transparent pixel that is larger - * than the number of entries in the palette. */ - if (transparentPixel > 1 << depth) { - transparentPixel = -1; - } - // Promote depth to next highest supported value. - if (!(depth == 1 || depth == 4 || depth == 8)) { - if (depth < 4) - depth = 4; - else - depth = 8; - } - if (palette == null) { - palette = grayRamp(1 << depth); - } - int initialCodeSize = -1; - try { - initialCodeSize = inputStream.read(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if (initialCodeSize < 0) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - ImageData image = ImageData.internal_new( - width, - height, - depth, - palette, - 4, - null, - 0, - null, - null, - -1, - transparentPixel, - SWT.IMAGE_GIF, - left, - top, - disposalMethod, - delayTime); - LZWCodec codec = new LZWCodec(); - codec.decode(inputStream, loader, image, interlaced, initialCodeSize); - return image; - } + /** + * Return a DeviceIndependentImage representing the + * image block at the current position in the input stream. + * Throw an error if an error occurs. + */ + ImageData readImageBlock(PaletteData defaultPalette) { + int depth; + PaletteData palette; + byte[] block = new byte[9]; + try { + inputStream.read(block); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + int left = (block[0] & 0xFF) | ((block[1] & 0xFF) << 8); + int top = (block[2] & 0xFF) | ((block[3] & 0xFF) << 8); + int width = (block[4] & 0xFF) | ((block[5] & 0xFF) << 8); + int height = (block[6] & 0xFF) | ((block[7] & 0xFF) << 8); + byte bitField = block[8]; + bool interlaced = (bitField & 0x40) != 0; + //bool sorted = (bitField & 0x20) != 0; + if ((bitField & 0x80) != 0) { + // Local palette. + depth = (bitField & 0x7) + 1; + palette = readPalette(1 << depth); + } else { + // No local palette. + depth = defaultDepth; + palette = defaultPalette; + } + /* Work around: Ignore the case where a GIF specifies an + * invalid index for the transparent pixel that is larger + * than the number of entries in the palette. */ + if (transparentPixel > 1 << depth) { + transparentPixel = -1; + } + // Promote depth to next highest supported value. + if (!(depth == 1 || depth == 4 || depth == 8)) { + if (depth < 4) + depth = 4; + else + depth = 8; + } + if (palette == null) { + palette = grayRamp(1 << depth); + } + int initialCodeSize = -1; + try { + initialCodeSize = inputStream.read(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if (initialCodeSize < 0) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + ImageData image = ImageData.internal_new( + width, + height, + depth, + palette, + 4, + null, + 0, + null, + null, + -1, + transparentPixel, + SWT.IMAGE_GIF, + left, + top, + disposalMethod, + delayTime); + LZWCodec codec = new LZWCodec(); + codec.decode(inputStream, loader, image, interlaced, initialCodeSize); + return image; + } - /** - * Read a palette from the input stream. - */ - PaletteData readPalette(int numColors) { - byte[] bytes = new byte[numColors * 3]; - try { - if (inputStream.read(bytes) != bytes.length) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - RGB[] colors = new RGB[numColors]; - for (int i = 0; i < numColors; i++) - colors[i] = new RGB(bytes[i*3] & 0xFF, - bytes[i*3+1] & 0xFF, bytes[i*3+2] & 0xFF); - return new PaletteData(colors); - } + /** + * Read a palette from the input stream. + */ + PaletteData readPalette(int numColors) { + byte[] bytes = new byte[numColors * 3]; + try { + if (inputStream.read(bytes) != bytes.length) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + RGB[] colors = new RGB[numColors]; + for (int i = 0; i < numColors; i++) + colors[i] = new RGB(bytes[i*3] & 0xFF, + bytes[i*3+1] & 0xFF, bytes[i*3+2] & 0xFF); + return new PaletteData(colors); + } - void unloadIntoByteStream(ImageLoader loader) { + void unloadIntoByteStream(ImageLoader loader) { - /* Step 1: Acquire GIF parameters. */ - ImageData[] data = loader.data; - int frameCount = data.length; - bool multi = frameCount > 1; - ImageData firstImage = data[0]; - int logicalScreenWidth = multi ? loader.logicalScreenWidth : firstImage.width; - int logicalScreenHeight = multi ? loader.logicalScreenHeight : firstImage.height; - int backgroundPixel = loader.backgroundPixel; - int depth = firstImage.depth; - PaletteData palette = firstImage.palette; - RGB[] colors = palette.getRGBs(); - short globalTable = 1; + /* Step 1: Acquire GIF parameters. */ + ImageData[] data = loader.data; + int frameCount = data.length; + bool multi = frameCount > 1; + ImageData firstImage = data[0]; + int logicalScreenWidth = multi ? loader.logicalScreenWidth : firstImage.width; + int logicalScreenHeight = multi ? loader.logicalScreenHeight : firstImage.height; + int backgroundPixel = loader.backgroundPixel; + int depth = firstImage.depth; + PaletteData palette = firstImage.palette; + RGB[] colors = palette.getRGBs(); + short globalTable = 1; - /* Step 2: Check for validity and global/local color map. */ - if (!(depth == 1 || depth == 4 || depth == 8)) { - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - } - for (int i=0; i> 8) & 0xFF); - block[2] = cast(byte)(y & 0xFF); - block[3] = cast(byte)((y >> 8) & 0xFF); - block[4] = cast(byte)(width & 0xFF); - block[5] = cast(byte)((width >> 8) & 0xFF); - block[6] = cast(byte)(height & 0xFF); - block[7] = cast(byte)((height >> 8) & 0xFF); - block[8] = cast(byte)(globalTable == 0 ? (depth-1) | 0x80 : 0x00); - outputStream.write(block); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + /* Step 7: Write Image Header for each frame. */ + int x = data[frame].x; + int y = data[frame].y; + int width = data[frame].width; + int height = data[frame].height; + try { + outputStream.write(GIF_IMAGE_BLOCK_ID); + byte[] block = new byte[9]; + block[0] = cast(byte)(x & 0xFF); + block[1] = cast(byte)((x >> 8) & 0xFF); + block[2] = cast(byte)(y & 0xFF); + block[3] = cast(byte)((y >> 8) & 0xFF); + block[4] = cast(byte)(width & 0xFF); + block[5] = cast(byte)((width >> 8) & 0xFF); + block[6] = cast(byte)(height & 0xFF); + block[7] = cast(byte)((height >> 8) & 0xFF); + block[8] = cast(byte)(globalTable == 0 ? (depth-1) | 0x80 : 0x00); + outputStream.write(block); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } - /* Step 8: Write Local Color Table for each frame if applicable. */ - if (globalTable == 0) { - writePalette(data[frame].palette, depth); - } + /* Step 8: Write Local Color Table for each frame if applicable. */ + if (globalTable == 0) { + writePalette(data[frame].palette, depth); + } - /* Step 9: Write the actual data for each frame. */ - try { - outputStream.write(depth); // Minimum LZW Code size - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - (new LZWCodec()).encode(outputStream, data[frame]); - } + /* Step 9: Write the actual data for each frame. */ + try { + outputStream.write(depth); // Minimum LZW Code size + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + (new LZWCodec()).encode(outputStream, data[frame]); + } - /* Step 10: Write GIF terminator. */ - try { - outputStream.write(0x3B); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + /* Step 10: Write GIF terminator. */ + try { + outputStream.write(0x3B); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - /** - * Write out a GraphicsControlBlock to describe - * the specified device independent image. - */ - void writeGraphicsControlBlock(ImageData image) { - try { - outputStream.write(GIF_EXTENSION_BLOCK_ID); - outputStream.write(GIF_GRAPHICS_CONTROL_BLOCK_ID); - byte[] gcBlock = new byte[4]; - gcBlock[0] = 0; - gcBlock[1] = 0; - gcBlock[2] = 0; - gcBlock[3] = 0; - if (image.transparentPixel != -1) { - gcBlock[0] = cast(byte)0x01; - gcBlock[3] = cast(byte)image.transparentPixel; - } - if (image.disposalMethod != 0) { - gcBlock[0] |= cast(byte)((image.disposalMethod & 0x07) << 2); - } - if (image.delayTime != 0) { - gcBlock[1] = cast(byte)(image.delayTime & 0xFF); - gcBlock[2] = cast(byte)((image.delayTime >> 8) & 0xFF); - } - outputStream.write(cast(byte)gcBlock.length); - outputStream.write(gcBlock); - outputStream.write(0); // Block terminator - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + /** + * Write out a GraphicsControlBlock to describe + * the specified device independent image. + */ + void writeGraphicsControlBlock(ImageData image) { + try { + outputStream.write(GIF_EXTENSION_BLOCK_ID); + outputStream.write(GIF_GRAPHICS_CONTROL_BLOCK_ID); + byte[] gcBlock = new byte[4]; + gcBlock[0] = 0; + gcBlock[1] = 0; + gcBlock[2] = 0; + gcBlock[3] = 0; + if (image.transparentPixel != -1) { + gcBlock[0] = cast(byte)0x01; + gcBlock[3] = cast(byte)image.transparentPixel; + } + if (image.disposalMethod != 0) { + gcBlock[0] |= cast(byte)((image.disposalMethod & 0x07) << 2); + } + if (image.delayTime != 0) { + gcBlock[1] = cast(byte)(image.delayTime & 0xFF); + gcBlock[2] = cast(byte)((image.delayTime >> 8) & 0xFF); + } + outputStream.write(cast(byte)gcBlock.length); + outputStream.write(gcBlock); + outputStream.write(0); // Block terminator + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - /** - * Write the specified palette to the output stream. - */ - void writePalette(PaletteData palette, int depth) { - byte[] bytes = new byte[(1 << depth) * 3]; - int offset = 0; - for (int i = 0; i < palette.colors.length; i++) { - RGB color = palette.colors[i]; - bytes[offset] = cast(byte)color.red; - bytes[offset + 1] = cast(byte)color.green; - bytes[offset + 2] = cast(byte)color.blue; - offset += 3; - } - try { - outputStream.write(bytes); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + /** + * Write the specified palette to the output stream. + */ + void writePalette(PaletteData palette, int depth) { + byte[] bytes = new byte[(1 << depth) * 3]; + int offset = 0; + for (int i = 0; i < palette.colors.length; i++) { + RGB color = palette.colors[i]; + bytes[offset] = cast(byte)color.red; + bytes[offset + 1] = cast(byte)color.green; + bytes[offset + 2] = cast(byte)color.blue; + offset += 3; + } + try { + outputStream.write(bytes); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGAppn.d --- a/dwt/internal/image/JPEGAppn.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGAppn.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,16 +16,16 @@ final class JPEGAppn : JPEGVariableSizeSegment { - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - super(byteStream); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + } - public bool verify() { - int marker = getSegmentMarker(); - return marker >= JPEGFileFormat.APP0 && marker <= JPEGFileFormat.APP15; - } + public bool verify() { + int marker = getSegmentMarker(); + return marker >= JPEGFileFormat.APP0 && marker <= JPEGFileFormat.APP15; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGArithmeticConditioningTable.d --- a/dwt/internal/image/JPEGArithmeticConditioningTable.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGArithmeticConditioningTable.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,11 +16,11 @@ final class JPEGArithmeticConditioningTable : JPEGVariableSizeSegment { - public this(LEDataInputStream byteStream) { - super(byteStream); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + } - public int signature() { - return JPEGFileFormat.DAC; - } + public int signature() { + return JPEGFileFormat.DAC; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGComment.d --- a/dwt/internal/image/JPEGComment.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGComment.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,15 +16,15 @@ final class JPEGComment : JPEGVariableSizeSegment { - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - super(byteStream); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + } - public int signature() { - return JPEGFileFormat.COM; - } + public int signature() { + return JPEGFileFormat.COM; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGDecoder.d --- a/dwt/internal/image/JPEGDecoder.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGDecoder.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -25,2695 +25,2695 @@ public class JPEGDecoder { - static const int DCTSIZE = 8; - static const int DCTSIZE2 = 64; - static const int NUM_QUANT_TBLS = 4; - static const int NUM_HUFF_TBLS = 4; - static const int NUM_ARITH_TBLS = 16; - static const int MAX_COMPS_IN_SCAN = 4; - static const int MAX_COMPONENTS = 10; - static const int MAX_SAMP_FACTOR = 4; - static const int D_MAX_BLOCKS_IN_MCU = 10; - static const int HUFF_LOOKAHEAD = 8; - static const int MAX_Q_COMPS = 4; - static const int IFAST_SCALE_BITS = 2; - static const int MAXJSAMPLE = 255; - static const int CENTERJSAMPLE = 128; - static const int MIN_GET_BITS = 32-7; - static const int INPUT_BUFFER_SIZE = 4096; - - static const int SCALEBITS = 16; /* speediest right-shift on some machines */ - static const int ONE_HALF = 1 << (SCALEBITS-1); - - static const int RGB_RED = 2; /* Offset of Red in an RGB scanline element */ - static const int RGB_GREEN = 1; /* Offset of Green */ - static const int RGB_BLUE = 0; /* Offset of Blue */ - static const int RGB_PIXELSIZE = 3; - - static const int JBUF_PASS_THRU = 0; - static const int JBUF_SAVE_SOURCE = 1; /* Run source subobject only, save output */ - static const int JBUF_CRANK_DEST = 2; /* Run dest subobject only, using saved data */ - static const int JBUF_SAVE_AND_PASS = 3; - - static const int JPEG_MAX_DIMENSION = 65500; - static const int BITS_IN_JSAMPLE = 8; - - static const int JDITHER_NONE = 0; /* no dithering */ - static const int JDITHER_ORDERED = 1; /* simple ordered dither */ - static const int JDITHER_FS = 2; - - static const int JDCT_ISLOW = 0; /* slow but accurate integer algorithm */ - static const int JDCT_IFAST = 1; /* faster, less accurate integer method */ - static const int JDCT_FLOAT = 2; /* floating-point: accurate, fast on fast HW */ - static const int JDCT_DEFAULT = JDCT_ISLOW; - - static const int JCS_UNKNOWN = 0; /* error/unspecified */ - static const int JCS_GRAYSCALE = 1; /* monochrome */ - static const int JCS_RGB = 2; /* red/green/blue */ - static const int JCS_YCbCr = 3; /* Y/Cb/Cr (also known as YUV) */ - static const int JCS_CMYK = 4; /* C/M/Y/K */ - static const int JCS_YCCK = 5; /* Y/Cb/Cr/K */ - - static const int SAVED_COEFS = 6; - static const int Q01_POS = 1; - static const int Q10_POS = 8; - static const int Q20_POS = 16; - static const int Q11_POS = 9; - static const int Q02_POS = 2; - - static const int CTX_PREPARE_FOR_IMCU = 0; /* need to prepare for MCU row */ - static const int CTX_PROCESS_IMCU = 1; /* feeding iMCU to postprocessor */ - static const int CTX_POSTPONED_ROW = 2; /* feeding postponed row group */ - - static const int APP0_DATA_LEN = 14; /* Length of interesting data in APP0 */ - static const int APP14_DATA_LEN = 12; /* Length of interesting data in APP14 */ - static const int APPN_DATA_LEN = 14; /* Must be the largest of the above!! */ - - /* markers */ - static const int M_SOF0 = 0xc0; - static const int M_SOF1 = 0xc1; - static const int M_SOF2 = 0xc2; - static const int M_SOF3 = 0xc3; - static const int M_SOF5 = 0xc5; - static const int M_SOF6 = 0xc6; - static const int M_SOF7 = 0xc7; - static const int M_JPG = 0xc8; - static const int M_SOF9 = 0xc9; - static const int M_SOF10 = 0xca; - static const int M_SOF11 = 0xcb; - static const int M_SOF13 = 0xcd; - static const int M_SOF14 = 0xce; - static const int M_SOF15 = 0xcf; - static const int M_DHT = 0xc4; - static const int M_DAC = 0xcc; - static const int M_RST0 = 0xd0; - static const int M_RST1 = 0xd1; - static const int M_RST2 = 0xd2; - static const int M_RST3 = 0xd3; - static const int M_RST4 = 0xd4; - static const int M_RST5 = 0xd5; - static const int M_RST6 = 0xd6; - static const int M_RST7 = 0xd7; - static const int M_SOI = 0xd8; - static const int M_EOI = 0xd9; - static const int M_SOS = 0xda; - static const int M_DQT = 0xdb; - static const int M_DNL = 0xdc; - static const int M_DRI = 0xdd; - static const int M_DHP = 0xde; - static const int M_EXP = 0xdf; - static const int M_APP0 = 0xe0; - static const int M_APP1 = 0xe1; - static const int M_APP2 = 0xe2; - static const int M_APP3 = 0xe3; - static const int M_APP4 = 0xe4; - static const int M_APP5 = 0xe5; - static const int M_APP6 = 0xe6; - static const int M_APP7 = 0xe7; - static const int M_APP8 = 0xe8; - static const int M_APP9 = 0xe9; - static const int M_APP10 = 0xea; - static const int M_APP11 = 0xeb; - static const int M_APP12 = 0xec; - static const int M_APP13 = 0xed; - static const int M_APP14 = 0xee; - static const int M_APP15 = 0xef; - static const int M_JPG0 = 0xf0; - static const int M_JPG13 = 0xfd; - static const int M_COM = 0xfe; - static const int M_TEM = 0x01; - static const int M_ERROR = 0x100; - - /* Values of global_state field (jdapi.c has some dependencies on ordering!) */ - static const int CSTATE_START = 100; /* after create_compress */ - static const int CSTATE_SCANNING = 101; /* start_compress done, write_scanlines OK */ - static const int CSTATE_RAW_OK = 102; /* start_compress done, write_raw_data OK */ - static const int CSTATE_WRCOEFS = 103; /* jpeg_write_coefficients done */ - static const int DSTATE_START = 200; /* after create_decompress */ - static const int DSTATE_INHEADER = 201; /* reading header markers, no SOS yet */ - static const int DSTATE_READY = 202; /* found SOS, ready for start_decompress */ - static const int DSTATE_PRELOAD = 203; /* reading multiscan file in start_decompress*/ - static const int DSTATE_PRESCAN = 204; /* performing dummy pass for 2-pass quant */ - static const int DSTATE_SCANNING = 205; /* start_decompress done, read_scanlines OK */ - static const int DSTATE_RAW_OK = 206; /* start_decompress done, read_raw_data OK */ - static const int DSTATE_BUFIMAGE = 207; /* expecting jpeg_start_output */ - static const int DSTATE_BUFPOST = 208; /* looking for SOS/EOI in jpeg_finish_output */ - static const int DSTATE_RDCOEFS = 209; /* reading file in jpeg_read_coefficients */ - static const int DSTATE_STOPPING = 210; /* looking for EOI in jpeg_finish_decompress */ - - static const int JPEG_REACHED_SOS = 1; /* Reached start of new scan */ - static const int JPEG_REACHED_EOI = 2; /* Reached end of image */ - static const int JPEG_ROW_COMPLETED = 3; /* Completed one iMCU row */ - static const int JPEG_SCAN_COMPLETED = 4; /* Completed last iMCU row of a scan */ - - static const int JPEG_SUSPENDED = 0; /* Suspended due to lack of input data */ - static const int JPEG_HEADER_OK = 1; /* Found valid image datastream */ - static const int JPEG_HEADER_TABLES_ONLY = 2; /* Found valid table-specs-only datastream */ - - /* Function pointers */ - static const int DECOMPRESS_DATA = 0; - static const int DECOMPRESS_SMOOTH_DATA = 1; - static const int DECOMPRESS_ONEPASS = 2; - - static const int CONSUME_DATA = 0; - static const int DUMMY_CONSUME_DATA = 1; - - static const int PROCESS_DATA_SIMPLE_MAIN = 0; - static const int PROCESS_DATA_CONTEXT_MAIN = 1; - static const int PROCESS_DATA_CRANK_POST = 2; - - static const int POST_PROCESS_1PASS = 0; - static const int POST_PROCESS_DATA_UPSAMPLE = 1; - - static const int NULL_CONVERT = 0; - static const int GRAYSCALE_CONVERT = 1; - static const int YCC_RGB_CONVERT = 2; - static const int GRAY_RGB_CONVERT = 3; - static const int YCCK_CMYK_CONVERT = 4; - - static const int NOOP_UPSAMPLE = 0; - static const int FULLSIZE_UPSAMPLE = 1; - static const int H2V1_FANCY_UPSAMPLE = 2; - static const int H2V1_UPSAMPLE = 3; - static const int H2V2_FANCY_UPSAMPLE = 4; - static const int H2V2_UPSAMPLE = 5; - static const int INT_UPSAMPLE = 6; - - static const int INPUT_CONSUME_INPUT = 0; - static const int COEF_CONSUME_INPUT = 1; - - static int extend_test[] = /* entry n is 2**(n-1) */ - [ - 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, - 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 - ]; - - static int extend_offset[] = /* entry n is (-1 << n) + 1 */ - [ - 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1, - ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1, - ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1, - ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 - ]; - - static int jpeg_natural_order[] = [ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63, - 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ - 63, 63, 63, 63, 63, 63, 63, 63 - ]; - - static final class JQUANT_TBL { - /* This array gives the coefficient quantizers in natural array order - * (not the zigzag order in which they are stored in a JPEG DQT marker). - * CAUTION: IJG versions prior to v6a kept this array in zigzag order. - */ - short[DCTSIZE2] quantval;// = new short[DCTSIZE2]; /* quantization step for each coefficient */ - /* This field is used only during compression. It's initialized false when - * the table is created, and set true when it's been output to the file. - * You could suppress output of a table by setting this to true. - * (See jpeg_suppress_tables for an example.) - */ - bool sent_table; /* true when table has been output */ - } - - static final class JHUFF_TBL { - /* These two fields directly represent the contents of a JPEG DHT marker */ - byte[17] bits;// = new byte[17]; /* bits[k] = # of symbols with codes of */ - /* length k bits; bits[0] is unused */ - byte[256] huffval;// = new byte[256]; /* The symbols, in order of incr code length */ - /* This field is used only during compression. It's initialized false when - * the table is created, and set true when it's been output to the file. - * You could suppress output of a table by setting this to true. - * (See jpeg_suppress_tables for an example.) - */ - bool sent_table; /* true when table has been output */ - } - - static final class bitread_perm_state { /* Bitreading state saved across MCUs */ - int get_buffer; /* current bit-extraction buffer */ - int bits_left; /* # of unused bits in it */ - } - - static final class bitread_working_state { /* Bitreading working state within an MCU */ - /* Current data source location */ - /* We need a copy, rather than munging the original, in case of suspension */ - byte[] buffer; /* => next byte to read from source */ - int bytes_offset; - int bytes_in_buffer; /* # of bytes remaining in source buffer */ - /* Bit input buffer --- note these values are kept in register variables, - * not in this struct, inside the inner loops. - */ - int get_buffer; /* current bit-extraction buffer */ - int bits_left; /* # of unused bits in it */ - /* Pointer needed by jpeg_fill_bit_buffer. */ - jpeg_decompress_struct cinfo; /* back link to decompress master record */ - } - - static final class savable_state { - int EOBRUN; //Note that this is only used in the progressive case - int[MAX_COMPS_IN_SCAN] last_dc_val;// = new int[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ - } - - static final class d_derived_tbl { - /* Basic tables: (element [0] of each array is unused) */ - int[18] maxcode;// = new int[18]; /* largest code of length k (-1 if none) */ - /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */ - int[17] valoffset;// = new int[17]; /* huffval[] offset for codes of length k */ - /* valoffset[k] = huffval[] index of 1st symbol of code length k, less - * the smallest code of length k; so given a code of length k, the - * corresponding symbol is huffval[code + valoffset[k]] - */ - - /* Link to public Huffman table (needed only in jpeg_huff_decode) */ - JHUFF_TBL pub; - - /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of - * the input data stream. If the next Huffman code is no more - * than HUFF_LOOKAHEAD bits long, we can obtain its length and - * the corresponding symbol directly from these tables. - */ - int[1< 1) { - coef.MCU_rows_per_iMCU_row = 1; - } else { - if (cinfo.input_iMCU_row < (cinfo.total_iMCU_rows-1)) - coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].v_samp_factor; - else - coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].last_row_height; - } - - coef.MCU_ctr = 0; - coef.MCU_vert_offset = 0; - } - - } - - static abstract class jpeg_entropy_decoder { - abstract void start_pass (jpeg_decompress_struct cinfo); - abstract bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data); - - /* This is here to share code between baseline and progressive decoders; */ - /* other modules probably should not use it */ - bool insufficient_data; /* set true after emitting warning */ - - bitread_working_state br_state_local; - savable_state state_local; + static const int DCTSIZE = 8; + static const int DCTSIZE2 = 64; + static const int NUM_QUANT_TBLS = 4; + static const int NUM_HUFF_TBLS = 4; + static const int NUM_ARITH_TBLS = 16; + static const int MAX_COMPS_IN_SCAN = 4; + static const int MAX_COMPONENTS = 10; + static const int MAX_SAMP_FACTOR = 4; + static const int D_MAX_BLOCKS_IN_MCU = 10; + static const int HUFF_LOOKAHEAD = 8; + static const int MAX_Q_COMPS = 4; + static const int IFAST_SCALE_BITS = 2; + static const int MAXJSAMPLE = 255; + static const int CENTERJSAMPLE = 128; + static const int MIN_GET_BITS = 32-7; + static const int INPUT_BUFFER_SIZE = 4096; + + static const int SCALEBITS = 16; /* speediest right-shift on some machines */ + static const int ONE_HALF = 1 << (SCALEBITS-1); + + static const int RGB_RED = 2; /* Offset of Red in an RGB scanline element */ + static const int RGB_GREEN = 1; /* Offset of Green */ + static const int RGB_BLUE = 0; /* Offset of Blue */ + static const int RGB_PIXELSIZE = 3; + + static const int JBUF_PASS_THRU = 0; + static const int JBUF_SAVE_SOURCE = 1; /* Run source subobject only, save output */ + static const int JBUF_CRANK_DEST = 2; /* Run dest subobject only, using saved data */ + static const int JBUF_SAVE_AND_PASS = 3; + + static const int JPEG_MAX_DIMENSION = 65500; + static const int BITS_IN_JSAMPLE = 8; + + static const int JDITHER_NONE = 0; /* no dithering */ + static const int JDITHER_ORDERED = 1; /* simple ordered dither */ + static const int JDITHER_FS = 2; + + static const int JDCT_ISLOW = 0; /* slow but accurate integer algorithm */ + static const int JDCT_IFAST = 1; /* faster, less accurate integer method */ + static const int JDCT_FLOAT = 2; /* floating-point: accurate, fast on fast HW */ + static const int JDCT_DEFAULT = JDCT_ISLOW; + + static const int JCS_UNKNOWN = 0; /* error/unspecified */ + static const int JCS_GRAYSCALE = 1; /* monochrome */ + static const int JCS_RGB = 2; /* red/green/blue */ + static const int JCS_YCbCr = 3; /* Y/Cb/Cr (also known as YUV) */ + static const int JCS_CMYK = 4; /* C/M/Y/K */ + static const int JCS_YCCK = 5; /* Y/Cb/Cr/K */ + + static const int SAVED_COEFS = 6; + static const int Q01_POS = 1; + static const int Q10_POS = 8; + static const int Q20_POS = 16; + static const int Q11_POS = 9; + static const int Q02_POS = 2; + + static const int CTX_PREPARE_FOR_IMCU = 0; /* need to prepare for MCU row */ + static const int CTX_PROCESS_IMCU = 1; /* feeding iMCU to postprocessor */ + static const int CTX_POSTPONED_ROW = 2; /* feeding postponed row group */ + + static const int APP0_DATA_LEN = 14; /* Length of interesting data in APP0 */ + static const int APP14_DATA_LEN = 12; /* Length of interesting data in APP14 */ + static const int APPN_DATA_LEN = 14; /* Must be the largest of the above!! */ + + /* markers */ + static const int M_SOF0 = 0xc0; + static const int M_SOF1 = 0xc1; + static const int M_SOF2 = 0xc2; + static const int M_SOF3 = 0xc3; + static const int M_SOF5 = 0xc5; + static const int M_SOF6 = 0xc6; + static const int M_SOF7 = 0xc7; + static const int M_JPG = 0xc8; + static const int M_SOF9 = 0xc9; + static const int M_SOF10 = 0xca; + static const int M_SOF11 = 0xcb; + static const int M_SOF13 = 0xcd; + static const int M_SOF14 = 0xce; + static const int M_SOF15 = 0xcf; + static const int M_DHT = 0xc4; + static const int M_DAC = 0xcc; + static const int M_RST0 = 0xd0; + static const int M_RST1 = 0xd1; + static const int M_RST2 = 0xd2; + static const int M_RST3 = 0xd3; + static const int M_RST4 = 0xd4; + static const int M_RST5 = 0xd5; + static const int M_RST6 = 0xd6; + static const int M_RST7 = 0xd7; + static const int M_SOI = 0xd8; + static const int M_EOI = 0xd9; + static const int M_SOS = 0xda; + static const int M_DQT = 0xdb; + static const int M_DNL = 0xdc; + static const int M_DRI = 0xdd; + static const int M_DHP = 0xde; + static const int M_EXP = 0xdf; + static const int M_APP0 = 0xe0; + static const int M_APP1 = 0xe1; + static const int M_APP2 = 0xe2; + static const int M_APP3 = 0xe3; + static const int M_APP4 = 0xe4; + static const int M_APP5 = 0xe5; + static const int M_APP6 = 0xe6; + static const int M_APP7 = 0xe7; + static const int M_APP8 = 0xe8; + static const int M_APP9 = 0xe9; + static const int M_APP10 = 0xea; + static const int M_APP11 = 0xeb; + static const int M_APP12 = 0xec; + static const int M_APP13 = 0xed; + static const int M_APP14 = 0xee; + static const int M_APP15 = 0xef; + static const int M_JPG0 = 0xf0; + static const int M_JPG13 = 0xfd; + static const int M_COM = 0xfe; + static const int M_TEM = 0x01; + static const int M_ERROR = 0x100; + + /* Values of global_state field (jdapi.c has some dependencies on ordering!) */ + static const int CSTATE_START = 100; /* after create_compress */ + static const int CSTATE_SCANNING = 101; /* start_compress done, write_scanlines OK */ + static const int CSTATE_RAW_OK = 102; /* start_compress done, write_raw_data OK */ + static const int CSTATE_WRCOEFS = 103; /* jpeg_write_coefficients done */ + static const int DSTATE_START = 200; /* after create_decompress */ + static const int DSTATE_INHEADER = 201; /* reading header markers, no SOS yet */ + static const int DSTATE_READY = 202; /* found SOS, ready for start_decompress */ + static const int DSTATE_PRELOAD = 203; /* reading multiscan file in start_decompress*/ + static const int DSTATE_PRESCAN = 204; /* performing dummy pass for 2-pass quant */ + static const int DSTATE_SCANNING = 205; /* start_decompress done, read_scanlines OK */ + static const int DSTATE_RAW_OK = 206; /* start_decompress done, read_raw_data OK */ + static const int DSTATE_BUFIMAGE = 207; /* expecting jpeg_start_output */ + static const int DSTATE_BUFPOST = 208; /* looking for SOS/EOI in jpeg_finish_output */ + static const int DSTATE_RDCOEFS = 209; /* reading file in jpeg_read_coefficients */ + static const int DSTATE_STOPPING = 210; /* looking for EOI in jpeg_finish_decompress */ + + static const int JPEG_REACHED_SOS = 1; /* Reached start of new scan */ + static const int JPEG_REACHED_EOI = 2; /* Reached end of image */ + static const int JPEG_ROW_COMPLETED = 3; /* Completed one iMCU row */ + static const int JPEG_SCAN_COMPLETED = 4; /* Completed last iMCU row of a scan */ + + static const int JPEG_SUSPENDED = 0; /* Suspended due to lack of input data */ + static const int JPEG_HEADER_OK = 1; /* Found valid image datastream */ + static const int JPEG_HEADER_TABLES_ONLY = 2; /* Found valid table-specs-only datastream */ + + /* Function pointers */ + static const int DECOMPRESS_DATA = 0; + static const int DECOMPRESS_SMOOTH_DATA = 1; + static const int DECOMPRESS_ONEPASS = 2; + + static const int CONSUME_DATA = 0; + static const int DUMMY_CONSUME_DATA = 1; + + static const int PROCESS_DATA_SIMPLE_MAIN = 0; + static const int PROCESS_DATA_CONTEXT_MAIN = 1; + static const int PROCESS_DATA_CRANK_POST = 2; + + static const int POST_PROCESS_1PASS = 0; + static const int POST_PROCESS_DATA_UPSAMPLE = 1; + + static const int NULL_CONVERT = 0; + static const int GRAYSCALE_CONVERT = 1; + static const int YCC_RGB_CONVERT = 2; + static const int GRAY_RGB_CONVERT = 3; + static const int YCCK_CMYK_CONVERT = 4; + + static const int NOOP_UPSAMPLE = 0; + static const int FULLSIZE_UPSAMPLE = 1; + static const int H2V1_FANCY_UPSAMPLE = 2; + static const int H2V1_UPSAMPLE = 3; + static const int H2V2_FANCY_UPSAMPLE = 4; + static const int H2V2_UPSAMPLE = 5; + static const int INT_UPSAMPLE = 6; + + static const int INPUT_CONSUME_INPUT = 0; + static const int COEF_CONSUME_INPUT = 1; + + static int extend_test[] = /* entry n is 2**(n-1) */ + [ + 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 + ]; + + static int extend_offset[] = /* entry n is (-1 << n) + 1 */ + [ + 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1, + ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1, + ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1, + ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 + ]; + + static int jpeg_natural_order[] = [ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */ + 63, 63, 63, 63, 63, 63, 63, 63 + ]; + + static final class JQUANT_TBL { + /* This array gives the coefficient quantizers in natural array order + * (not the zigzag order in which they are stored in a JPEG DQT marker). + * CAUTION: IJG versions prior to v6a kept this array in zigzag order. + */ + short[DCTSIZE2] quantval;// = new short[DCTSIZE2]; /* quantization step for each coefficient */ + /* This field is used only during compression. It's initialized false when + * the table is created, and set true when it's been output to the file. + * You could suppress output of a table by setting this to true. + * (See jpeg_suppress_tables for an example.) + */ + bool sent_table; /* true when table has been output */ + } + + static final class JHUFF_TBL { + /* These two fields directly represent the contents of a JPEG DHT marker */ + byte[17] bits;// = new byte[17]; /* bits[k] = # of symbols with codes of */ + /* length k bits; bits[0] is unused */ + byte[256] huffval;// = new byte[256]; /* The symbols, in order of incr code length */ + /* This field is used only during compression. It's initialized false when + * the table is created, and set true when it's been output to the file. + * You could suppress output of a table by setting this to true. + * (See jpeg_suppress_tables for an example.) + */ + bool sent_table; /* true when table has been output */ + } + + static final class bitread_perm_state { /* Bitreading state saved across MCUs */ + int get_buffer; /* current bit-extraction buffer */ + int bits_left; /* # of unused bits in it */ + } + + static final class bitread_working_state { /* Bitreading working state within an MCU */ + /* Current data source location */ + /* We need a copy, rather than munging the original, in case of suspension */ + byte[] buffer; /* => next byte to read from source */ + int bytes_offset; + int bytes_in_buffer; /* # of bytes remaining in source buffer */ + /* Bit input buffer --- note these values are kept in register variables, + * not in this struct, inside the inner loops. + */ + int get_buffer; /* current bit-extraction buffer */ + int bits_left; /* # of unused bits in it */ + /* Pointer needed by jpeg_fill_bit_buffer. */ + jpeg_decompress_struct cinfo; /* back link to decompress master record */ + } + + static final class savable_state { + int EOBRUN; //Note that this is only used in the progressive case + int[MAX_COMPS_IN_SCAN] last_dc_val;// = new int[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */ + } + + static final class d_derived_tbl { + /* Basic tables: (element [0] of each array is unused) */ + int[18] maxcode;// = new int[18]; /* largest code of length k (-1 if none) */ + /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */ + int[17] valoffset;// = new int[17]; /* huffval[] offset for codes of length k */ + /* valoffset[k] = huffval[] index of 1st symbol of code length k, less + * the smallest code of length k; so given a code of length k, the + * corresponding symbol is huffval[code + valoffset[k]] + */ + + /* Link to public Huffman table (needed only in jpeg_huff_decode) */ + JHUFF_TBL pub; + + /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of + * the input data stream. If the next Huffman code is no more + * than HUFF_LOOKAHEAD bits long, we can obtain its length and + * the corresponding symbol directly from these tables. + */ + int[1< 1) { + coef.MCU_rows_per_iMCU_row = 1; + } else { + if (cinfo.input_iMCU_row < (cinfo.total_iMCU_rows-1)) + coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].v_samp_factor; + else + coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].last_row_height; + } + + coef.MCU_ctr = 0; + coef.MCU_vert_offset = 0; + } + + } + + static abstract class jpeg_entropy_decoder { + abstract void start_pass (jpeg_decompress_struct cinfo); + abstract bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data); + + /* This is here to share code between baseline and progressive decoders; */ + /* other modules probably should not use it */ + bool insufficient_data; /* set true after emitting warning */ + + bitread_working_state br_state_local; + savable_state state_local; public this(){ br_state_local = new bitread_working_state(); state_local = new savable_state(); } - } - - static final class huff_entropy_decoder : jpeg_entropy_decoder { - bitread_perm_state bitstate;// = new bitread_perm_state(); /* Bit buffer at start of MCU */ - savable_state saved;// = new savable_state(); /* Other state at start of MCU */ - - /* These fields are NOT loaded into local working state. */ - int restarts_to_go; /* MCUs left in this restart interval */ - - /* Pointers to derived tables (these workspaces have image lifespan) */ - d_derived_tbl[NUM_HUFF_TBLS] dc_derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; - d_derived_tbl[NUM_HUFF_TBLS] ac_derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; - - /* Precalculated info set up by start_pass for use in decode_mcu: */ - - /* Pointers to derived tables to be used for each block within an MCU */ - d_derived_tbl[D_MAX_BLOCKS_IN_MCU] dc_cur_tbls;// = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU]; - d_derived_tbl[D_MAX_BLOCKS_IN_MCU] ac_cur_tbls;// = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU]; - /* Whether we care about the DC and AC coefficient values for each block */ - bool[D_MAX_BLOCKS_IN_MCU] dc_needed;// = new bool[D_MAX_BLOCKS_IN_MCU]; - bool[D_MAX_BLOCKS_IN_MCU] ac_needed;// = new bool[D_MAX_BLOCKS_IN_MCU]; + } + + static final class huff_entropy_decoder : jpeg_entropy_decoder { + bitread_perm_state bitstate;// = new bitread_perm_state(); /* Bit buffer at start of MCU */ + savable_state saved;// = new savable_state(); /* Other state at start of MCU */ + + /* These fields are NOT loaded into local working state. */ + int restarts_to_go; /* MCUs left in this restart interval */ + + /* Pointers to derived tables (these workspaces have image lifespan) */ + d_derived_tbl[NUM_HUFF_TBLS] dc_derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; + d_derived_tbl[NUM_HUFF_TBLS] ac_derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; + + /* Precalculated info set up by start_pass for use in decode_mcu: */ + + /* Pointers to derived tables to be used for each block within an MCU */ + d_derived_tbl[D_MAX_BLOCKS_IN_MCU] dc_cur_tbls;// = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU]; + d_derived_tbl[D_MAX_BLOCKS_IN_MCU] ac_cur_tbls;// = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU]; + /* Whether we care about the DC and AC coefficient values for each block */ + bool[D_MAX_BLOCKS_IN_MCU] dc_needed;// = new bool[D_MAX_BLOCKS_IN_MCU]; + bool[D_MAX_BLOCKS_IN_MCU] ac_needed;// = new bool[D_MAX_BLOCKS_IN_MCU]; public this(){ bitstate = new bitread_perm_state(); /* Bit buffer at start of MCU */ saved = new savable_state(); /* Other state at start of MCU */ } - void start_pass (jpeg_decompress_struct cinfo) { - start_pass_huff_decoder(cinfo); - } - - bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) { - huff_entropy_decoder entropy = this; - int blkn; -// BITREAD_STATE_VARS; - int get_buffer; - int bits_left; -// bitread_working_state br_state = new bitread_working_state(); -// savable_state state = new savable_state(); - bitread_working_state br_state = br_state_local; - savable_state state = state_local; - - /* Process restart marker if needed; may have to suspend */ - if (cinfo.restart_interval != 0) { - if (entropy.restarts_to_go == 0) - if (! process_restart(cinfo)) - return false; - } - - /* If we've run out of data, just leave the MCU set to zeroes. - * This way, we return uniform gray for the remainder of the segment. - */ - if (! entropy.insufficient_data) { - - /* Load up working state */ -// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); - br_state.cinfo = cinfo; - br_state.buffer = cinfo.buffer; - br_state.bytes_in_buffer = cinfo.bytes_in_buffer; - br_state.bytes_offset = cinfo.bytes_offset; - get_buffer = entropy.bitstate.get_buffer; - bits_left = entropy.bitstate.bits_left; - -// ASSIGN_STATE(state, entropy.saved); - state.last_dc_val[0] = entropy.saved.last_dc_val[0]; - state.last_dc_val[1] = entropy.saved.last_dc_val[1]; - state.last_dc_val[2] = entropy.saved.last_dc_val[2]; - state.last_dc_val[3] = entropy.saved.last_dc_val[3]; - - /* Outer loop handles each block in the MCU */ - - for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { - short[] block = MCU_data[blkn]; - d_derived_tbl dctbl = entropy.dc_cur_tbls[blkn]; - d_derived_tbl actbl = entropy.ac_cur_tbls[blkn]; - int s = 0, k, r; - - /* Decode a single block's worth of coefficients */ - - /* Section F.2.2.1: decode the DC coefficient difference */ -// HUFF_DECODE(s, br_state, dctbl, return FALSE, label1); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// look = PEEK_BITS(HUFF_LOOKAHEAD); - if (nb != 1) { - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - if ((nb = dctbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= nb; - s = dctbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - - if (s != 0) { -// CHECK_BIT_BUFFER(br_state, s, return FALSE); - { - if (bits_left < (s)) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// r = GET_BITS(s); - r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); -// s = HUFF_EXTEND(r, s); - s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); - } - - if (entropy.dc_needed[blkn]) { - /* Convert DC difference to actual value, update last_dc_val */ - int ci = cinfo.MCU_membership[blkn]; - s += state.last_dc_val[ci]; - state.last_dc_val[ci] = s; - /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */ - block[0] = cast(short) s; - } - - if (entropy.ac_needed[blkn]) { - - /* Section F.2.2.2: decode the AC coefficients */ - /* Since zeroes are skipped, output area must be cleared beforehand */ - for (k = 1; k < DCTSIZE2; k++) { -// HUFF_DECODE(s, br_state, actbl, return FALSE, label2); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - if (nb != 1) { -// look = PEEK_BITS(HUFF_LOOKAHEAD); - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - if ((nb = actbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= (nb); - s = actbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - r = s >> 4; - s &= 15; - - if (s != 0) { - k += r; -// CHECK_BIT_BUFFER(br_state, s, return FALSE); - { - if (bits_left < (s)) { - if (!jpeg_fill_bit_buffer(br_state, get_buffer, bits_left, s)) { - return false; - } - get_buffer = br_state.get_buffer; - bits_left = br_state.bits_left; - } - } -// r = GET_BITS(s); - r = (((get_buffer >> (bits_left -= (s)))) & ((1 << (s)) - 1)); -// s = HUFF_EXTEND(r, s); - s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); - /* - * Output coefficient in natural (dezigzagged) - * order. Note: the extra entries in - * jpeg_natural_order[] will save us if k >= - * DCTSIZE2, which could happen if the data is - * corrupted. - */ - block[jpeg_natural_order[k]] = cast(short) s; - } else { - if (r != 15) - break; - k += 15; - } - } - - } else { - - /* Section F.2.2.2: decode the AC coefficients */ - /* In this path we just discard the values */ - for (k = 1; k < DCTSIZE2; k++) { -// HUFF_DECODE(s, br_state, actbl, return FALSE, label3); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - if (nb != 1) { -// look = PEEK_BITS(HUFF_LOOKAHEAD); - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - if ((nb = actbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= (nb); - s = actbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - r = s >> 4; - s &= 15; - - if (s != 0) { - k += r; -// CHECK_BIT_BUFFER(br_state, s, return FALSE); - { - if (bits_left < (s)) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// DROP_BITS(s); - bits_left -= s; - } else { - if (r != 15) - break; - k += 15; - } - } - - } - } - - /* Completed MCU, so update state */ -// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); - cinfo.buffer = br_state.buffer; - cinfo.bytes_in_buffer = br_state.bytes_in_buffer; - cinfo.bytes_offset = br_state.bytes_offset; - entropy.bitstate.get_buffer = get_buffer; - entropy.bitstate.bits_left = bits_left; -// ASSIGN_STATE(entropy.saved, state); - entropy.saved.last_dc_val[0] = state.last_dc_val[0]; - entropy.saved.last_dc_val[1] = state.last_dc_val[1]; - entropy.saved.last_dc_val[2] = state.last_dc_val[2]; - entropy.saved.last_dc_val[3] = state.last_dc_val[3]; - } - - /* Account for restart interval (no-op if not using restarts) */ - entropy.restarts_to_go--; - - return true; - } - - void start_pass_huff_decoder (jpeg_decompress_struct cinfo) { - huff_entropy_decoder entropy = this; - int ci, blkn, dctbl, actbl; - jpeg_component_info compptr; - - /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. - * This ought to be an error condition, but we make it a warning because - * there are some baseline files out there with all zeroes in these bytes. - */ - if (cinfo.Ss != 0 || cinfo.Se != DCTSIZE2-1 || cinfo.Ah != 0 || cinfo.Al != 0) { -// WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); - } - - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - dctbl = compptr.dc_tbl_no; - actbl = compptr.ac_tbl_no; - /* Compute derived values for Huffman tables */ - /* We may do this more than once for a table, but it's not expensive */ - jpeg_make_d_derived_tbl(cinfo, true, dctbl, entropy.dc_derived_tbls[dctbl] = new d_derived_tbl()); - jpeg_make_d_derived_tbl(cinfo, false, actbl, entropy.ac_derived_tbls[actbl] = new d_derived_tbl()); - /* Initialize DC predictions to 0 */ - entropy.saved.last_dc_val[ci] = 0; - } - - /* Precalculate decoding info for each block in an MCU of this scan */ - for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { - ci = cinfo.MCU_membership[blkn]; - compptr = cinfo.cur_comp_info[ci]; - /* Precalculate which table to use for each block */ - entropy.dc_cur_tbls[blkn] = entropy.dc_derived_tbls[compptr.dc_tbl_no]; - entropy.ac_cur_tbls[blkn] = entropy.ac_derived_tbls[compptr.ac_tbl_no]; - /* Decide whether we really care about the coefficient values */ - if (compptr.component_needed) { - entropy.dc_needed[blkn] = true; - /* we don't need the ACs if producing a 1/8th-size image */ - entropy.ac_needed[blkn] = (compptr.DCT_scaled_size > 1); - } else { - entropy.dc_needed[blkn] = entropy.ac_needed[blkn] = false; - } - } - - /* Initialize bitread state variables */ - entropy.bitstate.bits_left = 0; - entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ - entropy.insufficient_data = false; - - /* Initialize restart counter */ - entropy.restarts_to_go = cinfo.restart_interval; - } - - bool process_restart (jpeg_decompress_struct cinfo) { - huff_entropy_decoder entropy = this; - int ci; - - /* Throw away any unused bits remaining in bit buffer; */ - /* include any full bytes in next_marker's count of discarded bytes */ - cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8; - entropy.bitstate.bits_left = 0; - - /* Advance past the RSTn marker */ - if (! read_restart_marker (cinfo)) - return false; - - /* Re-initialize DC predictions to 0 */ - for (ci = 0; ci < cinfo.comps_in_scan; ci++) - entropy.saved.last_dc_val[ci] = 0; - - /* Reset restart counter */ - entropy.restarts_to_go = cinfo.restart_interval; - - /* Reset out-of-data flag, unless read_restart_marker left us smack up - * against a marker. In that case we will end up treating the next data - * segment as empty, and we can avoid producing bogus output pixels by - * leaving the flag set. - */ - if (cinfo.unread_marker == 0) - entropy.insufficient_data = false; - - return true; - } - } - - static final class phuff_entropy_decoder : jpeg_entropy_decoder { - - /* These fields are loaded into local variables at start of each MCU. - * In case of suspension, we exit WITHOUT updating them. - */ - bitread_perm_state bitstate;// = new bitread_perm_state(); /* Bit buffer at start of MCU */ - savable_state saved;// = new savable_state(); /* Other state at start of MCU */ - - /* These fields are NOT loaded into local working state. */ - int restarts_to_go; /* MCUs left in this restart interval */ - - /* Pointers to derived tables (these workspaces have image lifespan) */ - d_derived_tbl[NUM_HUFF_TBLS] derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; - - d_derived_tbl ac_derived_tbl; /* active table during an AC scan */ - - int[DCTSIZE2] newnz_pos;// = new int[DCTSIZE2]; + void start_pass (jpeg_decompress_struct cinfo) { + start_pass_huff_decoder(cinfo); + } + + bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) { + huff_entropy_decoder entropy = this; + int blkn; +// BITREAD_STATE_VARS; + int get_buffer; + int bits_left; +// bitread_working_state br_state = new bitread_working_state(); +// savable_state state = new savable_state(); + bitread_working_state br_state = br_state_local; + savable_state state = state_local; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo.restart_interval != 0) { + if (entropy.restarts_to_go == 0) + if (! process_restart(cinfo)) + return false; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy.insufficient_data) { + + /* Load up working state */ +// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); + br_state.cinfo = cinfo; + br_state.buffer = cinfo.buffer; + br_state.bytes_in_buffer = cinfo.bytes_in_buffer; + br_state.bytes_offset = cinfo.bytes_offset; + get_buffer = entropy.bitstate.get_buffer; + bits_left = entropy.bitstate.bits_left; + +// ASSIGN_STATE(state, entropy.saved); + state.last_dc_val[0] = entropy.saved.last_dc_val[0]; + state.last_dc_val[1] = entropy.saved.last_dc_val[1]; + state.last_dc_val[2] = entropy.saved.last_dc_val[2]; + state.last_dc_val[3] = entropy.saved.last_dc_val[3]; + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { + short[] block = MCU_data[blkn]; + d_derived_tbl dctbl = entropy.dc_cur_tbls[blkn]; + d_derived_tbl actbl = entropy.ac_cur_tbls[blkn]; + int s = 0, k, r; + + /* Decode a single block's worth of coefficients */ + + /* Section F.2.2.1: decode the DC coefficient difference */ +// HUFF_DECODE(s, br_state, dctbl, return FALSE, label1); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// look = PEEK_BITS(HUFF_LOOKAHEAD); + if (nb != 1) { + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + if ((nb = dctbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= nb; + s = dctbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + + if (s != 0) { +// CHECK_BIT_BUFFER(br_state, s, return FALSE); + { + if (bits_left < (s)) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// r = GET_BITS(s); + r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); +// s = HUFF_EXTEND(r, s); + s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); + } + + if (entropy.dc_needed[blkn]) { + /* Convert DC difference to actual value, update last_dc_val */ + int ci = cinfo.MCU_membership[blkn]; + s += state.last_dc_val[ci]; + state.last_dc_val[ci] = s; + /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */ + block[0] = cast(short) s; + } + + if (entropy.ac_needed[blkn]) { + + /* Section F.2.2.2: decode the AC coefficients */ + /* Since zeroes are skipped, output area must be cleared beforehand */ + for (k = 1; k < DCTSIZE2; k++) { +// HUFF_DECODE(s, br_state, actbl, return FALSE, label2); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + if (nb != 1) { +// look = PEEK_BITS(HUFF_LOOKAHEAD); + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + if ((nb = actbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= (nb); + s = actbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + r = s >> 4; + s &= 15; + + if (s != 0) { + k += r; +// CHECK_BIT_BUFFER(br_state, s, return FALSE); + { + if (bits_left < (s)) { + if (!jpeg_fill_bit_buffer(br_state, get_buffer, bits_left, s)) { + return false; + } + get_buffer = br_state.get_buffer; + bits_left = br_state.bits_left; + } + } +// r = GET_BITS(s); + r = (((get_buffer >> (bits_left -= (s)))) & ((1 << (s)) - 1)); +// s = HUFF_EXTEND(r, s); + s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); + /* + * Output coefficient in natural (dezigzagged) + * order. Note: the extra entries in + * jpeg_natural_order[] will save us if k >= + * DCTSIZE2, which could happen if the data is + * corrupted. + */ + block[jpeg_natural_order[k]] = cast(short) s; + } else { + if (r != 15) + break; + k += 15; + } + } + + } else { + + /* Section F.2.2.2: decode the AC coefficients */ + /* In this path we just discard the values */ + for (k = 1; k < DCTSIZE2; k++) { +// HUFF_DECODE(s, br_state, actbl, return FALSE, label3); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + if (nb != 1) { +// look = PEEK_BITS(HUFF_LOOKAHEAD); + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + if ((nb = actbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= (nb); + s = actbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + r = s >> 4; + s &= 15; + + if (s != 0) { + k += r; +// CHECK_BIT_BUFFER(br_state, s, return FALSE); + { + if (bits_left < (s)) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// DROP_BITS(s); + bits_left -= s; + } else { + if (r != 15) + break; + k += 15; + } + } + + } + } + + /* Completed MCU, so update state */ +// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); + cinfo.buffer = br_state.buffer; + cinfo.bytes_in_buffer = br_state.bytes_in_buffer; + cinfo.bytes_offset = br_state.bytes_offset; + entropy.bitstate.get_buffer = get_buffer; + entropy.bitstate.bits_left = bits_left; +// ASSIGN_STATE(entropy.saved, state); + entropy.saved.last_dc_val[0] = state.last_dc_val[0]; + entropy.saved.last_dc_val[1] = state.last_dc_val[1]; + entropy.saved.last_dc_val[2] = state.last_dc_val[2]; + entropy.saved.last_dc_val[3] = state.last_dc_val[3]; + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy.restarts_to_go--; + + return true; + } + + void start_pass_huff_decoder (jpeg_decompress_struct cinfo) { + huff_entropy_decoder entropy = this; + int ci, blkn, dctbl, actbl; + jpeg_component_info compptr; + + /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG. + * This ought to be an error condition, but we make it a warning because + * there are some baseline files out there with all zeroes in these bytes. + */ + if (cinfo.Ss != 0 || cinfo.Se != DCTSIZE2-1 || cinfo.Ah != 0 || cinfo.Al != 0) { +// WARNMS(cinfo, JWRN_NOT_SEQUENTIAL); + } + + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + dctbl = compptr.dc_tbl_no; + actbl = compptr.ac_tbl_no; + /* Compute derived values for Huffman tables */ + /* We may do this more than once for a table, but it's not expensive */ + jpeg_make_d_derived_tbl(cinfo, true, dctbl, entropy.dc_derived_tbls[dctbl] = new d_derived_tbl()); + jpeg_make_d_derived_tbl(cinfo, false, actbl, entropy.ac_derived_tbls[actbl] = new d_derived_tbl()); + /* Initialize DC predictions to 0 */ + entropy.saved.last_dc_val[ci] = 0; + } + + /* Precalculate decoding info for each block in an MCU of this scan */ + for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { + ci = cinfo.MCU_membership[blkn]; + compptr = cinfo.cur_comp_info[ci]; + /* Precalculate which table to use for each block */ + entropy.dc_cur_tbls[blkn] = entropy.dc_derived_tbls[compptr.dc_tbl_no]; + entropy.ac_cur_tbls[blkn] = entropy.ac_derived_tbls[compptr.ac_tbl_no]; + /* Decide whether we really care about the coefficient values */ + if (compptr.component_needed) { + entropy.dc_needed[blkn] = true; + /* we don't need the ACs if producing a 1/8th-size image */ + entropy.ac_needed[blkn] = (compptr.DCT_scaled_size > 1); + } else { + entropy.dc_needed[blkn] = entropy.ac_needed[blkn] = false; + } + } + + /* Initialize bitread state variables */ + entropy.bitstate.bits_left = 0; + entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ + entropy.insufficient_data = false; + + /* Initialize restart counter */ + entropy.restarts_to_go = cinfo.restart_interval; + } + + bool process_restart (jpeg_decompress_struct cinfo) { + huff_entropy_decoder entropy = this; + int ci; + + /* Throw away any unused bits remaining in bit buffer; */ + /* include any full bytes in next_marker's count of discarded bytes */ + cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8; + entropy.bitstate.bits_left = 0; + + /* Advance past the RSTn marker */ + if (! read_restart_marker (cinfo)) + return false; + + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < cinfo.comps_in_scan; ci++) + entropy.saved.last_dc_val[ci] = 0; + + /* Reset restart counter */ + entropy.restarts_to_go = cinfo.restart_interval; + + /* Reset out-of-data flag, unless read_restart_marker left us smack up + * against a marker. In that case we will end up treating the next data + * segment as empty, and we can avoid producing bogus output pixels by + * leaving the flag set. + */ + if (cinfo.unread_marker == 0) + entropy.insufficient_data = false; + + return true; + } + } + + static final class phuff_entropy_decoder : jpeg_entropy_decoder { + + /* These fields are loaded into local variables at start of each MCU. + * In case of suspension, we exit WITHOUT updating them. + */ + bitread_perm_state bitstate;// = new bitread_perm_state(); /* Bit buffer at start of MCU */ + savable_state saved;// = new savable_state(); /* Other state at start of MCU */ + + /* These fields are NOT loaded into local working state. */ + int restarts_to_go; /* MCUs left in this restart interval */ + + /* Pointers to derived tables (these workspaces have image lifespan) */ + d_derived_tbl[NUM_HUFF_TBLS] derived_tbls;// = new d_derived_tbl[NUM_HUFF_TBLS]; + + d_derived_tbl ac_derived_tbl; /* active table during an AC scan */ + + int[DCTSIZE2] newnz_pos;// = new int[DCTSIZE2]; public this(){ bitstate = new bitread_perm_state(); /* Bit buffer at start of MCU */ saved = new savable_state(); /* Other state at start of MCU */ } - void start_pass (jpeg_decompress_struct cinfo) { - start_pass_phuff_decoder(cinfo); - } - - bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) { - bool is_DC_band = (cinfo.Ss == 0); - if (cinfo.Ah == 0) { - if (is_DC_band) - return decode_mcu_DC_first(cinfo, MCU_data); - else - return decode_mcu_AC_first(cinfo, MCU_data); - } else { - if (is_DC_band) - return decode_mcu_DC_refine(cinfo, MCU_data); - else - return decode_mcu_AC_refine(cinfo, MCU_data); - } - } - - bool decode_mcu_DC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) { - phuff_entropy_decoder entropy = this; - int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */ - int blkn; - short[] block; -// BITREAD_STATE_VARS; - int get_buffer; - int bits_left; -// bitread_working_state br_state = new bitread_working_state(); - bitread_working_state br_state = br_state_local; - - /* Process restart marker if needed; may have to suspend */ - if (cinfo.restart_interval != 0) { - if (entropy.restarts_to_go == 0) - if (! process_restart(cinfo)) - return false; - } - - /* Not worth the cycles to check insufficient_data here, - * since we will not change the data anyway if we read zeroes. - */ - - /* Load up working state */ -// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); - br_state.cinfo = cinfo; - br_state.buffer = cinfo.buffer; - br_state.bytes_in_buffer = cinfo.bytes_in_buffer; - br_state.bytes_offset = cinfo.bytes_offset; - get_buffer = entropy.bitstate.get_buffer; - bits_left = entropy.bitstate.bits_left; - - /* Outer loop handles each block in the MCU */ - - for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { - block = MCU_data[blkn]; - - /* Encoded data is simply the next bit of the two's-complement DC value */ -// CHECK_BIT_BUFFER(br_state, 1, return FALSE); - { - if (bits_left < (1)) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// if (GET_BITS(1)) - if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) - block[0] |= p1; - /* Note: since we use |=, repeating the assignment later is safe */ - } - - /* Completed MCU, so update state */ -// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); - cinfo.buffer = br_state.buffer; - cinfo.bytes_in_buffer = br_state.bytes_in_buffer; - cinfo.bytes_offset = br_state.bytes_offset; - entropy.bitstate.get_buffer = get_buffer; - entropy.bitstate.bits_left = bits_left; - - /* Account for restart interval (no-op if not using restarts) */ - entropy.restarts_to_go--; - - return true; - - } - - bool decode_mcu_AC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) { - phuff_entropy_decoder entropy = this; - int Se = cinfo.Se; - int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */ - int m1 = (-1) << cinfo.Al; /* -1 in the bit position being coded */ - int s = 0, k, r; - int EOBRUN; - short[] block; - short[] thiscoef; -// BITREAD_STATE_VARS; - int get_buffer; - int bits_left; -// bitread_working_state br_state = new bitread_working_state(); - bitread_working_state br_state = br_state_local; - - d_derived_tbl tbl; - int num_newnz; - int[] newnz_pos = entropy.newnz_pos; - - /* Process restart marker if needed; may have to suspend */ - if (cinfo.restart_interval != 0) { - if (entropy.restarts_to_go == 0) - if (! process_restart(cinfo)) - return false; - } - - /* If we've run out of data, don't modify the MCU. - */ - if (! entropy.insufficient_data) { - - /* Load up working state */ -// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); - br_state.cinfo = cinfo; - br_state.buffer = cinfo.buffer; - br_state.bytes_in_buffer = cinfo.bytes_in_buffer; - br_state.bytes_offset = cinfo.bytes_offset; - get_buffer = entropy.bitstate.get_buffer; - bits_left = entropy.bitstate.bits_left; - - EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */ - - /* There is always only one block per MCU */ - block = MCU_data[0]; - tbl = entropy.ac_derived_tbl; - - /* If we are forced to suspend, we must undo the assignments to any newly - * nonzero coefficients in the block, because otherwise we'd get confused - * next time about which coefficients were already nonzero. - * But we need not undo addition of bits to already-nonzero coefficients; - * instead, we can test the current bit to see if we already did it. - */ - num_newnz = 0; - - /* initialize coefficient loop counter to start of band */ - k = cinfo.Ss; - - if (EOBRUN == 0) { - for (; k <= Se; k++) { -// HUFF_DECODE(s, br_state, tbl, goto undoit, label3); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - if (nb != 1) { -// look = PEEK_BITS(HUFF_LOOKAHEAD); - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - if ((nb = tbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= nb; - s = tbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - r = s >> 4; - s &= 15; - if (s != 0) { - if (s != 1) { /* size of new coef should always be 1 */ -// WARNMS(cinfo, JWRN_HUFF_BAD_CODE); - } -// CHECK_BIT_BUFFER(br_state, 1, goto undoit); - { - if (bits_left < (1)) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// if (GET_BITS(1)) - if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) - s = p1; /* newly nonzero coef is positive */ - else - s = m1; /* newly nonzero coef is negative */ - } else { - if (r != 15) { - EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */ - if (r != 0) { -// CHECK_BIT_BUFFER(br_state, r, goto undoit); - { - if (bits_left < (r)) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// r = GET_BITS(r); - r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1)); - EOBRUN += r; - } - break; /* rest of block is handled by EOB logic */ - } - /* note s = 0 for processing ZRL */ - } - /* Advance over already-nonzero coefs and r still-zero coefs, - * appending correction bits to the nonzeroes. A correction bit is 1 - * if the absolute value of the coefficient must be increased. - */ - do { - thiscoef = block; - int thiscoef_offset = jpeg_natural_order[k]; - if (thiscoef[thiscoef_offset] != 0) { -// CHECK_BIT_BUFFER(br_state, 1, goto undoit); - { - if (bits_left < (1)) { - if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// if (GET_BITS(1)) { - if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) { - if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already set it */ - if (thiscoef[thiscoef_offset] >= 0) - thiscoef[thiscoef_offset] += p1; - else - thiscoef[thiscoef_offset] += m1; - } - } - } else { - if (--r < 0) - break; /* reached target zero coefficient */ - } - k++; - } while (k <= Se); - if (s != 0) { - int pos = jpeg_natural_order[k]; - /* Output newly nonzero coefficient */ - block[pos] = cast(short) s; - /* Remember its position in case we have to suspend */ - newnz_pos[num_newnz++] = pos; - } - } - } - - if (EOBRUN > 0) { - /* Scan any remaining coefficient positions after the end-of-band - * (the last newly nonzero coefficient, if any). Append a correction - * bit to each already-nonzero coefficient. A correction bit is 1 - * if the absolute value of the coefficient must be increased. - */ - for (; k <= Se; k++) { - thiscoef = block; - int thiscoef_offset = jpeg_natural_order[k]; - if (thiscoef[thiscoef_offset] != 0) { -// CHECK_BIT_BUFFER(br_state, 1, goto undoit); - { - if (bits_left < (1)) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { -// failaction; - while (num_newnz > 0) - block[newnz_pos[--num_newnz]] = 0; - - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// if (GET_BITS(1)) { - if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) { - if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already changed it */ - if (thiscoef[thiscoef_offset] >= 0) - thiscoef[thiscoef_offset] += p1; - else - thiscoef[thiscoef_offset] += m1; - } - } - } - } - /* Count one block completed in EOB run */ - EOBRUN--; - } - - /* Completed MCU, so update state */ -// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); - cinfo.buffer = br_state.buffer; - cinfo.bytes_in_buffer = br_state.bytes_in_buffer; - cinfo.bytes_offset = br_state.bytes_offset; - entropy.bitstate.get_buffer = get_buffer; - entropy.bitstate.bits_left = bits_left; - - entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */ - } - - /* Account for restart interval (no-op if not using restarts) */ - entropy.restarts_to_go--; - - return true; - -// undoit: -// /* Re-zero any output coefficients that we made newly nonzero */ -// while (num_newnz > 0) -// (*block)[newnz_pos[--num_newnz]] = 0; + void start_pass (jpeg_decompress_struct cinfo) { + start_pass_phuff_decoder(cinfo); + } + + bool decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) { + bool is_DC_band = (cinfo.Ss == 0); + if (cinfo.Ah == 0) { + if (is_DC_band) + return decode_mcu_DC_first(cinfo, MCU_data); + else + return decode_mcu_AC_first(cinfo, MCU_data); + } else { + if (is_DC_band) + return decode_mcu_DC_refine(cinfo, MCU_data); + else + return decode_mcu_AC_refine(cinfo, MCU_data); + } + } + + bool decode_mcu_DC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) { + phuff_entropy_decoder entropy = this; + int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */ + int blkn; + short[] block; +// BITREAD_STATE_VARS; + int get_buffer; + int bits_left; +// bitread_working_state br_state = new bitread_working_state(); + bitread_working_state br_state = br_state_local; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo.restart_interval != 0) { + if (entropy.restarts_to_go == 0) + if (! process_restart(cinfo)) + return false; + } + + /* Not worth the cycles to check insufficient_data here, + * since we will not change the data anyway if we read zeroes. + */ + + /* Load up working state */ +// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); + br_state.cinfo = cinfo; + br_state.buffer = cinfo.buffer; + br_state.bytes_in_buffer = cinfo.bytes_in_buffer; + br_state.bytes_offset = cinfo.bytes_offset; + get_buffer = entropy.bitstate.get_buffer; + bits_left = entropy.bitstate.bits_left; + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + + /* Encoded data is simply the next bit of the two's-complement DC value */ +// CHECK_BIT_BUFFER(br_state, 1, return FALSE); + { + if (bits_left < (1)) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// if (GET_BITS(1)) + if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) + block[0] |= p1; + /* Note: since we use |=, repeating the assignment later is safe */ + } + + /* Completed MCU, so update state */ +// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); + cinfo.buffer = br_state.buffer; + cinfo.bytes_in_buffer = br_state.bytes_in_buffer; + cinfo.bytes_offset = br_state.bytes_offset; + entropy.bitstate.get_buffer = get_buffer; + entropy.bitstate.bits_left = bits_left; + + /* Account for restart interval (no-op if not using restarts) */ + entropy.restarts_to_go--; + + return true; + + } + + bool decode_mcu_AC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) { + phuff_entropy_decoder entropy = this; + int Se = cinfo.Se; + int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */ + int m1 = (-1) << cinfo.Al; /* -1 in the bit position being coded */ + int s = 0, k, r; + int EOBRUN; + short[] block; + short[] thiscoef; +// BITREAD_STATE_VARS; + int get_buffer; + int bits_left; +// bitread_working_state br_state = new bitread_working_state(); + bitread_working_state br_state = br_state_local; + + d_derived_tbl tbl; + int num_newnz; + int[] newnz_pos = entropy.newnz_pos; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo.restart_interval != 0) { + if (entropy.restarts_to_go == 0) + if (! process_restart(cinfo)) + return false; + } + + /* If we've run out of data, don't modify the MCU. + */ + if (! entropy.insufficient_data) { + + /* Load up working state */ +// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); + br_state.cinfo = cinfo; + br_state.buffer = cinfo.buffer; + br_state.bytes_in_buffer = cinfo.bytes_in_buffer; + br_state.bytes_offset = cinfo.bytes_offset; + get_buffer = entropy.bitstate.get_buffer; + bits_left = entropy.bitstate.bits_left; + + EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */ + + /* There is always only one block per MCU */ + block = MCU_data[0]; + tbl = entropy.ac_derived_tbl; + + /* If we are forced to suspend, we must undo the assignments to any newly + * nonzero coefficients in the block, because otherwise we'd get confused + * next time about which coefficients were already nonzero. + * But we need not undo addition of bits to already-nonzero coefficients; + * instead, we can test the current bit to see if we already did it. + */ + num_newnz = 0; + + /* initialize coefficient loop counter to start of band */ + k = cinfo.Ss; + + if (EOBRUN == 0) { + for (; k <= Se; k++) { +// HUFF_DECODE(s, br_state, tbl, goto undoit, label3); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + if (nb != 1) { +// look = PEEK_BITS(HUFF_LOOKAHEAD); + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + if ((nb = tbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= nb; + s = tbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + r = s >> 4; + s &= 15; + if (s != 0) { + if (s != 1) { /* size of new coef should always be 1 */ +// WARNMS(cinfo, JWRN_HUFF_BAD_CODE); + } +// CHECK_BIT_BUFFER(br_state, 1, goto undoit); + { + if (bits_left < (1)) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// if (GET_BITS(1)) + if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) + s = p1; /* newly nonzero coef is positive */ + else + s = m1; /* newly nonzero coef is negative */ + } else { + if (r != 15) { + EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */ + if (r != 0) { +// CHECK_BIT_BUFFER(br_state, r, goto undoit); + { + if (bits_left < (r)) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// r = GET_BITS(r); + r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1)); + EOBRUN += r; + } + break; /* rest of block is handled by EOB logic */ + } + /* note s = 0 for processing ZRL */ + } + /* Advance over already-nonzero coefs and r still-zero coefs, + * appending correction bits to the nonzeroes. A correction bit is 1 + * if the absolute value of the coefficient must be increased. + */ + do { + thiscoef = block; + int thiscoef_offset = jpeg_natural_order[k]; + if (thiscoef[thiscoef_offset] != 0) { +// CHECK_BIT_BUFFER(br_state, 1, goto undoit); + { + if (bits_left < (1)) { + if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// if (GET_BITS(1)) { + if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) { + if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already set it */ + if (thiscoef[thiscoef_offset] >= 0) + thiscoef[thiscoef_offset] += p1; + else + thiscoef[thiscoef_offset] += m1; + } + } + } else { + if (--r < 0) + break; /* reached target zero coefficient */ + } + k++; + } while (k <= Se); + if (s != 0) { + int pos = jpeg_natural_order[k]; + /* Output newly nonzero coefficient */ + block[pos] = cast(short) s; + /* Remember its position in case we have to suspend */ + newnz_pos[num_newnz++] = pos; + } + } + } + + if (EOBRUN > 0) { + /* Scan any remaining coefficient positions after the end-of-band + * (the last newly nonzero coefficient, if any). Append a correction + * bit to each already-nonzero coefficient. A correction bit is 1 + * if the absolute value of the coefficient must be increased. + */ + for (; k <= Se; k++) { + thiscoef = block; + int thiscoef_offset = jpeg_natural_order[k]; + if (thiscoef[thiscoef_offset] != 0) { +// CHECK_BIT_BUFFER(br_state, 1, goto undoit); + { + if (bits_left < (1)) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) { +// failaction; + while (num_newnz > 0) + block[newnz_pos[--num_newnz]] = 0; + + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// if (GET_BITS(1)) { + if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) { + if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already changed it */ + if (thiscoef[thiscoef_offset] >= 0) + thiscoef[thiscoef_offset] += p1; + else + thiscoef[thiscoef_offset] += m1; + } + } + } + } + /* Count one block completed in EOB run */ + EOBRUN--; + } + + /* Completed MCU, so update state */ +// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); + cinfo.buffer = br_state.buffer; + cinfo.bytes_in_buffer = br_state.bytes_in_buffer; + cinfo.bytes_offset = br_state.bytes_offset; + entropy.bitstate.get_buffer = get_buffer; + entropy.bitstate.bits_left = bits_left; + + entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */ + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy.restarts_to_go--; + + return true; + +// undoit: +// /* Re-zero any output coefficients that we made newly nonzero */ +// while (num_newnz > 0) +// (*block)[newnz_pos[--num_newnz]] = 0; // -// return false; - - } - - bool decode_mcu_AC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) { - phuff_entropy_decoder entropy = this; - int Se = cinfo.Se; - int Al = cinfo.Al; - int s = 0, k, r; - int EOBRUN; - short[] block; -// BITREAD_STATE_VARS; - int get_buffer; - int bits_left; -// bitread_working_state br_state = new bitread_working_state(); - bitread_working_state br_state = br_state_local; - - d_derived_tbl tbl; - - /* Process restart marker if needed; may have to suspend */ - if (cinfo.restart_interval != 0) { - if (entropy.restarts_to_go == 0) - if (! process_restart(cinfo)) - return false; - } - - /* If we've run out of data, just leave the MCU set to zeroes. - * This way, we return uniform gray for the remainder of the segment. - */ - if (! entropy.insufficient_data) { - - /* Load up working state. - * We can avoid loading/saving bitread state if in an EOB run. - */ - EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */ - - /* There is always only one block per MCU */ - - if (EOBRUN > 0) /* if it's a band of zeroes... */ - EOBRUN--; /* ...process it now (we do nothing) */ - else { -// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); - br_state.cinfo = cinfo; - br_state.buffer = cinfo.buffer; - br_state.bytes_in_buffer = cinfo.bytes_in_buffer; - br_state.bytes_offset = cinfo.bytes_offset; - get_buffer = entropy.bitstate.get_buffer; - bits_left = entropy.bitstate.bits_left; - - block = MCU_data[0]; - tbl = entropy.ac_derived_tbl; - - for (k = cinfo.Ss; k <= Se; k++) { -// HUFF_DECODE(s, br_state, tbl, return FALSE, label2); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - if (nb != 1) { -// look = PEEK_BITS(HUFF_LOOKAHEAD); - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - - if ((nb = tbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= nb; - s = tbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - r = s >> 4; - s &= 15; - if (s != 0) { - k += r; -// CHECK_BIT_BUFFER(br_state, s, return FALSE); - { - if (bits_left < (s)) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// r = GET_BITS(s); - r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); -// s = HUFF_EXTEND(r, s); - s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); - /* Scale and output coefficient in natural (dezigzagged) order */ - block[jpeg_natural_order[k]] = cast(short) (s << Al); - } else { - if (r == 15) { /* ZRL */ - k += 15; /* skip 15 zeroes in band */ - } else { /* EOBr, run length is 2^r + appended bits */ - EOBRUN = 1 << r; - if (r != 0) { /* EOBr, r > 0 */ -// CHECK_BIT_BUFFER(br_state, r, return FALSE); - { - if (bits_left < (r)) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// r = GET_BITS(r); - r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1)); - EOBRUN += r; - } - EOBRUN--; /* this band is processed at this moment */ - break; /* force end-of-band */ - } - } - } - -// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); - cinfo.buffer = br_state.buffer; - cinfo.bytes_in_buffer = br_state.bytes_in_buffer; - cinfo.bytes_offset = br_state.bytes_offset; - entropy.bitstate.get_buffer = get_buffer; - entropy.bitstate.bits_left = bits_left; - } - - /* Completed MCU, so update state */ - entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */ - } - - /* Account for restart interval (no-op if not using restarts) */ - entropy.restarts_to_go--; - - return true; - } - - bool decode_mcu_DC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) { - phuff_entropy_decoder entropy = this; - int Al = cinfo.Al; - int s = 0, r; - int blkn, ci; - short[] block; -// BITREAD_STATE_VARS; - int get_buffer; - int bits_left; -// bitread_working_state br_state = new bitread_working_state(); - bitread_working_state br_state = br_state_local; - -// savable_state state = new savable_state(); - savable_state state = state_local; - d_derived_tbl tbl; - jpeg_component_info compptr; - - /* Process restart marker if needed; may have to suspend */ - if (cinfo.restart_interval != 0) { - if (entropy.restarts_to_go == 0) - if (! process_restart(cinfo)) - return false; - } - - /* If we've run out of data, just leave the MCU set to zeroes. - * This way, we return uniform gray for the remainder of the segment. - */ - if (! entropy.insufficient_data) { - - /* Load up working state */ -// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); - br_state.cinfo = cinfo; - br_state.buffer = cinfo.buffer; - br_state.bytes_in_buffer = cinfo.bytes_in_buffer; - br_state.bytes_offset = cinfo.bytes_offset; - get_buffer = entropy.bitstate.get_buffer; - bits_left = entropy.bitstate.bits_left; - -// ASSIGN_STATE(state, entropy.saved); - state.EOBRUN = entropy.saved.EOBRUN; - state.last_dc_val[0] = entropy.saved.last_dc_val[0]; - state.last_dc_val[1] = entropy.saved.last_dc_val[1]; - state.last_dc_val[2] = entropy.saved.last_dc_val[2]; - state.last_dc_val[3] = entropy.saved.last_dc_val[3]; - - /* Outer loop handles each block in the MCU */ - - for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { - block = MCU_data[blkn]; - ci = cinfo.MCU_membership[blkn]; - compptr = cinfo.cur_comp_info[ci]; - tbl = entropy.derived_tbls[compptr.dc_tbl_no]; - - /* Decode a single block's worth of coefficients */ - - /* Section F.2.2.1: decode the DC coefficient difference */ -// HUFF_DECODE(s, br_state, tbl, return FALSE, label1); - { - int nb = 0, look; - if (bits_left < HUFF_LOOKAHEAD) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - if (bits_left < HUFF_LOOKAHEAD) { - nb = 1; -// goto slowlabel; - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - if (nb != 1) { -// look = PEEK_BITS(HUFF_LOOKAHEAD); - look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); - - if ((nb = tbl.look_nbits[look]) != 0) { -// DROP_BITS(nb); - bits_left -= nb; - s = tbl.look_sym[look] & 0xFF; - } else { - nb = HUFF_LOOKAHEAD+1; -// slowlabel: - if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } - } - if (s != 0) { -// CHECK_BIT_BUFFER(br_state, s, return FALSE); - { - if (bits_left < (s)) { - if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { - return false; - } - get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; - } - } -// r = GET_BITS(s); - r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); -// s = HUFF_EXTEND(r, s); - s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); - } - - /* Convert DC difference to actual value, update last_dc_val */ - s += state.last_dc_val[ci]; - state.last_dc_val[ci] = s; - /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */ - block[0] = cast(short) (s << Al); - } - - /* Completed MCU, so update state */ -// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); - cinfo.buffer = br_state.buffer; - cinfo.bytes_in_buffer = br_state.bytes_in_buffer; - cinfo.bytes_offset = br_state.bytes_offset; - entropy.bitstate.get_buffer = get_buffer; - entropy.bitstate.bits_left = bits_left; -// ASSIGN_STATE(entropy.saved, state); - entropy.saved.EOBRUN = state.EOBRUN; - entropy.saved.last_dc_val[0] = state.last_dc_val[0]; - entropy.saved.last_dc_val[1] = state.last_dc_val[1]; - entropy.saved.last_dc_val[2] = state.last_dc_val[2]; - entropy.saved.last_dc_val[3] = state.last_dc_val[3]; - } - - /* Account for restart interval (no-op if not using restarts) */ - entropy.restarts_to_go--; - - return true; - } - - bool process_restart (jpeg_decompress_struct cinfo) { - phuff_entropy_decoder entropy = this; - int ci; - - /* Throw away any unused bits remaining in bit buffer; */ - /* include any full bytes in next_marker's count of discarded bytes */ - cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8; - entropy.bitstate.bits_left = 0; - - /* Advance past the RSTn marker */ - if (! read_restart_marker (cinfo)) - return false; - - /* Re-initialize DC predictions to 0 */ - for (ci = 0; ci < cinfo.comps_in_scan; ci++) - entropy.saved.last_dc_val[ci] = 0; - /* Re-init EOB run count, too */ - entropy.saved.EOBRUN = 0; - - /* Reset restart counter */ - entropy.restarts_to_go = cinfo.restart_interval; - - /* Reset out-of-data flag, unless read_restart_marker left us smack up - * against a marker. In that case we will end up treating the next data - * segment as empty, and we can avoid producing bogus output pixels by - * leaving the flag set. - */ - if (cinfo.unread_marker == 0) - entropy.insufficient_data = false; - - return true; - } - - void start_pass_phuff_decoder (jpeg_decompress_struct cinfo) { - phuff_entropy_decoder entropy = this; - bool is_DC_band, bad; - int ci, coefi, tbl; - int[] coef_bit_ptr; - jpeg_component_info compptr; - - is_DC_band = (cinfo.Ss == 0); - - /* Validate scan parameters */ - bad = false; - if (is_DC_band) { - if (cinfo.Se != 0) - bad = true; - } else { - /* need not check Ss/Se < 0 since they came from unsigned bytes */ - if (cinfo.Ss > cinfo.Se || cinfo.Se >= DCTSIZE2) - bad = true; - /* AC scans may have only one component */ - if (cinfo.comps_in_scan != 1) - bad = true; - } - if (cinfo.Ah != 0) { - /* Successive approximation refinement scan: must have Al = Ah-1. */ - if (cinfo.Al != cinfo.Ah-1) - bad = true; - } - if (cinfo.Al > 13) /* need not check for < 0 */ - bad = true; - /* Arguably the maximum Al value should be less than 13 for 8-bit precision, - * but the spec doesn't say so, and we try to be liberal about what we - * accept. Note: large Al values could result in out-of-range DC - * coefficients during early scans, leading to bizarre displays due to - * overflows in the IDCT math. But we won't crash. - */ - if (bad) - error(); -// ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al); - /* Update progression status, and verify that scan order is legal. - * Note that inter-scan inconsistencies are treated as warnings - * not fatal errors ... not clear if this is right way to behave. - */ - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - int cindex = cinfo.cur_comp_info[ci].component_index; - coef_bit_ptr = cinfo.coef_bits[cindex]; - if (!is_DC_band && coef_bit_ptr[0] < 0) {/* AC without prior DC scan */ -// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0); - } - for (coefi = cinfo.Ss; coefi <= cinfo.Se; coefi++) { - int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi]; - if (cinfo.Ah != expected) { -// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi); - } - coef_bit_ptr[coefi] = cinfo.Al; - } - } - - /* Select MCU decoding routine */ -// if (cinfo.Ah == 0) { -// if (is_DC_band) -// entropy.pub.decode_mcu = decode_mcu_DC_first; -// else -// entropy.pub.decode_mcu = decode_mcu_AC_first; -// } else { -// if (is_DC_band) -// entropy.pub.decode_mcu = decode_mcu_DC_refine; -// else -// entropy.pub.decode_mcu = decode_mcu_AC_refine; -// } - - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - /* Make sure requested tables are present, and compute derived tables. - * We may build same derived table more than once, but it's not expensive. - */ - if (is_DC_band) { - if (cinfo.Ah == 0) { /* DC refinement needs no table */ - tbl = compptr.dc_tbl_no; - jpeg_make_d_derived_tbl(cinfo, true, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl()); - } - } else { - tbl = compptr.ac_tbl_no; - jpeg_make_d_derived_tbl(cinfo, false, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl()); - /* remember the single active table */ - entropy.ac_derived_tbl = entropy.derived_tbls[tbl]; - } - /* Initialize DC predictions to 0 */ - entropy.saved.last_dc_val[ci] = 0; - } - - /* Initialize bitread state variables */ - entropy.bitstate.bits_left = 0; - entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ - entropy.insufficient_data = false; - - /* Initialize private state variables */ - entropy.saved.EOBRUN = 0; - - /* Initialize restart counter */ - entropy.restarts_to_go = cinfo.restart_interval; - } - - } - - static final class jpeg_component_info { - /* These values are fixed over the whole image. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOF marker. */ - int component_id; /* identifier for this component (0..255) */ - int component_index; /* its index in SOF or cinfo.comp_info[] */ - int h_samp_factor; /* horizontal sampling factor (1..4) */ - int v_samp_factor; /* vertical sampling factor (1..4) */ - int quant_tbl_no; /* quantization table selector (0..3) */ - /* These values may vary between scans. */ - /* For compression, they must be supplied by parameter setup; */ - /* for decompression, they are read from the SOS marker. */ - /* The decompressor output side may not use these variables. */ - int dc_tbl_no; /* DC entropy table selector (0..3) */ - int ac_tbl_no; /* AC entropy table selector (0..3) */ - - /* Remaining fields should be treated as private by applications. */ - - /* These values are computed during compression or decompression startup: */ - /* Component's size in DCT blocks. - * Any dummy blocks added to complete an MCU are not counted; therefore - * these values do not depend on whether a scan is interleaved or not. - */ - int width_in_blocks; - int height_in_blocks; - /* Size of a DCT block in samples. Always DCTSIZE for compression. - * For decompression this is the size of the output from one DCT block, - * reflecting any scaling we choose to apply during the IDCT step. - * Values of 1,2,4,8 are likely to be supported. Note that different - * components may receive different IDCT scalings. - */ - int DCT_scaled_size; - /* The downsampled dimensions are the component's actual, unpadded number - * of samples at the main buffer (preprocessing/compression interface), thus - * downsampled_width = ceil(image_width * Hi/Hmax) - * and similarly for height. For decompression, IDCT scaling is included, so - * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) - */ - int downsampled_width; /* actual width in samples */ - int downsampled_height; /* actual height in samples */ - /* This flag is used only for decompression. In cases where some of the - * components will be ignored (eg grayscale output from YCbCr image), - * we can skip most computations for the unused components. - */ - bool component_needed; /* do we need the value of this component? */ - - /* These values are computed before starting a scan of the component. */ - /* The decompressor output side may not use these variables. */ - int MCU_width; /* number of blocks per MCU, horizontally */ - int MCU_height; /* number of blocks per MCU, vertically */ - int MCU_blocks; /* MCU_width * MCU_height */ - int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ - int last_col_width; /* # of non-dummy blocks across in last MCU */ - int last_row_height; /* # of non-dummy blocks down in last MCU */ - - /* Saved quantization table for component; null if none yet saved. - * See jdinput.c comments about the need for this information. - * This field is currently used only for decompression. - */ - JQUANT_TBL quant_table; - - /* Private per-component storage for DCT or IDCT subsystem. */ - int[] dct_table; - } - - static final class jpeg_color_quantizer { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, bool is_pre_scan)); -// JMETHOD(void, color_quantize, (j_decompress_ptr cinfo, -// JSAMPARRAY input_buf, JSAMPARRAY output_buf, -// int num_rows)); -// JMETHOD(void, finish_pass, (j_decompress_ptr cinfo)); -// JMETHOD(void, new_color_map, (j_decompress_ptr cinfo)); - - /* Initially allocated colormap is saved here */ - int[][] sv_colormap; /* The color map as a 2-D pixel array */ - int sv_actual; /* number of entries in use */ - - int[][] colorindex; /* Precomputed mapping for speed */ - /* colorindex[i][j] = index of color closest to pixel value j in component i, - * premultiplied as described above. Since colormap indexes must fit into - * JSAMPLEs, the entries of this array will too. - */ - bool is_padded; /* is the colorindex padded for odither? */ - - int[MAX_Q_COMPS] Ncolors;// = new int [MAX_Q_COMPS]; /* # of values alloced to each component */ - - /* Variables for ordered dithering */ - int row_index; /* cur row's vertical index in dither matrix */ -// ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */ - - /* Variables for Floyd-Steinberg dithering */ -// FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */ - bool on_odd_row; - - void start_pass (jpeg_decompress_struct cinfo, bool is_pre_scan) { - error(); - } - } - - static final class jpeg_upsampler { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); -// JMETHOD(void, upsample, (j_decompress_ptr cinfo, -// JSAMPIMAGE input_buf, -// JDIMENSION *in_row_group_ctr, -// JDIMENSION in_row_groups_avail, -// JSAMPARRAY output_buf, -// JDIMENSION *out_row_ctr, -// JDIMENSION out_rows_avail)); - - bool need_context_rows; /* TRUE if need rows above & below */ - - /* Color conversion buffer. When using separate upsampling and color - * conversion steps, this buffer holds one upsampled row group until it - * has been color converted and output. - * Note: we do not allocate any storage for component(s) which are full-size, - * ie do not need rescaling. The corresponding entry of color_buf[] is - * simply set to point to the input data array, thereby avoiding copying. - */ - byte[][][MAX_COMPONENTS] color_buf;// = new byte[MAX_COMPONENTS][][]; - int[MAX_COMPONENTS] color_buf_offset;// = new int[MAX_COMPONENTS]; - - /* Per-component upsampling method pointers */ - int[MAX_COMPONENTS] methods;// = new int[MAX_COMPONENTS]; - - int next_row_out; /* counts rows emitted from color_buf */ - int rows_to_go; /* counts rows remaining in image */ - - /* Height of an input row group for each component. */ - int[MAX_COMPONENTS] rowgroup_height;// = new int[MAX_COMPONENTS]; - - /* These arrays save pixel expansion factors so that int_expand need not - * recompute them each time. They are unused for other upsampling methods. - */ - byte[MAX_COMPONENTS] h_expand;// = new byte[MAX_COMPONENTS]; - byte[MAX_COMPONENTS] v_expand;// = new byte[MAX_COMPONENTS]; - - void start_pass (jpeg_decompress_struct cinfo) { - jpeg_upsampler upsample = cinfo.upsample; - - /* Mark the conversion buffer empty */ - upsample.next_row_out = cinfo.max_v_samp_factor; - /* Initialize total-height counter for detecting bottom of image */ - upsample.rows_to_go = cinfo.output_height; - } - - } - - static final class jpeg_marker_reader { - /* Read a restart marker --- exported for use by entropy decoder only */ -// jpeg_marker_parser_method read_restart_marker; - - /* State of marker reader --- nominally internal, but applications - * supplying COM or APPn handlers might like to know the state. - */ - bool saw_SOI; /* found SOI? */ - bool saw_SOF; /* found SOF? */ - int next_restart_num; /* next restart number expected (0-7) */ - int discarded_bytes; /* # of bytes skipped looking for a marker */ - - /* Application-overridable marker processing methods */ -// jpeg_marker_parser_method process_COM; -// jpeg_marker_parser_method process_APPn[16]; - - /* Limit on marker data length to save for each marker type */ - int length_limit_COM; - int[16] length_limit_APPn;// = new int[16]; - - /* Status of COM/APPn marker saving */ -// jpeg_marker_reader cur_marker; /* null if not processing a marker */ -// int bytes_read; /* data bytes read so far in marker */ - /* Note: cur_marker is not linked into marker_list until it's all read. */ - } - - - static final class jpeg_d_main_controller { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); - int process_data; - - /* Pointer to allocated workspace (M or M+2 row groups). */ - byte[][][MAX_COMPONENTS] buffer;// = new byte[MAX_COMPONENTS][][]; - int[MAX_COMPONENTS] buffer_offset;// = new int[MAX_COMPONENTS]; - - bool buffer_full; /* Have we gotten an iMCU row from decoder? */ - int[1] rowgroup_ctr;// = new int[1]; /* counts row groups output to postprocessor */ - - /* Remaining fields are only used in the context case. */ - - /* These are the master pointers to the funny-order pointer lists. */ - byte[][][][2] xbuffer;// = new byte[2][][][]; /* pointers to weird pointer lists */ - int[][2] xbuffer_offset;// = new int[2][]; - - int whichptr; /* indicates which pointer set is now in use */ - int context_state; /* process_data state machine status */ - int rowgroups_avail; /* row groups available to postprocessor */ - int iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */ - - void start_pass (jpeg_decompress_struct cinfo, int pass_mode) { - jpeg_d_main_controller main = cinfo.main; - - switch (pass_mode) { - case JBUF_PASS_THRU: - if (cinfo.upsample.need_context_rows) { - main.process_data = PROCESS_DATA_CONTEXT_MAIN; - make_funny_pointers(cinfo); /* Create the xbuffer[] lists */ - main.whichptr = 0; /* Read first iMCU row into xbuffer[0] */ - main.context_state = CTX_PREPARE_FOR_IMCU; - main.iMCU_row_ctr = 0; - } else { - /* Simple case with no context needed */ - main.process_data = PROCESS_DATA_SIMPLE_MAIN; - } - main.buffer_full = false; /* Mark buffer empty */ - main.rowgroup_ctr[0] = 0; - break; -// #ifdef QUANT_2PASS_SUPPORTED -// case JBUF_CRANK_DEST: -// /* For last pass of 2-pass quantization, just crank the postprocessor */ -// main.process_data = PROCESS_DATA_CRANK_POST; -// break; -// #endif - default: - error(); -// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); - break; - } - } - - } - - static final class jpeg_decomp_master { -// JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo)); -// JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo)); - - /* State variables made visible to other modules */ - bool is_dummy_pass; - - int pass_number; /* # of passes completed */ - - bool using_merged_upsample; /* true if using merged upsample/cconvert */ - - /* Saved references to initialized quantizer modules, - * in case we need to switch modes. - */ - jpeg_color_quantizer quantizer_1pass; - jpeg_color_quantizer quantizer_2pass; - } - - static final class jpeg_inverse_dct { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); -// /* It is useful to allow each component to have a separate IDCT method. */ -// inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS]; - int[MAX_COMPONENTS] cur_method;// = new int[MAX_COMPONENTS]; - - void start_pass (jpeg_decompress_struct cinfo) { - jpeg_inverse_dct idct = cinfo.idct; - int ci, i; - jpeg_component_info compptr; - int method = 0; -// inverse_DCT_method_ptr method_ptr = NULL; - JQUANT_TBL qtbl; - - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* Select the proper IDCT routine for this component's scaling */ - switch (compptr.DCT_scaled_size) { -// #ifdef IDCT_SCALING_SUPPORTED -// case 1: -// method_ptr = jpeg_idct_1x1; -// method = JDCT_ISLOW; /* jidctred uses islow-style table */ -// break; -// case 2: -// method_ptr = jpeg_idct_2x2; -// method = JDCT_ISLOW; /* jidctred uses islow-style table */ -// break; -// case 4: -// method_ptr = jpeg_idct_4x4; -// method = JDCT_ISLOW; /* jidctred uses islow-style table */ -// break; -// #endif - case DCTSIZE: - switch (cinfo.dct_method) { -// #ifdef DCT_ISLOW_SUPPORTED - case JDCT_ISLOW: -// method_ptr = jpeg_idct_islow; - method = JDCT_ISLOW; - break; -// #endif -// #ifdef DCT_IFAST_SUPPORTED -// case JDCT_IFAST: -// method_ptr = jpeg_idct_ifast; -// method = JDCT_IFAST; -// break; -// #endif -// #ifdef DCT_FLOAT_SUPPORTED -// case JDCT_FLOAT: -// method_ptr = jpeg_idct_float; -// method = JDCT_FLOAT; -// break; -// #endif - default: - error(); -// ERREXIT(cinfo, JERR_NOT_COMPILED); - break; - } - break; - default: - error(); -// ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr.DCT_scaled_size); - break; - } -// idct.inverse_DCT[ci] = method_ptr; - /* Create multiplier table from quant table. - * However, we can skip this if the component is uninteresting - * or if we already built the table. Also, if no quant table - * has yet been saved for the component, we leave the - * multiplier table all-zero; we'll be reading zeroes from the - * coefficient controller's buffer anyway. - */ - if (! compptr.component_needed || idct.cur_method[ci] == method) - continue; - qtbl = compptr.quant_table; - if (qtbl == null) /* happens if no data yet for component */ - continue; - idct.cur_method[ci] = method; - switch (method) { -// #ifdef PROVIDE_ISLOW_TABLES - case JDCT_ISLOW: - { - /* For LL&M IDCT method, multipliers are equal to raw quantization - * coefficients, but are stored as ints to ensure access efficiency. - */ - int[] ismtbl = compptr.dct_table; - for (i = 0; i < DCTSIZE2; i++) { - ismtbl[i] = qtbl.quantval[i]; - } - } - break; -// #endif -// #ifdef DCT_IFAST_SUPPORTED -// case JDCT_IFAST: -// { -// /* For AA&N IDCT method, multipliers are equal to quantization -// * coefficients scaled by scalefactor[row]*scalefactor[col], where -// * scalefactor[0] = 1 -// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 -// * For integer operation, the multiplier table is to be scaled by -// * IFAST_SCALE_BITS. -// */ -// int[] ifmtbl = compptr.dct_table; -// short aanscales[] = { -// /* precomputed values scaled up by 14 bits */ -// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, -// 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, -// 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, -// 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, -// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, -// 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, -// 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, -// 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 -// }; -// SHIFT_TEMPS +// return false; + + } + + bool decode_mcu_AC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) { + phuff_entropy_decoder entropy = this; + int Se = cinfo.Se; + int Al = cinfo.Al; + int s = 0, k, r; + int EOBRUN; + short[] block; +// BITREAD_STATE_VARS; + int get_buffer; + int bits_left; +// bitread_working_state br_state = new bitread_working_state(); + bitread_working_state br_state = br_state_local; + + d_derived_tbl tbl; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo.restart_interval != 0) { + if (entropy.restarts_to_go == 0) + if (! process_restart(cinfo)) + return false; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy.insufficient_data) { + + /* Load up working state. + * We can avoid loading/saving bitread state if in an EOB run. + */ + EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */ + + /* There is always only one block per MCU */ + + if (EOBRUN > 0) /* if it's a band of zeroes... */ + EOBRUN--; /* ...process it now (we do nothing) */ + else { +// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); + br_state.cinfo = cinfo; + br_state.buffer = cinfo.buffer; + br_state.bytes_in_buffer = cinfo.bytes_in_buffer; + br_state.bytes_offset = cinfo.bytes_offset; + get_buffer = entropy.bitstate.get_buffer; + bits_left = entropy.bitstate.bits_left; + + block = MCU_data[0]; + tbl = entropy.ac_derived_tbl; + + for (k = cinfo.Ss; k <= Se; k++) { +// HUFF_DECODE(s, br_state, tbl, return FALSE, label2); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + if (nb != 1) { +// look = PEEK_BITS(HUFF_LOOKAHEAD); + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + + if ((nb = tbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= nb; + s = tbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + r = s >> 4; + s &= 15; + if (s != 0) { + k += r; +// CHECK_BIT_BUFFER(br_state, s, return FALSE); + { + if (bits_left < (s)) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// r = GET_BITS(s); + r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); +// s = HUFF_EXTEND(r, s); + s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); + /* Scale and output coefficient in natural (dezigzagged) order */ + block[jpeg_natural_order[k]] = cast(short) (s << Al); + } else { + if (r == 15) { /* ZRL */ + k += 15; /* skip 15 zeroes in band */ + } else { /* EOBr, run length is 2^r + appended bits */ + EOBRUN = 1 << r; + if (r != 0) { /* EOBr, r > 0 */ +// CHECK_BIT_BUFFER(br_state, r, return FALSE); + { + if (bits_left < (r)) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// r = GET_BITS(r); + r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1)); + EOBRUN += r; + } + EOBRUN--; /* this band is processed at this moment */ + break; /* force end-of-band */ + } + } + } + +// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); + cinfo.buffer = br_state.buffer; + cinfo.bytes_in_buffer = br_state.bytes_in_buffer; + cinfo.bytes_offset = br_state.bytes_offset; + entropy.bitstate.get_buffer = get_buffer; + entropy.bitstate.bits_left = bits_left; + } + + /* Completed MCU, so update state */ + entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */ + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy.restarts_to_go--; + + return true; + } + + bool decode_mcu_DC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) { + phuff_entropy_decoder entropy = this; + int Al = cinfo.Al; + int s = 0, r; + int blkn, ci; + short[] block; +// BITREAD_STATE_VARS; + int get_buffer; + int bits_left; +// bitread_working_state br_state = new bitread_working_state(); + bitread_working_state br_state = br_state_local; + +// savable_state state = new savable_state(); + savable_state state = state_local; + d_derived_tbl tbl; + jpeg_component_info compptr; + + /* Process restart marker if needed; may have to suspend */ + if (cinfo.restart_interval != 0) { + if (entropy.restarts_to_go == 0) + if (! process_restart(cinfo)) + return false; + } + + /* If we've run out of data, just leave the MCU set to zeroes. + * This way, we return uniform gray for the remainder of the segment. + */ + if (! entropy.insufficient_data) { + + /* Load up working state */ +// BITREAD_LOAD_STATE(cinfo,entropy.bitstate); + br_state.cinfo = cinfo; + br_state.buffer = cinfo.buffer; + br_state.bytes_in_buffer = cinfo.bytes_in_buffer; + br_state.bytes_offset = cinfo.bytes_offset; + get_buffer = entropy.bitstate.get_buffer; + bits_left = entropy.bitstate.bits_left; + +// ASSIGN_STATE(state, entropy.saved); + state.EOBRUN = entropy.saved.EOBRUN; + state.last_dc_val[0] = entropy.saved.last_dc_val[0]; + state.last_dc_val[1] = entropy.saved.last_dc_val[1]; + state.last_dc_val[2] = entropy.saved.last_dc_val[2]; + state.last_dc_val[3] = entropy.saved.last_dc_val[3]; + + /* Outer loop handles each block in the MCU */ + + for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) { + block = MCU_data[blkn]; + ci = cinfo.MCU_membership[blkn]; + compptr = cinfo.cur_comp_info[ci]; + tbl = entropy.derived_tbls[compptr.dc_tbl_no]; + + /* Decode a single block's worth of coefficients */ + + /* Section F.2.2.1: decode the DC coefficient difference */ +// HUFF_DECODE(s, br_state, tbl, return FALSE, label1); + { + int nb = 0, look; + if (bits_left < HUFF_LOOKAHEAD) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + if (bits_left < HUFF_LOOKAHEAD) { + nb = 1; +// goto slowlabel; + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + if (nb != 1) { +// look = PEEK_BITS(HUFF_LOOKAHEAD); + look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1)); + + if ((nb = tbl.look_nbits[look]) != 0) { +// DROP_BITS(nb); + bits_left -= nb; + s = tbl.look_sym[look] & 0xFF; + } else { + nb = HUFF_LOOKAHEAD+1; +// slowlabel: + if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } + } + if (s != 0) { +// CHECK_BIT_BUFFER(br_state, s, return FALSE); + { + if (bits_left < (s)) { + if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) { + return false; + } + get_buffer = br_state.get_buffer; bits_left = br_state.bits_left; + } + } +// r = GET_BITS(s); + r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1)); +// s = HUFF_EXTEND(r, s); + s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r)); + } + + /* Convert DC difference to actual value, update last_dc_val */ + s += state.last_dc_val[ci]; + state.last_dc_val[ci] = s; + /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */ + block[0] = cast(short) (s << Al); + } + + /* Completed MCU, so update state */ +// BITREAD_SAVE_STATE(cinfo,entropy.bitstate); + cinfo.buffer = br_state.buffer; + cinfo.bytes_in_buffer = br_state.bytes_in_buffer; + cinfo.bytes_offset = br_state.bytes_offset; + entropy.bitstate.get_buffer = get_buffer; + entropy.bitstate.bits_left = bits_left; +// ASSIGN_STATE(entropy.saved, state); + entropy.saved.EOBRUN = state.EOBRUN; + entropy.saved.last_dc_val[0] = state.last_dc_val[0]; + entropy.saved.last_dc_val[1] = state.last_dc_val[1]; + entropy.saved.last_dc_val[2] = state.last_dc_val[2]; + entropy.saved.last_dc_val[3] = state.last_dc_val[3]; + } + + /* Account for restart interval (no-op if not using restarts) */ + entropy.restarts_to_go--; + + return true; + } + + bool process_restart (jpeg_decompress_struct cinfo) { + phuff_entropy_decoder entropy = this; + int ci; + + /* Throw away any unused bits remaining in bit buffer; */ + /* include any full bytes in next_marker's count of discarded bytes */ + cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8; + entropy.bitstate.bits_left = 0; + + /* Advance past the RSTn marker */ + if (! read_restart_marker (cinfo)) + return false; + + /* Re-initialize DC predictions to 0 */ + for (ci = 0; ci < cinfo.comps_in_scan; ci++) + entropy.saved.last_dc_val[ci] = 0; + /* Re-init EOB run count, too */ + entropy.saved.EOBRUN = 0; + + /* Reset restart counter */ + entropy.restarts_to_go = cinfo.restart_interval; + + /* Reset out-of-data flag, unless read_restart_marker left us smack up + * against a marker. In that case we will end up treating the next data + * segment as empty, and we can avoid producing bogus output pixels by + * leaving the flag set. + */ + if (cinfo.unread_marker == 0) + entropy.insufficient_data = false; + + return true; + } + + void start_pass_phuff_decoder (jpeg_decompress_struct cinfo) { + phuff_entropy_decoder entropy = this; + bool is_DC_band, bad; + int ci, coefi, tbl; + int[] coef_bit_ptr; + jpeg_component_info compptr; + + is_DC_band = (cinfo.Ss == 0); + + /* Validate scan parameters */ + bad = false; + if (is_DC_band) { + if (cinfo.Se != 0) + bad = true; + } else { + /* need not check Ss/Se < 0 since they came from unsigned bytes */ + if (cinfo.Ss > cinfo.Se || cinfo.Se >= DCTSIZE2) + bad = true; + /* AC scans may have only one component */ + if (cinfo.comps_in_scan != 1) + bad = true; + } + if (cinfo.Ah != 0) { + /* Successive approximation refinement scan: must have Al = Ah-1. */ + if (cinfo.Al != cinfo.Ah-1) + bad = true; + } + if (cinfo.Al > 13) /* need not check for < 0 */ + bad = true; + /* Arguably the maximum Al value should be less than 13 for 8-bit precision, + * but the spec doesn't say so, and we try to be liberal about what we + * accept. Note: large Al values could result in out-of-range DC + * coefficients during early scans, leading to bizarre displays due to + * overflows in the IDCT math. But we won't crash. + */ + if (bad) + error(); +// ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al); + /* Update progression status, and verify that scan order is legal. + * Note that inter-scan inconsistencies are treated as warnings + * not fatal errors ... not clear if this is right way to behave. + */ + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + int cindex = cinfo.cur_comp_info[ci].component_index; + coef_bit_ptr = cinfo.coef_bits[cindex]; + if (!is_DC_band && coef_bit_ptr[0] < 0) {/* AC without prior DC scan */ +// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0); + } + for (coefi = cinfo.Ss; coefi <= cinfo.Se; coefi++) { + int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi]; + if (cinfo.Ah != expected) { +// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi); + } + coef_bit_ptr[coefi] = cinfo.Al; + } + } + + /* Select MCU decoding routine */ +// if (cinfo.Ah == 0) { +// if (is_DC_band) +// entropy.pub.decode_mcu = decode_mcu_DC_first; +// else +// entropy.pub.decode_mcu = decode_mcu_AC_first; +// } else { +// if (is_DC_band) +// entropy.pub.decode_mcu = decode_mcu_DC_refine; +// else +// entropy.pub.decode_mcu = decode_mcu_AC_refine; +// } + + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + /* Make sure requested tables are present, and compute derived tables. + * We may build same derived table more than once, but it's not expensive. + */ + if (is_DC_band) { + if (cinfo.Ah == 0) { /* DC refinement needs no table */ + tbl = compptr.dc_tbl_no; + jpeg_make_d_derived_tbl(cinfo, true, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl()); + } + } else { + tbl = compptr.ac_tbl_no; + jpeg_make_d_derived_tbl(cinfo, false, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl()); + /* remember the single active table */ + entropy.ac_derived_tbl = entropy.derived_tbls[tbl]; + } + /* Initialize DC predictions to 0 */ + entropy.saved.last_dc_val[ci] = 0; + } + + /* Initialize bitread state variables */ + entropy.bitstate.bits_left = 0; + entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */ + entropy.insufficient_data = false; + + /* Initialize private state variables */ + entropy.saved.EOBRUN = 0; + + /* Initialize restart counter */ + entropy.restarts_to_go = cinfo.restart_interval; + } + + } + + static final class jpeg_component_info { + /* These values are fixed over the whole image. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOF marker. */ + int component_id; /* identifier for this component (0..255) */ + int component_index; /* its index in SOF or cinfo.comp_info[] */ + int h_samp_factor; /* horizontal sampling factor (1..4) */ + int v_samp_factor; /* vertical sampling factor (1..4) */ + int quant_tbl_no; /* quantization table selector (0..3) */ + /* These values may vary between scans. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOS marker. */ + /* The decompressor output side may not use these variables. */ + int dc_tbl_no; /* DC entropy table selector (0..3) */ + int ac_tbl_no; /* AC entropy table selector (0..3) */ + + /* Remaining fields should be treated as private by applications. */ + + /* These values are computed during compression or decompression startup: */ + /* Component's size in DCT blocks. + * Any dummy blocks added to complete an MCU are not counted; therefore + * these values do not depend on whether a scan is interleaved or not. + */ + int width_in_blocks; + int height_in_blocks; + /* Size of a DCT block in samples. Always DCTSIZE for compression. + * For decompression this is the size of the output from one DCT block, + * reflecting any scaling we choose to apply during the IDCT step. + * Values of 1,2,4,8 are likely to be supported. Note that different + * components may receive different IDCT scalings. + */ + int DCT_scaled_size; + /* The downsampled dimensions are the component's actual, unpadded number + * of samples at the main buffer (preprocessing/compression interface), thus + * downsampled_width = ceil(image_width * Hi/Hmax) + * and similarly for height. For decompression, IDCT scaling is included, so + * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) + */ + int downsampled_width; /* actual width in samples */ + int downsampled_height; /* actual height in samples */ + /* This flag is used only for decompression. In cases where some of the + * components will be ignored (eg grayscale output from YCbCr image), + * we can skip most computations for the unused components. + */ + bool component_needed; /* do we need the value of this component? */ + + /* These values are computed before starting a scan of the component. */ + /* The decompressor output side may not use these variables. */ + int MCU_width; /* number of blocks per MCU, horizontally */ + int MCU_height; /* number of blocks per MCU, vertically */ + int MCU_blocks; /* MCU_width * MCU_height */ + int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ + int last_col_width; /* # of non-dummy blocks across in last MCU */ + int last_row_height; /* # of non-dummy blocks down in last MCU */ + + /* Saved quantization table for component; null if none yet saved. + * See jdinput.c comments about the need for this information. + * This field is currently used only for decompression. + */ + JQUANT_TBL quant_table; + + /* Private per-component storage for DCT or IDCT subsystem. */ + int[] dct_table; + } + + static final class jpeg_color_quantizer { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, bool is_pre_scan)); +// JMETHOD(void, color_quantize, (j_decompress_ptr cinfo, +// JSAMPARRAY input_buf, JSAMPARRAY output_buf, +// int num_rows)); +// JMETHOD(void, finish_pass, (j_decompress_ptr cinfo)); +// JMETHOD(void, new_color_map, (j_decompress_ptr cinfo)); + + /* Initially allocated colormap is saved here */ + int[][] sv_colormap; /* The color map as a 2-D pixel array */ + int sv_actual; /* number of entries in use */ + + int[][] colorindex; /* Precomputed mapping for speed */ + /* colorindex[i][j] = index of color closest to pixel value j in component i, + * premultiplied as described above. Since colormap indexes must fit into + * JSAMPLEs, the entries of this array will too. + */ + bool is_padded; /* is the colorindex padded for odither? */ + + int[MAX_Q_COMPS] Ncolors;// = new int [MAX_Q_COMPS]; /* # of values alloced to each component */ + + /* Variables for ordered dithering */ + int row_index; /* cur row's vertical index in dither matrix */ +// ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */ + + /* Variables for Floyd-Steinberg dithering */ +// FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */ + bool on_odd_row; + + void start_pass (jpeg_decompress_struct cinfo, bool is_pre_scan) { + error(); + } + } + + static final class jpeg_upsampler { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); +// JMETHOD(void, upsample, (j_decompress_ptr cinfo, +// JSAMPIMAGE input_buf, +// JDIMENSION *in_row_group_ctr, +// JDIMENSION in_row_groups_avail, +// JSAMPARRAY output_buf, +// JDIMENSION *out_row_ctr, +// JDIMENSION out_rows_avail)); + + bool need_context_rows; /* TRUE if need rows above & below */ + + /* Color conversion buffer. When using separate upsampling and color + * conversion steps, this buffer holds one upsampled row group until it + * has been color converted and output. + * Note: we do not allocate any storage for component(s) which are full-size, + * ie do not need rescaling. The corresponding entry of color_buf[] is + * simply set to point to the input data array, thereby avoiding copying. + */ + byte[][][MAX_COMPONENTS] color_buf;// = new byte[MAX_COMPONENTS][][]; + int[MAX_COMPONENTS] color_buf_offset;// = new int[MAX_COMPONENTS]; + + /* Per-component upsampling method pointers */ + int[MAX_COMPONENTS] methods;// = new int[MAX_COMPONENTS]; + + int next_row_out; /* counts rows emitted from color_buf */ + int rows_to_go; /* counts rows remaining in image */ + + /* Height of an input row group for each component. */ + int[MAX_COMPONENTS] rowgroup_height;// = new int[MAX_COMPONENTS]; + + /* These arrays save pixel expansion factors so that int_expand need not + * recompute them each time. They are unused for other upsampling methods. + */ + byte[MAX_COMPONENTS] h_expand;// = new byte[MAX_COMPONENTS]; + byte[MAX_COMPONENTS] v_expand;// = new byte[MAX_COMPONENTS]; + + void start_pass (jpeg_decompress_struct cinfo) { + jpeg_upsampler upsample = cinfo.upsample; + + /* Mark the conversion buffer empty */ + upsample.next_row_out = cinfo.max_v_samp_factor; + /* Initialize total-height counter for detecting bottom of image */ + upsample.rows_to_go = cinfo.output_height; + } + + } + + static final class jpeg_marker_reader { + /* Read a restart marker --- exported for use by entropy decoder only */ +// jpeg_marker_parser_method read_restart_marker; + + /* State of marker reader --- nominally internal, but applications + * supplying COM or APPn handlers might like to know the state. + */ + bool saw_SOI; /* found SOI? */ + bool saw_SOF; /* found SOF? */ + int next_restart_num; /* next restart number expected (0-7) */ + int discarded_bytes; /* # of bytes skipped looking for a marker */ + + /* Application-overridable marker processing methods */ +// jpeg_marker_parser_method process_COM; +// jpeg_marker_parser_method process_APPn[16]; + + /* Limit on marker data length to save for each marker type */ + int length_limit_COM; + int[16] length_limit_APPn;// = new int[16]; + + /* Status of COM/APPn marker saving */ +// jpeg_marker_reader cur_marker; /* null if not processing a marker */ +// int bytes_read; /* data bytes read so far in marker */ + /* Note: cur_marker is not linked into marker_list until it's all read. */ + } + + + static final class jpeg_d_main_controller { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); + int process_data; + + /* Pointer to allocated workspace (M or M+2 row groups). */ + byte[][][MAX_COMPONENTS] buffer;// = new byte[MAX_COMPONENTS][][]; + int[MAX_COMPONENTS] buffer_offset;// = new int[MAX_COMPONENTS]; + + bool buffer_full; /* Have we gotten an iMCU row from decoder? */ + int[1] rowgroup_ctr;// = new int[1]; /* counts row groups output to postprocessor */ + + /* Remaining fields are only used in the context case. */ + + /* These are the master pointers to the funny-order pointer lists. */ + byte[][][][2] xbuffer;// = new byte[2][][][]; /* pointers to weird pointer lists */ + int[][2] xbuffer_offset;// = new int[2][]; + + int whichptr; /* indicates which pointer set is now in use */ + int context_state; /* process_data state machine status */ + int rowgroups_avail; /* row groups available to postprocessor */ + int iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */ + + void start_pass (jpeg_decompress_struct cinfo, int pass_mode) { + jpeg_d_main_controller main = cinfo.main; + + switch (pass_mode) { + case JBUF_PASS_THRU: + if (cinfo.upsample.need_context_rows) { + main.process_data = PROCESS_DATA_CONTEXT_MAIN; + make_funny_pointers(cinfo); /* Create the xbuffer[] lists */ + main.whichptr = 0; /* Read first iMCU row into xbuffer[0] */ + main.context_state = CTX_PREPARE_FOR_IMCU; + main.iMCU_row_ctr = 0; + } else { + /* Simple case with no context needed */ + main.process_data = PROCESS_DATA_SIMPLE_MAIN; + } + main.buffer_full = false; /* Mark buffer empty */ + main.rowgroup_ctr[0] = 0; + break; +// #ifdef QUANT_2PASS_SUPPORTED +// case JBUF_CRANK_DEST: +// /* For last pass of 2-pass quantization, just crank the postprocessor */ +// main.process_data = PROCESS_DATA_CRANK_POST; +// break; +// #endif + default: + error(); +// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } + } + + } + + static final class jpeg_decomp_master { +// JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo)); +// JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo)); + + /* State variables made visible to other modules */ + bool is_dummy_pass; + + int pass_number; /* # of passes completed */ + + bool using_merged_upsample; /* true if using merged upsample/cconvert */ + + /* Saved references to initialized quantizer modules, + * in case we need to switch modes. + */ + jpeg_color_quantizer quantizer_1pass; + jpeg_color_quantizer quantizer_2pass; + } + + static final class jpeg_inverse_dct { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); +// /* It is useful to allow each component to have a separate IDCT method. */ +// inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS]; + int[MAX_COMPONENTS] cur_method;// = new int[MAX_COMPONENTS]; + + void start_pass (jpeg_decompress_struct cinfo) { + jpeg_inverse_dct idct = cinfo.idct; + int ci, i; + jpeg_component_info compptr; + int method = 0; +// inverse_DCT_method_ptr method_ptr = NULL; + JQUANT_TBL qtbl; + + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* Select the proper IDCT routine for this component's scaling */ + switch (compptr.DCT_scaled_size) { +// #ifdef IDCT_SCALING_SUPPORTED +// case 1: +// method_ptr = jpeg_idct_1x1; +// method = JDCT_ISLOW; /* jidctred uses islow-style table */ +// break; +// case 2: +// method_ptr = jpeg_idct_2x2; +// method = JDCT_ISLOW; /* jidctred uses islow-style table */ +// break; +// case 4: +// method_ptr = jpeg_idct_4x4; +// method = JDCT_ISLOW; /* jidctred uses islow-style table */ +// break; +// #endif + case DCTSIZE: + switch (cinfo.dct_method) { +// #ifdef DCT_ISLOW_SUPPORTED + case JDCT_ISLOW: +// method_ptr = jpeg_idct_islow; + method = JDCT_ISLOW; + break; +// #endif +// #ifdef DCT_IFAST_SUPPORTED +// case JDCT_IFAST: +// method_ptr = jpeg_idct_ifast; +// method = JDCT_IFAST; +// break; +// #endif +// #ifdef DCT_FLOAT_SUPPORTED +// case JDCT_FLOAT: +// method_ptr = jpeg_idct_float; +// method = JDCT_FLOAT; +// break; +// #endif + default: + error(); +// ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + break; + default: + error(); +// ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr.DCT_scaled_size); + break; + } +// idct.inverse_DCT[ci] = method_ptr; + /* Create multiplier table from quant table. + * However, we can skip this if the component is uninteresting + * or if we already built the table. Also, if no quant table + * has yet been saved for the component, we leave the + * multiplier table all-zero; we'll be reading zeroes from the + * coefficient controller's buffer anyway. + */ + if (! compptr.component_needed || idct.cur_method[ci] == method) + continue; + qtbl = compptr.quant_table; + if (qtbl == null) /* happens if no data yet for component */ + continue; + idct.cur_method[ci] = method; + switch (method) { +// #ifdef PROVIDE_ISLOW_TABLES + case JDCT_ISLOW: + { + /* For LL&M IDCT method, multipliers are equal to raw quantization + * coefficients, but are stored as ints to ensure access efficiency. + */ + int[] ismtbl = compptr.dct_table; + for (i = 0; i < DCTSIZE2; i++) { + ismtbl[i] = qtbl.quantval[i]; + } + } + break; +// #endif +// #ifdef DCT_IFAST_SUPPORTED +// case JDCT_IFAST: +// { +// /* For AA&N IDCT method, multipliers are equal to quantization +// * coefficients scaled by scalefactor[row]*scalefactor[col], where +// * scalefactor[0] = 1 +// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 +// * For integer operation, the multiplier table is to be scaled by +// * IFAST_SCALE_BITS. +// */ +// int[] ifmtbl = compptr.dct_table; +// short aanscales[] = { +// /* precomputed values scaled up by 14 bits */ +// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, +// 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, +// 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, +// 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, +// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, +// 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, +// 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, +// 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 +// }; +// SHIFT_TEMPS // -// for (i = 0; i < DCTSIZE2; i++) { -// ifmtbl[i] = DESCALE(MULTIPLY16V16( qtbl.quantval[i], aanscales[i]), CONST_BITS-IFAST_SCALE_BITS); -// } -// } -// break; -// #endif -// #ifdef DCT_FLOAT_SUPPORTED -// case JDCT_FLOAT: -// { -// /* For float AA&N IDCT method, multipliers are equal to quantization -// * coefficients scaled by scalefactor[row]*scalefactor[col], where -// * scalefactor[0] = 1 -// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 -// */ -// FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr.dct_table; -// int row, col; -// static const double aanscalefactor[DCTSIZE] = { -// 1.0, 1.387039845, 1.306562965, 1.175875602, -// 1.0, 0.785694958, 0.541196100, 0.275899379 -// }; +// for (i = 0; i < DCTSIZE2; i++) { +// ifmtbl[i] = DESCALE(MULTIPLY16V16( qtbl.quantval[i], aanscales[i]), CONST_BITS-IFAST_SCALE_BITS); +// } +// } +// break; +// #endif +// #ifdef DCT_FLOAT_SUPPORTED +// case JDCT_FLOAT: +// { +// /* For float AA&N IDCT method, multipliers are equal to quantization +// * coefficients scaled by scalefactor[row]*scalefactor[col], where +// * scalefactor[0] = 1 +// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 +// */ +// FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr.dct_table; +// int row, col; +// static const double aanscalefactor[DCTSIZE] = { +// 1.0, 1.387039845, 1.306562965, 1.175875602, +// 1.0, 0.785694958, 0.541196100, 0.275899379 +// }; // -// i = 0; -// for (row = 0; row < DCTSIZE; row++) { -// for (col = 0; col < DCTSIZE; col++) { -// fmtbl[i] = (FLOAT_MULT_TYPE) -// ((double) qtbl.quantval[i] * -// aanscalefactor[row] * aanscalefactor[col]); -// i++; -// } -// } -// } -// break; -// #endif - default: - error(); -// ERREXIT(cinfo, JERR_NOT_COMPILED); - break; - } - } - } - } - - static final class jpeg_input_controller { - int consume_input; - bool has_multiple_scans; /* True if file has multiple scans */ - bool eoi_reached; - - bool inheaders; /* true until first SOS is reached */ - } - - static final class jpeg_color_deconverter { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); - int color_convert; - - /* Private state for YCC.RGB conversion */ - int[] Cr_r_tab; /* => table for Cr to R conversion */ - int[] Cb_b_tab; /* => table for Cb to B conversion */ - int[] Cr_g_tab; /* => table for Cr to G conversion */ - int[] Cb_g_tab; /* => table for Cb to G conversion */ - - void start_pass (jpeg_decompress_struct cinfo) { - /* no work needed */ - } - - } - - static final class jpeg_d_post_controller { -// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); - int post_process_data; - - /* Color quantization source buffer: this holds output data from - * the upsample/color conversion step to be passed to the quantizer. - * For two-pass color quantization, we need a full-image buffer; - * for one-pass operation, a strip buffer is sufficient. - */ - int[] whole_image; /* virtual array, or NULL if one-pass */ - int[][] buffer; /* strip buffer, or current strip of virtual */ - int strip_height; /* buffer size in rows */ - /* for two-pass mode only: */ - int starting_row; /* row # of first row in current strip */ - int next_row; /* index of next row to fill/empty in strip */ - - void start_pass (jpeg_decompress_struct cinfo, int pass_mode) { - jpeg_d_post_controller post = cinfo.post; - - switch (pass_mode) { - case JBUF_PASS_THRU: - if (cinfo.quantize_colors) { - error(SWT.ERROR_NOT_IMPLEMENTED); -// /* Single-pass processing with color quantization. */ -// post.post_process_data = POST_PROCESS_1PASS; -// /* We could be doing buffered-image output before starting a 2-pass -// * color quantization; in that case, jinit_d_post_controller did not -// * allocate a strip buffer. Use the virtual-array buffer as workspace. -// */ -// if (post.buffer == null) { -// post.buffer = (*cinfo.mem.access_virt_sarray) -// ((j_common_ptr) cinfo, post.whole_image, -// (JDIMENSION) 0, post.strip_height, TRUE); -// } - } else { - /* For single-pass processing without color quantization, - * I have no work to do; just call the upsampler directly. - */ - post.post_process_data = POST_PROCESS_DATA_UPSAMPLE; - } - break; -// #ifdef QUANT_2PASS_SUPPORTED -// case JBUF_SAVE_AND_PASS: -// /* First pass of 2-pass quantization */ -// if (post.whole_image == NULL) -// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); -// post.pub.post_process_data = post_process_prepass; -// break; -// case JBUF_CRANK_DEST: -// /* Second pass of 2-pass quantization */ -// if (post.whole_image == NULL) -// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); -// post.pub.post_process_data = post_process_2pass; -// break; -// #endif /* QUANT_2PASS_SUPPORTED */ - default: - error(); -// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); - break; - } - post.starting_row = post.next_row = 0; - } - - } - - static final class jpeg_decompress_struct { -// jpeg_error_mgr * err; /* Error handler module */\ -// struct jpeg_memory_mgr * mem; /* Memory manager module */\ -// struct jpeg_progress_mgr * progress; /* Progress monitor, or null if none */\ -// void * client_data; /* Available for use by application */\ - bool is_decompressor; /* So common code can tell which is which */ - int global_state; /* For checking call sequence validity */ - -// /* Source of compressed data */ -// struct jpeg_source_mgr * src; - InputStream inputStream; - byte[] buffer; - int bytes_in_buffer; - int bytes_offset; - bool start_of_file; - - /* Basic description of image --- filled in by jpeg_read_header(). */ - /* Application may inspect these values to decide how to process image. */ - - int image_width; /* nominal image width (from SOF marker) */ - int image_height; /* nominal image height */ - int num_components; /* # of color components in JPEG image */ - int jpeg_color_space; /* colorspace of JPEG image */ - - /* Decompression processing parameters --- these fields must be set before - * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes - * them to default values. - */ - - int out_color_space; /* colorspace for output */ - - int scale_num, scale_denom; /* fraction by which to scale image */ - - double output_gamma; /* image gamma wanted in output */ - - bool buffered_image; /* true=multiple output passes */ - bool raw_data_out; /* true=downsampled data wanted */ - - int dct_method; /* IDCT algorithm selector */ - bool do_fancy_upsampling; /* true=apply fancy upsampling */ - bool do_block_smoothing; /* true=apply interblock smoothing */ - - bool quantize_colors; /* true=colormapped output wanted */ - /* the following are ignored if not quantize_colors: */ - int dither_mode; /* type of color dithering to use */ - bool two_pass_quantize; /* true=use two-pass color quantization */ - int desired_number_of_colors; /* max # colors to use in created colormap */ - /* these are significant only in buffered-image mode: */ - bool enable_1pass_quant; /* enable future use of 1-pass quantizer */ - bool enable_external_quant;/* enable future use of external colormap */ - bool enable_2pass_quant; /* enable future use of 2-pass quantizer */ - - /* Description of actual output image that will be returned to application. - * These fields are computed by jpeg_start_decompress(). - * You can also use jpeg_calc_output_dimensions() to determine these values - * in advance of calling jpeg_start_decompress(). - */ - - int output_width; /* scaled image width */ - int output_height; /* scaled image height */ - int out_color_components; /* # of color components in out_color_space */ - int output_components; /* # of color components returned */ - /* output_components is 1 (a colormap index) when quantizing colors; - * otherwise it equals out_color_components. - */ - int rec_outbuf_height; /* min recommended height of scanline buffer */ - /* If the buffer passed to jpeg_read_scanlines() is less than this many rows - * high, space and time will be wasted due to unnecessary data copying. - * Usually rec_outbuf_height will be 1 or 2, at most 4. - */ - - /* When quantizing colors, the output colormap is described by these fields. - * The application can supply a colormap by setting colormap non-null before - * calling jpeg_start_decompress; otherwise a colormap is created during - * jpeg_start_decompress or jpeg_start_output. - * The map has out_color_components rows and actual_number_of_colors columns. - */ - int actual_number_of_colors; /* number of entries in use */ - int[] colormap; /* The color map as a 2-D pixel array */ - - /* State variables: these variables indicate the progress of decompression. - * The application may examine these but must not modify them. - */ - - /* Row index of next scanline to be read from jpeg_read_scanlines(). - * Application may use this to control its processing loop, e.g., - * "while (output_scanline < output_height)". - */ - int output_scanline; /* 0 .. output_height-1 */ - - /* Current input scan number and number of iMCU rows completed in scan. - * These indicate the progress of the decompressor input side. - */ - int input_scan_number; /* Number of SOS markers seen so far */ - int input_iMCU_row; /* Number of iMCU rows completed */ - - /* The "output scan number" is the notional scan being displayed by the - * output side. The decompressor will not allow output scan/row number - * to get ahead of input scan/row, but it can fall arbitrarily far behind. - */ - int output_scan_number; /* Nominal scan number being displayed */ - int output_iMCU_row; /* Number of iMCU rows read */ - - /* Current progression status. coef_bits[c][i] indicates the precision - * with which component c's DCT coefficient i (in zigzag order) is known. - * It is -1 when no data has yet been received, otherwise it is the point - * transform (shift) value for the most recent scan of the coefficient - * (thus, 0 at completion of the progression). - * This pointer is null when reading a non-progressive file. - */ - int[][] coef_bits; /* -1 or current Al value for each coef */ - - /* Internal JPEG parameters --- the application usually need not look at - * these fields. Note that the decompressor output side may not use - * any parameters that can change between scans. - */ - - /* Quantization and Huffman tables are carried forward across input - * datastreams when processing abbreviated JPEG datastreams. - */ - - JQUANT_TBL[NUM_QUANT_TBLS] quant_tbl_ptrs;// = new JQUANT_TBL[NUM_QUANT_TBLS]; - /* ptrs to coefficient quantization tables, or null if not defined */ - - JHUFF_TBL[NUM_HUFF_TBLS] dc_huff_tbl_ptrs;// = new JHUFF_TBL[NUM_HUFF_TBLS]; - JHUFF_TBL[NUM_HUFF_TBLS] ac_huff_tbl_ptrs;// = new JHUFF_TBL[NUM_HUFF_TBLS]; - /* ptrs to Huffman coding tables, or null if not defined */ - - /* These parameters are never carried across datastreams, since they - * are given in SOF/SOS markers or defined to be reset by SOI. - */ - - int data_precision; /* bits of precision in image data */ - - jpeg_component_info[] comp_info; - /* comp_info[i] describes component that appears i'th in SOF */ - - bool progressive_mode; /* true if SOFn specifies progressive mode */ - bool arith_code; /* true=arithmetic coding, false=Huffman */ - - byte[NUM_ARITH_TBLS] arith_dc_L;// = new byte[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ - byte[NUM_ARITH_TBLS] arith_dc_U;// = new byte[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ - byte[NUM_ARITH_TBLS] arith_ac_K;// = new byte[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ - - int restart_interval; /* MCUs per restart interval, or 0 for no restart */ - - /* These fields record data obtained from optional markers recognized by - * the JPEG library. - */ - bool saw_JFIF_marker; /* true iff a JFIF APP0 marker was found */ - /* Data copied from JFIF marker; only valid if saw_JFIF_marker is true: */ - byte JFIF_major_version; /* JFIF version number */ - byte JFIF_minor_version; - byte density_unit; /* JFIF code for pixel size units */ - short X_density; /* Horizontal pixel density */ - short Y_density; /* Vertical pixel density */ - bool saw_Adobe_marker; /* true iff an Adobe APP14 marker was found */ - byte Adobe_transform; /* Color transform code from Adobe marker */ - - bool CCIR601_sampling; /* true=first samples are cosited */ - - /* Aside from the specific data retained from APPn markers known to the - * library, the uninterpreted contents of any or all APPn and COM markers - * can be saved in a list for examination by the application. - */ - jpeg_marker_reader marker_list; /* Head of list of saved markers */ - - /* Remaining fields are known throughout decompressor, but generally - * should not be touched by a surrounding application. - */ - - /* - * These fields are computed during decompression startup - */ - int max_h_samp_factor; /* largest h_samp_factor */ - int max_v_samp_factor; /* largest v_samp_factor */ - - int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ - - int total_iMCU_rows; /* # of iMCU rows in image */ - /* The coefficient controller's input and output progress is measured in - * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows - * in fully interleaved JPEG scans, but are used whether the scan is - * interleaved or not. We define an iMCU row as v_samp_factor DCT block - * rows of each component. Therefore, the IDCT output contains - * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. - */ - - byte[] sample_range_limit; /* table for fast range-limiting */ - int sample_range_limit_offset; - - /* - * These fields are valid during any one scan. - * They describe the components and MCUs actually appearing in the scan. - * Note that the decompressor output side must not use these fields. - */ - int comps_in_scan; /* # of JPEG components in this scan */ - jpeg_component_info[MAX_COMPS_IN_SCAN] cur_comp_info;// = new jpeg_component_info[MAX_COMPS_IN_SCAN]; - /* *cur_comp_info[i] describes component that appears i'th in SOS */ - - int MCUs_per_row; /* # of MCUs across the image */ - int MCU_rows_in_scan; /* # of MCU rows in the image */ - - int blocks_in_MCU; /* # of DCT blocks per MCU */ - int[D_MAX_BLOCKS_IN_MCU] MCU_membership;// = new int[D_MAX_BLOCKS_IN_MCU]; - /* MCU_membership[i] is index in cur_comp_info of component owning */ - /* i'th block in an MCU */ - - int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ - - /* This field is shared between entropy decoder and marker parser. - * It is either zero or the code of a JPEG marker that has been - * read from the data source, but has not yet been processed. - */ - int unread_marker; - - int[DCTSIZE2] workspace;// = new int[DCTSIZE2]; - int[1] row_ctr;// = new int[1]; - - /* - * Links to decompression subobjects (methods, private variables of modules) - */ - jpeg_decomp_master master; - jpeg_d_main_controller main; - jpeg_d_coef_controller coef; - jpeg_d_post_controller post; - jpeg_input_controller inputctl; - jpeg_marker_reader marker; - jpeg_entropy_decoder entropy; - jpeg_inverse_dct idct; - jpeg_upsampler upsample; - jpeg_color_deconverter cconvert; - jpeg_color_quantizer cquantize; - } +// i = 0; +// for (row = 0; row < DCTSIZE; row++) { +// for (col = 0; col < DCTSIZE; col++) { +// fmtbl[i] = (FLOAT_MULT_TYPE) +// ((double) qtbl.quantval[i] * +// aanscalefactor[row] * aanscalefactor[col]); +// i++; +// } +// } +// } +// break; +// #endif + default: + error(); +// ERREXIT(cinfo, JERR_NOT_COMPILED); + break; + } + } + } + } + + static final class jpeg_input_controller { + int consume_input; + bool has_multiple_scans; /* True if file has multiple scans */ + bool eoi_reached; + + bool inheaders; /* true until first SOS is reached */ + } + + static final class jpeg_color_deconverter { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo)); + int color_convert; + + /* Private state for YCC.RGB conversion */ + int[] Cr_r_tab; /* => table for Cr to R conversion */ + int[] Cb_b_tab; /* => table for Cb to B conversion */ + int[] Cr_g_tab; /* => table for Cr to G conversion */ + int[] Cb_g_tab; /* => table for Cb to G conversion */ + + void start_pass (jpeg_decompress_struct cinfo) { + /* no work needed */ + } + + } + + static final class jpeg_d_post_controller { +// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)); + int post_process_data; + + /* Color quantization source buffer: this holds output data from + * the upsample/color conversion step to be passed to the quantizer. + * For two-pass color quantization, we need a full-image buffer; + * for one-pass operation, a strip buffer is sufficient. + */ + int[] whole_image; /* virtual array, or NULL if one-pass */ + int[][] buffer; /* strip buffer, or current strip of virtual */ + int strip_height; /* buffer size in rows */ + /* for two-pass mode only: */ + int starting_row; /* row # of first row in current strip */ + int next_row; /* index of next row to fill/empty in strip */ + + void start_pass (jpeg_decompress_struct cinfo, int pass_mode) { + jpeg_d_post_controller post = cinfo.post; + + switch (pass_mode) { + case JBUF_PASS_THRU: + if (cinfo.quantize_colors) { + error(SWT.ERROR_NOT_IMPLEMENTED); +// /* Single-pass processing with color quantization. */ +// post.post_process_data = POST_PROCESS_1PASS; +// /* We could be doing buffered-image output before starting a 2-pass +// * color quantization; in that case, jinit_d_post_controller did not +// * allocate a strip buffer. Use the virtual-array buffer as workspace. +// */ +// if (post.buffer == null) { +// post.buffer = (*cinfo.mem.access_virt_sarray) +// ((j_common_ptr) cinfo, post.whole_image, +// (JDIMENSION) 0, post.strip_height, TRUE); +// } + } else { + /* For single-pass processing without color quantization, + * I have no work to do; just call the upsampler directly. + */ + post.post_process_data = POST_PROCESS_DATA_UPSAMPLE; + } + break; +// #ifdef QUANT_2PASS_SUPPORTED +// case JBUF_SAVE_AND_PASS: +// /* First pass of 2-pass quantization */ +// if (post.whole_image == NULL) +// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +// post.pub.post_process_data = post_process_prepass; +// break; +// case JBUF_CRANK_DEST: +// /* Second pass of 2-pass quantization */ +// if (post.whole_image == NULL) +// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); +// post.pub.post_process_data = post_process_2pass; +// break; +// #endif /* QUANT_2PASS_SUPPORTED */ + default: + error(); +// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE); + break; + } + post.starting_row = post.next_row = 0; + } + + } + + static final class jpeg_decompress_struct { +// jpeg_error_mgr * err; /* Error handler module */\ +// struct jpeg_memory_mgr * mem; /* Memory manager module */\ +// struct jpeg_progress_mgr * progress; /* Progress monitor, or null if none */\ +// void * client_data; /* Available for use by application */\ + bool is_decompressor; /* So common code can tell which is which */ + int global_state; /* For checking call sequence validity */ + +// /* Source of compressed data */ +// struct jpeg_source_mgr * src; + InputStream inputStream; + byte[] buffer; + int bytes_in_buffer; + int bytes_offset; + bool start_of_file; + + /* Basic description of image --- filled in by jpeg_read_header(). */ + /* Application may inspect these values to decide how to process image. */ + + int image_width; /* nominal image width (from SOF marker) */ + int image_height; /* nominal image height */ + int num_components; /* # of color components in JPEG image */ + int jpeg_color_space; /* colorspace of JPEG image */ + + /* Decompression processing parameters --- these fields must be set before + * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes + * them to default values. + */ + + int out_color_space; /* colorspace for output */ + + int scale_num, scale_denom; /* fraction by which to scale image */ + + double output_gamma; /* image gamma wanted in output */ + + bool buffered_image; /* true=multiple output passes */ + bool raw_data_out; /* true=downsampled data wanted */ + + int dct_method; /* IDCT algorithm selector */ + bool do_fancy_upsampling; /* true=apply fancy upsampling */ + bool do_block_smoothing; /* true=apply interblock smoothing */ + + bool quantize_colors; /* true=colormapped output wanted */ + /* the following are ignored if not quantize_colors: */ + int dither_mode; /* type of color dithering to use */ + bool two_pass_quantize; /* true=use two-pass color quantization */ + int desired_number_of_colors; /* max # colors to use in created colormap */ + /* these are significant only in buffered-image mode: */ + bool enable_1pass_quant; /* enable future use of 1-pass quantizer */ + bool enable_external_quant;/* enable future use of external colormap */ + bool enable_2pass_quant; /* enable future use of 2-pass quantizer */ + + /* Description of actual output image that will be returned to application. + * These fields are computed by jpeg_start_decompress(). + * You can also use jpeg_calc_output_dimensions() to determine these values + * in advance of calling jpeg_start_decompress(). + */ + + int output_width; /* scaled image width */ + int output_height; /* scaled image height */ + int out_color_components; /* # of color components in out_color_space */ + int output_components; /* # of color components returned */ + /* output_components is 1 (a colormap index) when quantizing colors; + * otherwise it equals out_color_components. + */ + int rec_outbuf_height; /* min recommended height of scanline buffer */ + /* If the buffer passed to jpeg_read_scanlines() is less than this many rows + * high, space and time will be wasted due to unnecessary data copying. + * Usually rec_outbuf_height will be 1 or 2, at most 4. + */ + + /* When quantizing colors, the output colormap is described by these fields. + * The application can supply a colormap by setting colormap non-null before + * calling jpeg_start_decompress; otherwise a colormap is created during + * jpeg_start_decompress or jpeg_start_output. + * The map has out_color_components rows and actual_number_of_colors columns. + */ + int actual_number_of_colors; /* number of entries in use */ + int[] colormap; /* The color map as a 2-D pixel array */ + + /* State variables: these variables indicate the progress of decompression. + * The application may examine these but must not modify them. + */ + + /* Row index of next scanline to be read from jpeg_read_scanlines(). + * Application may use this to control its processing loop, e.g., + * "while (output_scanline < output_height)". + */ + int output_scanline; /* 0 .. output_height-1 */ + + /* Current input scan number and number of iMCU rows completed in scan. + * These indicate the progress of the decompressor input side. + */ + int input_scan_number; /* Number of SOS markers seen so far */ + int input_iMCU_row; /* Number of iMCU rows completed */ + + /* The "output scan number" is the notional scan being displayed by the + * output side. The decompressor will not allow output scan/row number + * to get ahead of input scan/row, but it can fall arbitrarily far behind. + */ + int output_scan_number; /* Nominal scan number being displayed */ + int output_iMCU_row; /* Number of iMCU rows read */ + + /* Current progression status. coef_bits[c][i] indicates the precision + * with which component c's DCT coefficient i (in zigzag order) is known. + * It is -1 when no data has yet been received, otherwise it is the point + * transform (shift) value for the most recent scan of the coefficient + * (thus, 0 at completion of the progression). + * This pointer is null when reading a non-progressive file. + */ + int[][] coef_bits; /* -1 or current Al value for each coef */ + + /* Internal JPEG parameters --- the application usually need not look at + * these fields. Note that the decompressor output side may not use + * any parameters that can change between scans. + */ + + /* Quantization and Huffman tables are carried forward across input + * datastreams when processing abbreviated JPEG datastreams. + */ + + JQUANT_TBL[NUM_QUANT_TBLS] quant_tbl_ptrs;// = new JQUANT_TBL[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or null if not defined */ + + JHUFF_TBL[NUM_HUFF_TBLS] dc_huff_tbl_ptrs;// = new JHUFF_TBL[NUM_HUFF_TBLS]; + JHUFF_TBL[NUM_HUFF_TBLS] ac_huff_tbl_ptrs;// = new JHUFF_TBL[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or null if not defined */ + + /* These parameters are never carried across datastreams, since they + * are given in SOF/SOS markers or defined to be reset by SOI. + */ + + int data_precision; /* bits of precision in image data */ + + jpeg_component_info[] comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + bool progressive_mode; /* true if SOFn specifies progressive mode */ + bool arith_code; /* true=arithmetic coding, false=Huffman */ + + byte[NUM_ARITH_TBLS] arith_dc_L;// = new byte[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + byte[NUM_ARITH_TBLS] arith_dc_U;// = new byte[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + byte[NUM_ARITH_TBLS] arith_ac_K;// = new byte[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + int restart_interval; /* MCUs per restart interval, or 0 for no restart */ + + /* These fields record data obtained from optional markers recognized by + * the JPEG library. + */ + bool saw_JFIF_marker; /* true iff a JFIF APP0 marker was found */ + /* Data copied from JFIF marker; only valid if saw_JFIF_marker is true: */ + byte JFIF_major_version; /* JFIF version number */ + byte JFIF_minor_version; + byte density_unit; /* JFIF code for pixel size units */ + short X_density; /* Horizontal pixel density */ + short Y_density; /* Vertical pixel density */ + bool saw_Adobe_marker; /* true iff an Adobe APP14 marker was found */ + byte Adobe_transform; /* Color transform code from Adobe marker */ + + bool CCIR601_sampling; /* true=first samples are cosited */ + + /* Aside from the specific data retained from APPn markers known to the + * library, the uninterpreted contents of any or all APPn and COM markers + * can be saved in a list for examination by the application. + */ + jpeg_marker_reader marker_list; /* Head of list of saved markers */ + + /* Remaining fields are known throughout decompressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during decompression startup + */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ + + int total_iMCU_rows; /* # of iMCU rows in image */ + /* The coefficient controller's input and output progress is measured in + * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows + * in fully interleaved JPEG scans, but are used whether the scan is + * interleaved or not. We define an iMCU row as v_samp_factor DCT block + * rows of each component. Therefore, the IDCT output contains + * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. + */ + + byte[] sample_range_limit; /* table for fast range-limiting */ + int sample_range_limit_offset; + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + * Note that the decompressor output side must not use these fields. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info[MAX_COMPS_IN_SCAN] cur_comp_info;// = new jpeg_component_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + int MCUs_per_row; /* # of MCUs across the image */ + int MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int[D_MAX_BLOCKS_IN_MCU] MCU_membership;// = new int[D_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* This field is shared between entropy decoder and marker parser. + * It is either zero or the code of a JPEG marker that has been + * read from the data source, but has not yet been processed. + */ + int unread_marker; + + int[DCTSIZE2] workspace;// = new int[DCTSIZE2]; + int[1] row_ctr;// = new int[1]; + + /* + * Links to decompression subobjects (methods, private variables of modules) + */ + jpeg_decomp_master master; + jpeg_d_main_controller main; + jpeg_d_coef_controller coef; + jpeg_d_post_controller post; + jpeg_input_controller inputctl; + jpeg_marker_reader marker; + jpeg_entropy_decoder entropy; + jpeg_inverse_dct idct; + jpeg_upsampler upsample; + jpeg_color_deconverter cconvert; + jpeg_color_quantizer cquantize; + } static void error() { - SWT.error(SWT.ERROR_INVALID_IMAGE); + SWT.error(SWT.ERROR_INVALID_IMAGE); } static void error(int code) { - SWT.error(code); + SWT.error(code); } static void error(char[] msg) { - SWT.error(SWT.ERROR_INVALID_IMAGE, null, msg); + SWT.error(SWT.ERROR_INVALID_IMAGE, null, msg); } static void jinit_marker_reader (jpeg_decompress_struct cinfo) { - jpeg_marker_reader marker = cinfo.marker = new jpeg_marker_reader(); -// int i; - - /* Initialize COM/APPn processing. - * By default, we examine and then discard APP0 and APP14, - * but simply discard COM and all other APPn. - */ -// marker.process_COM = skip_variable; - marker.length_limit_COM = 0; -// for (i = 0; i < 16; i++) { -// marker.process_APPn[i] = skip_variable; -// marker.length_limit_APPn[i] = 0; -// } -// marker.process_APPn[0] = get_interesting_appn; -// marker.process_APPn[14] = get_interesting_appn; - /* Reset marker processing state */ - reset_marker_reader(cinfo); + jpeg_marker_reader marker = cinfo.marker = new jpeg_marker_reader(); +// int i; + + /* Initialize COM/APPn processing. + * By default, we examine and then discard APP0 and APP14, + * but simply discard COM and all other APPn. + */ +// marker.process_COM = skip_variable; + marker.length_limit_COM = 0; +// for (i = 0; i < 16; i++) { +// marker.process_APPn[i] = skip_variable; +// marker.length_limit_APPn[i] = 0; +// } +// marker.process_APPn[0] = get_interesting_appn; +// marker.process_APPn[14] = get_interesting_appn; + /* Reset marker processing state */ + reset_marker_reader(cinfo); } static void jinit_d_coef_controller (jpeg_decompress_struct cinfo, bool need_full_buffer) { - jpeg_d_coef_controller coef = new jpeg_d_coef_controller(); - cinfo.coef = coef; -// coef.pub.start_input_pass = start_input_pass; -// coef.pub.start_output_pass = start_output_pass; - coef.coef_bits_latch = null; - - /* Create the coefficient buffer. */ - if (need_full_buffer) { + jpeg_d_coef_controller coef = new jpeg_d_coef_controller(); + cinfo.coef = coef; +// coef.pub.start_input_pass = start_input_pass; +// coef.pub.start_output_pass = start_output_pass; + coef.coef_bits_latch = null; + + /* Create the coefficient buffer. */ + if (need_full_buffer) { //#ifdef D_MULTISCAN_FILES_SUPPORTED - /* Allocate a full-image virtual array for each component, */ - /* padded to a multiple of samp_factor DCT blocks in each direction. */ - /* Note we ask for a pre-zeroed array. */ - int ci, access_rows; - jpeg_component_info compptr; - - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - access_rows = compptr.v_samp_factor; + /* Allocate a full-image virtual array for each component, */ + /* padded to a multiple of samp_factor DCT blocks in each direction. */ + /* Note we ask for a pre-zeroed array. */ + int ci, access_rows; + jpeg_component_info compptr; + + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + access_rows = compptr.v_samp_factor; //#ifdef BLOCK_SMOOTHING_SUPPORTED - /* If block smoothing could be used, need a bigger window */ - if (cinfo.progressive_mode) - access_rows *= 3; + /* If block smoothing could be used, need a bigger window */ + if (cinfo.progressive_mode) + access_rows *= 3; //#endif - coef.whole_image[ci] = - new short[][][]( + coef.whole_image[ci] = + new short[][][]( cast(int)jround_up( compptr.height_in_blocks, compptr.v_samp_factor), cast(int)jround_up( compptr.width_in_blocks, compptr.h_samp_factor), DCTSIZE2 - ); - } -// coef.consume_data = consume_data; - coef.decompress_data = DECOMPRESS_DATA; - coef.coef_arrays = coef.whole_image[0]; /* link to virtual arrays */ -// #else -// ERREXIT(cinfo, JERR_NOT_COMPILED); -// #endif - } else { - /* We only need a single-MCU buffer. */ + ); + } +// coef.consume_data = consume_data; + coef.decompress_data = DECOMPRESS_DATA; + coef.coef_arrays = coef.whole_image[0]; /* link to virtual arrays */ +// #else +// ERREXIT(cinfo, JERR_NOT_COMPILED); +// #endif + } else { + /* We only need a single-MCU buffer. */ foreach( inout el; coef.MCU_buffer ){ el = new short[](DCTSIZE2); } -// coef.consume_data = dummy_consume_data; - coef.decompress_data = DECOMPRESS_ONEPASS; - coef.coef_arrays = null; /* flag for no virtual arrays */ - } +// coef.consume_data = dummy_consume_data; + coef.decompress_data = DECOMPRESS_ONEPASS; + coef.coef_arrays = null; /* flag for no virtual arrays */ + } } static void start_output_pass (jpeg_decompress_struct cinfo) { //#ifdef BLOCK_SMOOTHING_SUPPORTED - jpeg_d_coef_controller coef = cinfo.coef; - - /* If multipass, check to see whether to use block smoothing on this pass */ - if (coef.coef_arrays != null) { - if (cinfo.do_block_smoothing && smoothing_ok(cinfo)) - coef.decompress_data = DECOMPRESS_SMOOTH_DATA; - else - coef.decompress_data = DECOMPRESS_DATA; - } + jpeg_d_coef_controller coef = cinfo.coef; + + /* If multipass, check to see whether to use block smoothing on this pass */ + if (coef.coef_arrays != null) { + if (cinfo.do_block_smoothing && smoothing_ok(cinfo)) + coef.decompress_data = DECOMPRESS_SMOOTH_DATA; + else + coef.decompress_data = DECOMPRESS_DATA; + } //#endif - cinfo.output_iMCU_row = 0; + cinfo.output_iMCU_row = 0; } static void jpeg_create_decompress(jpeg_decompress_struct cinfo) { - cinfo.is_decompressor = true; - - - /* Initialize marker processor so application can override methods - * for COM, APPn markers before calling jpeg_read_header. - */ - cinfo.marker_list = null; - jinit_marker_reader(cinfo); - - /* And initialize the overall input controller. */ - jinit_input_controller(cinfo); - - /* OK, I'm ready */ - cinfo.global_state = DSTATE_START; + cinfo.is_decompressor = true; + + + /* Initialize marker processor so application can override methods + * for COM, APPn markers before calling jpeg_read_header. + */ + cinfo.marker_list = null; + jinit_marker_reader(cinfo); + + /* And initialize the overall input controller. */ + jinit_input_controller(cinfo); + + /* OK, I'm ready */ + cinfo.global_state = DSTATE_START; } static void jpeg_calc_output_dimensions (jpeg_decompress_struct cinfo) /* Do computations that are needed before master selection phase */ { //#ifdef IDCT_SCALING_SUPPORTED -// int ci; -// jpeg_component_info compptr; +// int ci; +// jpeg_component_info compptr; //#endif - /* Prevent application from calling me at wrong times */ - if (cinfo.global_state != DSTATE_READY) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + /* Prevent application from calling me at wrong times */ + if (cinfo.global_state != DSTATE_READY) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); //#ifdef IDCT_SCALING_SUPPORTED // -// /* Compute actual output image dimensions and DCT scaling choices. */ -// if (cinfo.scale_num * 8 <= cinfo.scale_denom) { -// /* Provide 1/8 scaling */ -// cinfo.output_width = cast(int) -// jdiv_round_up(cinfo.image_width, 8L); -// cinfo.output_height = cast(int) -// jdiv_round_up(cinfo.image_height, 8L); -// cinfo.min_DCT_scaled_size = 1; -// } else if (cinfo.scale_num * 4 <= cinfo.scale_denom) { -// /* Provide 1/4 scaling */ -// cinfo.output_width = cast(int) -// jdiv_round_up(cinfo.image_width, 4L); -// cinfo.output_height = cast(int) -// jdiv_round_up(cinfo.image_height, 4L); -// cinfo.min_DCT_scaled_size = 2; -// } else if (cinfo.scale_num * 2 <= cinfo.scale_denom) { -// /* Provide 1/2 scaling */ -// cinfo.output_width = cast(int) -// jdiv_round_up(cinfo.image_width, 2L); -// cinfo.output_height = cast(int) -// jdiv_round_up(cinfo.image_height, 2L); -// cinfo.min_DCT_scaled_size = 4; -// } else { -// /* Provide 1/1 scaling */ -// cinfo.output_width = cinfo.image_width; -// cinfo.output_height = cinfo.image_height; -// cinfo.min_DCT_scaled_size = DCTSIZE; -// } -// /* In selecting the actual DCT scaling for each component, we try to -// * scale up the chroma components via IDCT scaling rather than upsampling. -// * This saves time if the upsampler gets to use 1:1 scaling. -// * Note this code assumes that the supported DCT scalings are powers of 2. -// */ -// for (ci = 0; ci < cinfo.num_components; ci++) { -// compptr = cinfo.comp_info[ci]; -// int ssize = cinfo.min_DCT_scaled_size; -// while (ssize < DCTSIZE && -// (compptr.h_samp_factor * ssize * 2 <= cinfo.max_h_samp_factor * cinfo.min_DCT_scaled_size) && -// (compptr.v_samp_factor * ssize * 2 <= cinfo.max_v_samp_factor * cinfo.min_DCT_scaled_size)) -// { -// ssize = ssize * 2; -// } -// compptr.DCT_scaled_size = ssize; -// } +// /* Compute actual output image dimensions and DCT scaling choices. */ +// if (cinfo.scale_num * 8 <= cinfo.scale_denom) { +// /* Provide 1/8 scaling */ +// cinfo.output_width = cast(int) +// jdiv_round_up(cinfo.image_width, 8L); +// cinfo.output_height = cast(int) +// jdiv_round_up(cinfo.image_height, 8L); +// cinfo.min_DCT_scaled_size = 1; +// } else if (cinfo.scale_num * 4 <= cinfo.scale_denom) { +// /* Provide 1/4 scaling */ +// cinfo.output_width = cast(int) +// jdiv_round_up(cinfo.image_width, 4L); +// cinfo.output_height = cast(int) +// jdiv_round_up(cinfo.image_height, 4L); +// cinfo.min_DCT_scaled_size = 2; +// } else if (cinfo.scale_num * 2 <= cinfo.scale_denom) { +// /* Provide 1/2 scaling */ +// cinfo.output_width = cast(int) +// jdiv_round_up(cinfo.image_width, 2L); +// cinfo.output_height = cast(int) +// jdiv_round_up(cinfo.image_height, 2L); +// cinfo.min_DCT_scaled_size = 4; +// } else { +// /* Provide 1/1 scaling */ +// cinfo.output_width = cinfo.image_width; +// cinfo.output_height = cinfo.image_height; +// cinfo.min_DCT_scaled_size = DCTSIZE; +// } +// /* In selecting the actual DCT scaling for each component, we try to +// * scale up the chroma components via IDCT scaling rather than upsampling. +// * This saves time if the upsampler gets to use 1:1 scaling. +// * Note this code assumes that the supported DCT scalings are powers of 2. +// */ +// for (ci = 0; ci < cinfo.num_components; ci++) { +// compptr = cinfo.comp_info[ci]; +// int ssize = cinfo.min_DCT_scaled_size; +// while (ssize < DCTSIZE && +// (compptr.h_samp_factor * ssize * 2 <= cinfo.max_h_samp_factor * cinfo.min_DCT_scaled_size) && +// (compptr.v_samp_factor * ssize * 2 <= cinfo.max_v_samp_factor * cinfo.min_DCT_scaled_size)) +// { +// ssize = ssize * 2; +// } +// compptr.DCT_scaled_size = ssize; +// } // -// /* Recompute downsampled dimensions of components; -// * application needs to know these if using raw downsampled data. -// */ -// for (ci = 0; ci < cinfo.num_components; ci++) { -// compptr = cinfo.comp_info[ci]; -// /* Size in samples, after IDCT scaling */ -// compptr.downsampled_width = cast(int) -// jdiv_round_up(cast(long) cinfo.image_width * cast(long) (compptr.h_samp_factor * compptr.DCT_scaled_size), -// (cinfo.max_h_samp_factor * DCTSIZE)); -// compptr.downsampled_height = cast(int) -// jdiv_round_up(cast(long) cinfo.image_height * cast(long) (compptr.v_samp_factor * compptr.DCT_scaled_size), -// (cinfo.max_v_samp_factor * DCTSIZE)); -// } +// /* Recompute downsampled dimensions of components; +// * application needs to know these if using raw downsampled data. +// */ +// for (ci = 0; ci < cinfo.num_components; ci++) { +// compptr = cinfo.comp_info[ci]; +// /* Size in samples, after IDCT scaling */ +// compptr.downsampled_width = cast(int) +// jdiv_round_up(cast(long) cinfo.image_width * cast(long) (compptr.h_samp_factor * compptr.DCT_scaled_size), +// (cinfo.max_h_samp_factor * DCTSIZE)); +// compptr.downsampled_height = cast(int) +// jdiv_round_up(cast(long) cinfo.image_height * cast(long) (compptr.v_samp_factor * compptr.DCT_scaled_size), +// (cinfo.max_v_samp_factor * DCTSIZE)); +// } // //#else /* !IDCT_SCALING_SUPPORTED */ - /* Hardwire it to "no scaling" */ - cinfo.output_width = cinfo.image_width; - cinfo.output_height = cinfo.image_height; - /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE, - * and has computed unscaled downsampled_width and downsampled_height. - */ + /* Hardwire it to "no scaling" */ + cinfo.output_width = cinfo.image_width; + cinfo.output_height = cinfo.image_height; + /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE, + * and has computed unscaled downsampled_width and downsampled_height. + */ //#endif /* IDCT_SCALING_SUPPORTED */ - /* Report number of components in selected colorspace. */ - /* Probably this should be in the color conversion module... */ - switch (cinfo.out_color_space) { - case JCS_GRAYSCALE: - cinfo.out_color_components = 1; - break; - case JCS_RGB: - if (RGB_PIXELSIZE != 3) { - cinfo.out_color_components = RGB_PIXELSIZE; - break; - } - //FALLTHROUGH - case JCS_YCbCr: - cinfo.out_color_components = 3; - break; - case JCS_CMYK: - case JCS_YCCK: - cinfo.out_color_components = 4; - break; - default: /* else must be same colorspace as in file */ - cinfo.out_color_components = cinfo.num_components; - break; - } - cinfo.output_components = (cinfo.quantize_colors ? 1 : cinfo.out_color_components); - - /* See if upsampler will want to emit more than one row at a time */ - if (use_merged_upsample(cinfo)) - cinfo.rec_outbuf_height = cinfo.max_v_samp_factor; - else - cinfo.rec_outbuf_height = 1; + /* Report number of components in selected colorspace. */ + /* Probably this should be in the color conversion module... */ + switch (cinfo.out_color_space) { + case JCS_GRAYSCALE: + cinfo.out_color_components = 1; + break; + case JCS_RGB: + if (RGB_PIXELSIZE != 3) { + cinfo.out_color_components = RGB_PIXELSIZE; + break; + } + //FALLTHROUGH + case JCS_YCbCr: + cinfo.out_color_components = 3; + break; + case JCS_CMYK: + case JCS_YCCK: + cinfo.out_color_components = 4; + break; + default: /* else must be same colorspace as in file */ + cinfo.out_color_components = cinfo.num_components; + break; + } + cinfo.output_components = (cinfo.quantize_colors ? 1 : cinfo.out_color_components); + + /* See if upsampler will want to emit more than one row at a time */ + if (use_merged_upsample(cinfo)) + cinfo.rec_outbuf_height = cinfo.max_v_samp_factor; + else + cinfo.rec_outbuf_height = 1; } static bool use_merged_upsample (jpeg_decompress_struct cinfo) { //#ifdef UPSAMPLE_MERGING_SUPPORTED - /* Merging is the equivalent of plain box-filter upsampling */ - if (cinfo.do_fancy_upsampling || cinfo.CCIR601_sampling) - return false; - /* jdmerge.c only supports YCC=>RGB color conversion */ - if (cinfo.jpeg_color_space != JCS_YCbCr || cinfo.num_components != 3 || - cinfo.out_color_space != JCS_RGB || - cinfo.out_color_components != RGB_PIXELSIZE) - return false; - /* and it only handles 2h1v or 2h2v sampling ratios */ - if (cinfo.comp_info[0].h_samp_factor != 2 || - cinfo.comp_info[1].h_samp_factor != 1 || - cinfo.comp_info[2].h_samp_factor != 1 || - cinfo.comp_info[0].v_samp_factor > 2 || - cinfo.comp_info[1].v_samp_factor != 1 || - cinfo.comp_info[2].v_samp_factor != 1) - return false; - /* furthermore, it doesn't work if we've scaled the IDCTs differently */ - if (cinfo.comp_info[0].DCT_scaled_size != cinfo.min_DCT_scaled_size || - cinfo.comp_info[1].DCT_scaled_size != cinfo.min_DCT_scaled_size || - cinfo.comp_info[2].DCT_scaled_size != cinfo.min_DCT_scaled_size) - return false; - /* ??? also need to test for upsample-time rescaling, when & if supported */ - return true; /* by golly, it'll work... */ + /* Merging is the equivalent of plain box-filter upsampling */ + if (cinfo.do_fancy_upsampling || cinfo.CCIR601_sampling) + return false; + /* jdmerge.c only supports YCC=>RGB color conversion */ + if (cinfo.jpeg_color_space != JCS_YCbCr || cinfo.num_components != 3 || + cinfo.out_color_space != JCS_RGB || + cinfo.out_color_components != RGB_PIXELSIZE) + return false; + /* and it only handles 2h1v or 2h2v sampling ratios */ + if (cinfo.comp_info[0].h_samp_factor != 2 || + cinfo.comp_info[1].h_samp_factor != 1 || + cinfo.comp_info[2].h_samp_factor != 1 || + cinfo.comp_info[0].v_samp_factor > 2 || + cinfo.comp_info[1].v_samp_factor != 1 || + cinfo.comp_info[2].v_samp_factor != 1) + return false; + /* furthermore, it doesn't work if we've scaled the IDCTs differently */ + if (cinfo.comp_info[0].DCT_scaled_size != cinfo.min_DCT_scaled_size || + cinfo.comp_info[1].DCT_scaled_size != cinfo.min_DCT_scaled_size || + cinfo.comp_info[2].DCT_scaled_size != cinfo.min_DCT_scaled_size) + return false; + /* ??? also need to test for upsample-time rescaling, when & if supported */ + return true; /* by golly, it'll work... */ //#else -// return false; +// return false; //#endif } static void prepare_range_limit_table (jpeg_decompress_struct cinfo) /* Allocate and fill in the sample_range_limit table */ { - byte[] table; - int i; - - table = new byte[5 * (MAXJSAMPLE+1) + CENTERJSAMPLE]; - int offset = (MAXJSAMPLE+1); /* allow negative subscripts of simple table */ - cinfo.sample_range_limit_offset = offset; - cinfo.sample_range_limit = table; - /* First segment of "simple" table: limit[x] = 0 for x < 0 */ - /* Main part of "simple" table: limit[x] = x */ - for (i = 0; i <= MAXJSAMPLE; i++) - table[i + offset] = cast(byte)i; - offset += CENTERJSAMPLE; /* Point to where post-IDCT table starts */ - /* End of simple table, rest of first half of post-IDCT table */ - for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++) - table[i+offset] = cast(byte)MAXJSAMPLE; - /* Second half of post-IDCT table */ + byte[] table; + int i; + + table = new byte[5 * (MAXJSAMPLE+1) + CENTERJSAMPLE]; + int offset = (MAXJSAMPLE+1); /* allow negative subscripts of simple table */ + cinfo.sample_range_limit_offset = offset; + cinfo.sample_range_limit = table; + /* First segment of "simple" table: limit[x] = 0 for x < 0 */ + /* Main part of "simple" table: limit[x] = x */ + for (i = 0; i <= MAXJSAMPLE; i++) + table[i + offset] = cast(byte)i; + offset += CENTERJSAMPLE; /* Point to where post-IDCT table starts */ + /* End of simple table, rest of first half of post-IDCT table */ + for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++) + table[i+offset] = cast(byte)MAXJSAMPLE; + /* Second half of post-IDCT table */ System.arraycopy(cinfo.sample_range_limit, cinfo.sample_range_limit_offset, table, offset + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE), CENTERJSAMPLE); } static void build_ycc_rgb_table (jpeg_decompress_struct cinfo) { - jpeg_color_deconverter cconvert = cinfo.cconvert; - int i; - int x; -// SHIFT_TEMPS - - cconvert.Cr_r_tab = new int[MAXJSAMPLE+1]; - cconvert.Cb_b_tab = new int[MAXJSAMPLE+1]; - cconvert.Cr_g_tab = new int[MAXJSAMPLE+1]; - cconvert.Cb_g_tab = new int[MAXJSAMPLE+1]; - - for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { - /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ - /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ - /* Cr=>R value is nearest int to 1.40200 * x */ - cconvert.Cr_r_tab[i] = (cast(int)(1.40200f * (1<> SCALEBITS; - /* Cb=>B value is nearest int to 1.77200 * x */ - cconvert.Cb_b_tab[i] = (cast(int)(1.77200f * (1<> SCALEBITS; - /* Cr=>G value is scaled-up -0.71414 * x */ - cconvert.Cr_g_tab[i] = (cast(int)(- (0.71414f * (1<G value is scaled-up -0.34414 * x */ - /* We also add in ONE_HALF so that need not do it in inner loop */ - cconvert.Cb_g_tab[i] = (cast(int)(- (0.34414f* (1<R value is nearest int to 1.40200 * x */ + cconvert.Cr_r_tab[i] = (cast(int)(1.40200f * (1<> SCALEBITS; + /* Cb=>B value is nearest int to 1.77200 * x */ + cconvert.Cb_b_tab[i] = (cast(int)(1.77200f * (1<> SCALEBITS; + /* Cr=>G value is scaled-up -0.71414 * x */ + cconvert.Cr_g_tab[i] = (cast(int)(- (0.71414f * (1<G value is scaled-up -0.34414 * x */ + /* We also add in ONE_HALF so that need not do it in inner loop */ + cconvert.Cb_g_tab[i] = (cast(int)(- (0.34414f* (1<= 0, b > 0 */ { - a += b - 1L; - return a - (a % b); + a += b - 1L; + return a - (a % b); } static void jinit_upsampler (jpeg_decompress_struct cinfo) { - int ci; - jpeg_component_info compptr; - bool need_buffer, do_fancy; - int h_in_group, v_in_group, h_out_group, v_out_group; - - jpeg_upsampler upsample = new jpeg_upsampler(); - cinfo.upsample = upsample; -// upsample.start_pass = start_pass_upsample; -// upsample.upsample = sep_upsample; - upsample.need_context_rows = false; /* until we find out differently */ - - if (cinfo.CCIR601_sampling) /* this isn't supported */ - error(); -// ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); - - /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1, - * so don't ask for it. - */ - do_fancy = cinfo.do_fancy_upsampling && cinfo.min_DCT_scaled_size > 1; - - /* Verify we can handle the sampling factors, select per-component methods, - * and create storage as needed. - */ - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* Compute size of an "input group" after IDCT scaling. This many samples - * are to be converted to max_h_samp_factor * max_v_samp_factor pixels. - */ - h_in_group = (compptr.h_samp_factor * compptr.DCT_scaled_size) / - cinfo.min_DCT_scaled_size; - v_in_group = (compptr.v_samp_factor * compptr.DCT_scaled_size) / - cinfo.min_DCT_scaled_size; - h_out_group = cinfo.max_h_samp_factor; - v_out_group = cinfo.max_v_samp_factor; - upsample.rowgroup_height[ci] = v_in_group; /* save for use later */ - need_buffer = true; - if (! compptr.component_needed) { - /* Don't bother to upsample an uninteresting component. */ - upsample.methods[ci] = NOOP_UPSAMPLE; - need_buffer = false; - } else if (h_in_group == h_out_group && v_in_group == v_out_group) { - /* Fullsize components can be processed without any work. */ - upsample.methods[ci] = FULLSIZE_UPSAMPLE; - need_buffer = false; - } else if (h_in_group * 2 == h_out_group && v_in_group == v_out_group) { - /* Special cases for 2h1v upsampling */ - if (do_fancy && compptr.downsampled_width > 2) - upsample.methods[ci] = H2V1_FANCY_UPSAMPLE; - else - upsample.methods[ci] = H2V1_UPSAMPLE; - } else if (h_in_group * 2 == h_out_group && v_in_group * 2 == v_out_group) { - /* Special cases for 2h2v upsampling */ - if (do_fancy && compptr.downsampled_width > 2) { - upsample.methods[ci] = H2V2_FANCY_UPSAMPLE; - upsample.need_context_rows = true; - } else - upsample.methods[ci] = H2V2_UPSAMPLE; - } else if ((h_out_group % h_in_group) == 0 && (v_out_group % v_in_group) == 0) { - /* Generic integral-factors upsampling method */ - upsample.methods[ci] = INT_UPSAMPLE; - upsample.h_expand[ci] = cast(byte) (h_out_group / h_in_group); - upsample.v_expand[ci] = cast(byte) (v_out_group / v_in_group); - } else - error(); -// ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); - if (need_buffer) { - upsample.color_buf[ci] = new byte[][]( cinfo.max_v_samp_factor, - cast(int) jround_up(cinfo.output_width, cinfo.max_h_samp_factor)); - } - } + int ci; + jpeg_component_info compptr; + bool need_buffer, do_fancy; + int h_in_group, v_in_group, h_out_group, v_out_group; + + jpeg_upsampler upsample = new jpeg_upsampler(); + cinfo.upsample = upsample; +// upsample.start_pass = start_pass_upsample; +// upsample.upsample = sep_upsample; + upsample.need_context_rows = false; /* until we find out differently */ + + if (cinfo.CCIR601_sampling) /* this isn't supported */ + error(); +// ERREXIT(cinfo, JERR_CCIR601_NOTIMPL); + + /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1, + * so don't ask for it. + */ + do_fancy = cinfo.do_fancy_upsampling && cinfo.min_DCT_scaled_size > 1; + + /* Verify we can handle the sampling factors, select per-component methods, + * and create storage as needed. + */ + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* Compute size of an "input group" after IDCT scaling. This many samples + * are to be converted to max_h_samp_factor * max_v_samp_factor pixels. + */ + h_in_group = (compptr.h_samp_factor * compptr.DCT_scaled_size) / + cinfo.min_DCT_scaled_size; + v_in_group = (compptr.v_samp_factor * compptr.DCT_scaled_size) / + cinfo.min_DCT_scaled_size; + h_out_group = cinfo.max_h_samp_factor; + v_out_group = cinfo.max_v_samp_factor; + upsample.rowgroup_height[ci] = v_in_group; /* save for use later */ + need_buffer = true; + if (! compptr.component_needed) { + /* Don't bother to upsample an uninteresting component. */ + upsample.methods[ci] = NOOP_UPSAMPLE; + need_buffer = false; + } else if (h_in_group == h_out_group && v_in_group == v_out_group) { + /* Fullsize components can be processed without any work. */ + upsample.methods[ci] = FULLSIZE_UPSAMPLE; + need_buffer = false; + } else if (h_in_group * 2 == h_out_group && v_in_group == v_out_group) { + /* Special cases for 2h1v upsampling */ + if (do_fancy && compptr.downsampled_width > 2) + upsample.methods[ci] = H2V1_FANCY_UPSAMPLE; + else + upsample.methods[ci] = H2V1_UPSAMPLE; + } else if (h_in_group * 2 == h_out_group && v_in_group * 2 == v_out_group) { + /* Special cases for 2h2v upsampling */ + if (do_fancy && compptr.downsampled_width > 2) { + upsample.methods[ci] = H2V2_FANCY_UPSAMPLE; + upsample.need_context_rows = true; + } else + upsample.methods[ci] = H2V2_UPSAMPLE; + } else if ((h_out_group % h_in_group) == 0 && (v_out_group % v_in_group) == 0) { + /* Generic integral-factors upsampling method */ + upsample.methods[ci] = INT_UPSAMPLE; + upsample.h_expand[ci] = cast(byte) (h_out_group / h_in_group); + upsample.v_expand[ci] = cast(byte) (v_out_group / v_in_group); + } else + error(); +// ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL); + if (need_buffer) { + upsample.color_buf[ci] = new byte[][]( cinfo.max_v_samp_factor, + cast(int) jround_up(cinfo.output_width, cinfo.max_h_samp_factor)); + } + } } static void jinit_phuff_decoder (jpeg_decompress_struct cinfo) { - int[][] coef_bit_ptr; - int ci, i; - - cinfo.entropy = new phuff_entropy_decoder(); -// entropy.pub.start_pass = start_pass_phuff_decoder; - - /* Create progression status table */ - cinfo.coef_bits = new int[][]( cinfo.num_components, DCTSIZE2 ); - coef_bit_ptr = cinfo.coef_bits; - for (ci = 0; ci < cinfo.num_components; ci++) - for (i = 0; i < DCTSIZE2; i++) - coef_bit_ptr[ci][i] = -1; + int[][] coef_bit_ptr; + int ci, i; + + cinfo.entropy = new phuff_entropy_decoder(); +// entropy.pub.start_pass = start_pass_phuff_decoder; + + /* Create progression status table */ + cinfo.coef_bits = new int[][]( cinfo.num_components, DCTSIZE2 ); + coef_bit_ptr = cinfo.coef_bits; + for (ci = 0; ci < cinfo.num_components; ci++) + for (i = 0; i < DCTSIZE2; i++) + coef_bit_ptr[ci][i] = -1; } static void jinit_huff_decoder (jpeg_decompress_struct cinfo) { - cinfo.entropy = new huff_entropy_decoder(); -// entropy.pub.start_pass = start_pass_huff_decoder; -// entropy.pub.decode_mcu = decode_mcu; + cinfo.entropy = new huff_entropy_decoder(); +// entropy.pub.start_pass = start_pass_huff_decoder; +// entropy.pub.decode_mcu = decode_mcu; } static void jinit_inverse_dct (jpeg_decompress_struct cinfo) { - int ci; - jpeg_component_info compptr; - - jpeg_inverse_dct idct = cinfo.idct = new jpeg_inverse_dct(); -// idct.pub.start_pass = start_pass; - - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* Allocate and pre-zero a multiplier table for each component */ - compptr.dct_table = new int[DCTSIZE2]; - /* Mark multiplier table not yet set up for any method */ - idct.cur_method[ci] = -1; - } + int ci; + jpeg_component_info compptr; + + jpeg_inverse_dct idct = cinfo.idct = new jpeg_inverse_dct(); +// idct.pub.start_pass = start_pass; + + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* Allocate and pre-zero a multiplier table for each component */ + compptr.dct_table = new int[DCTSIZE2]; + /* Mark multiplier table not yet set up for any method */ + idct.cur_method[ci] = -1; + } } static final int CONST_BITS = 13; static final int PASS1_BITS = 2; static final int RANGE_MASK =(MAXJSAMPLE * 4 + 3); static void jpeg_idct_islow (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - short[] coef_block, - byte[][] output_buf, int output_buf_offset, int output_col) + short[] coef_block, + byte[][] output_buf, int output_buf_offset, int output_col) { - int tmp0, tmp1, tmp2, tmp3; - int tmp10, tmp11, tmp12, tmp13; - int z1, z2, z3, z4, z5; - short[] inptr; - int[] quantptr; - int[] wsptr; - byte[] outptr; - byte[] range_limit = cinfo.sample_range_limit; - int range_limit_offset = cinfo.sample_range_limit_offset + CENTERJSAMPLE; - int ctr; - int[] workspace = cinfo.workspace; /* buffers data between passes */ -// SHIFT_TEMPS - - /* Pass 1: process columns from input, store into work array. */ - /* Note results are scaled up by sqrt(8) compared to a true IDCT; */ - /* furthermore, we scale the results by 2**PASS1_BITS. */ - - inptr = coef_block; - quantptr = compptr.dct_table; - wsptr = workspace; - int inptr_offset = 0, quantptr_offset = 0, wsptr_offset = 0; - for (ctr = DCTSIZE; ctr > 0; ctr--) { - /* Due to quantization, we will usually find that many of the input - * coefficients are zero, especially the AC terms. We can exploit this - * by short-circuiting the IDCT calculation for any column in which all - * the AC terms are zero. In that case each output is equal to the - * DC coefficient (with scale factor as needed). - * With typical images and quantization tables, half or more of the - * column DCT calculations can be simplified this way. - */ - - if (inptr[DCTSIZE*1+inptr_offset] == 0 && inptr[DCTSIZE*2+inptr_offset] == 0 && - inptr[DCTSIZE*3+inptr_offset] == 0 && inptr[DCTSIZE*4+inptr_offset] == 0 && - inptr[DCTSIZE*5+inptr_offset] == 0 && inptr[DCTSIZE*6+inptr_offset] == 0 && - inptr[DCTSIZE*7+inptr_offset] == 0) - { - /* AC terms all zero */ - int dcval = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]) << PASS1_BITS; - - wsptr[DCTSIZE*0+wsptr_offset] = dcval; - wsptr[DCTSIZE*1+wsptr_offset] = dcval; - wsptr[DCTSIZE*2+wsptr_offset] = dcval; - wsptr[DCTSIZE*3+wsptr_offset] = dcval; - wsptr[DCTSIZE*4+wsptr_offset] = dcval; - wsptr[DCTSIZE*5+wsptr_offset] = dcval; - wsptr[DCTSIZE*6+wsptr_offset] = dcval; - wsptr[DCTSIZE*7+wsptr_offset] = dcval; - - inptr_offset++; /* advance pointers to next column */ - quantptr_offset++; - wsptr_offset++; - continue; - } - - /* Even part: reverse the even part of the forward DCT. */ - /* The rotator is sqrt(2)*c(-6). */ - - z2 = ((inptr[DCTSIZE*2+inptr_offset]) * quantptr[DCTSIZE*2+quantptr_offset]); - z3 = ((inptr[DCTSIZE*6+inptr_offset]) * quantptr[DCTSIZE*6+quantptr_offset]); - - z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/); - tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/); - tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/); - - z2 = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]); - z3 = ((inptr[DCTSIZE*4+inptr_offset]) * quantptr[DCTSIZE*4+quantptr_offset]); - - tmp0 = (z2 + z3) << CONST_BITS; - tmp1 = (z2 - z3) << CONST_BITS; - - tmp10 = tmp0 + tmp3; - tmp13 = tmp0 - tmp3; - tmp11 = tmp1 + tmp2; - tmp12 = tmp1 - tmp2; - - /* Odd part per figure 8; the matrix is unitary and hence its - * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. - */ - - tmp0 = ((inptr[DCTSIZE*7+inptr_offset]) * quantptr[DCTSIZE*7+quantptr_offset]); - tmp1 = ((inptr[DCTSIZE*5+inptr_offset]) * quantptr[DCTSIZE*5+quantptr_offset]); - tmp2 = ((inptr[DCTSIZE*3+inptr_offset]) * quantptr[DCTSIZE*3+quantptr_offset]); - tmp3 = ((inptr[DCTSIZE*1+inptr_offset]) * quantptr[DCTSIZE*1+quantptr_offset]); - - z1 = tmp0 + tmp3; - z2 = tmp1 + tmp2; - z3 = tmp0 + tmp2; - z4 = tmp1 + tmp3; - z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */ - - tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */ - tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */ - tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */ - tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */ - z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */ - z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */ - z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */ - z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */ - - z3 += z5; - z4 += z5; - - tmp0 += z1 + z3; - tmp1 += z2 + z4; - tmp2 += z2 + z3; - tmp3 += z1 + z4; - - /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ - -// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) - wsptr[DCTSIZE*0+wsptr_offset] = (((tmp10 + tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*7+wsptr_offset] = (((tmp10 - tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*1+wsptr_offset] = (((tmp11 + tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*6+wsptr_offset] = (((tmp11 - tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*2+wsptr_offset] = (((tmp12 + tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*5+wsptr_offset] = (((tmp12 - tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*3+wsptr_offset] = (((tmp13 + tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - wsptr[DCTSIZE*4+wsptr_offset] = (((tmp13 - tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); - - inptr_offset++; /* advance pointers to next column */ - quantptr_offset++; - wsptr_offset++; - } - - - /* Pass 2: process rows from work array, store into output array. */ - /* Note that we must descale the results by a factor of 8 == 2**3, */ - /* and also undo the PASS1_BITS scaling. */ - - int outptr_offset = 0; - wsptr = workspace; - wsptr_offset =0; - for (ctr = 0; ctr < DCTSIZE; ctr++) { - outptr = output_buf[ctr+output_buf_offset]; - outptr_offset = output_col; - /* Rows of zeroes can be exploited in the same way as we did with columns. - * However, the column calculation has created many nonzero AC terms, so - * the simplification applies less often (typically 5% to 10% of the time). - * On machines with very fast multiplication, it's possible that the - * test takes more time than it's worth. In that case this section - * may be commented out. - */ + int tmp0, tmp1, tmp2, tmp3; + int tmp10, tmp11, tmp12, tmp13; + int z1, z2, z3, z4, z5; + short[] inptr; + int[] quantptr; + int[] wsptr; + byte[] outptr; + byte[] range_limit = cinfo.sample_range_limit; + int range_limit_offset = cinfo.sample_range_limit_offset + CENTERJSAMPLE; + int ctr; + int[] workspace = cinfo.workspace; /* buffers data between passes */ +// SHIFT_TEMPS + + /* Pass 1: process columns from input, store into work array. */ + /* Note results are scaled up by sqrt(8) compared to a true IDCT; */ + /* furthermore, we scale the results by 2**PASS1_BITS. */ + + inptr = coef_block; + quantptr = compptr.dct_table; + wsptr = workspace; + int inptr_offset = 0, quantptr_offset = 0, wsptr_offset = 0; + for (ctr = DCTSIZE; ctr > 0; ctr--) { + /* Due to quantization, we will usually find that many of the input + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any column in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * column DCT calculations can be simplified this way. + */ + + if (inptr[DCTSIZE*1+inptr_offset] == 0 && inptr[DCTSIZE*2+inptr_offset] == 0 && + inptr[DCTSIZE*3+inptr_offset] == 0 && inptr[DCTSIZE*4+inptr_offset] == 0 && + inptr[DCTSIZE*5+inptr_offset] == 0 && inptr[DCTSIZE*6+inptr_offset] == 0 && + inptr[DCTSIZE*7+inptr_offset] == 0) + { + /* AC terms all zero */ + int dcval = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]) << PASS1_BITS; + + wsptr[DCTSIZE*0+wsptr_offset] = dcval; + wsptr[DCTSIZE*1+wsptr_offset] = dcval; + wsptr[DCTSIZE*2+wsptr_offset] = dcval; + wsptr[DCTSIZE*3+wsptr_offset] = dcval; + wsptr[DCTSIZE*4+wsptr_offset] = dcval; + wsptr[DCTSIZE*5+wsptr_offset] = dcval; + wsptr[DCTSIZE*6+wsptr_offset] = dcval; + wsptr[DCTSIZE*7+wsptr_offset] = dcval; + + inptr_offset++; /* advance pointers to next column */ + quantptr_offset++; + wsptr_offset++; + continue; + } + + /* Even part: reverse the even part of the forward DCT. */ + /* The rotator is sqrt(2)*c(-6). */ + + z2 = ((inptr[DCTSIZE*2+inptr_offset]) * quantptr[DCTSIZE*2+quantptr_offset]); + z3 = ((inptr[DCTSIZE*6+inptr_offset]) * quantptr[DCTSIZE*6+quantptr_offset]); + + z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/); + tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/); + tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/); + + z2 = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]); + z3 = ((inptr[DCTSIZE*4+inptr_offset]) * quantptr[DCTSIZE*4+quantptr_offset]); + + tmp0 = (z2 + z3) << CONST_BITS; + tmp1 = (z2 - z3) << CONST_BITS; + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + /* Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + + tmp0 = ((inptr[DCTSIZE*7+inptr_offset]) * quantptr[DCTSIZE*7+quantptr_offset]); + tmp1 = ((inptr[DCTSIZE*5+inptr_offset]) * quantptr[DCTSIZE*5+quantptr_offset]); + tmp2 = ((inptr[DCTSIZE*3+inptr_offset]) * quantptr[DCTSIZE*3+quantptr_offset]); + tmp3 = ((inptr[DCTSIZE*1+inptr_offset]) * quantptr[DCTSIZE*1+quantptr_offset]); + + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + z4 = tmp1 + tmp3; + z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */ + + tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */ + z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */ + z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */ + z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; + + /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ + +// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) + wsptr[DCTSIZE*0+wsptr_offset] = (((tmp10 + tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*7+wsptr_offset] = (((tmp10 - tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*1+wsptr_offset] = (((tmp11 + tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*6+wsptr_offset] = (((tmp11 - tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*2+wsptr_offset] = (((tmp12 + tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*5+wsptr_offset] = (((tmp12 - tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*3+wsptr_offset] = (((tmp13 + tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + wsptr[DCTSIZE*4+wsptr_offset] = (((tmp13 - tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS)); + + inptr_offset++; /* advance pointers to next column */ + quantptr_offset++; + wsptr_offset++; + } + + + /* Pass 2: process rows from work array, store into output array. */ + /* Note that we must descale the results by a factor of 8 == 2**3, */ + /* and also undo the PASS1_BITS scaling. */ + + int outptr_offset = 0; + wsptr = workspace; + wsptr_offset =0; + for (ctr = 0; ctr < DCTSIZE; ctr++) { + outptr = output_buf[ctr+output_buf_offset]; + outptr_offset = output_col; + /* Rows of zeroes can be exploited in the same way as we did with columns. + * However, the column calculation has created many nonzero AC terms, so + * the simplification applies less often (typically 5% to 10% of the time). + * On machines with very fast multiplication, it's possible that the + * test takes more time than it's worth. In that case this section + * may be commented out. + */ //#ifndef NO_ZERO_ROW_TEST - if (wsptr[1+wsptr_offset] == 0 && wsptr[2+wsptr_offset] == 0 && wsptr[3+wsptr_offset] == 0 && wsptr[4+wsptr_offset] == 0 && - wsptr[5+wsptr_offset] == 0 && wsptr[6+wsptr_offset] == 0 && wsptr[7+wsptr_offset] == 0) - { - /* AC terms all zero */ -// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) - byte dcval = range_limit[range_limit_offset + ((((wsptr[0+wsptr_offset]) + (1 << ((PASS1_BITS+3)-1))) >> PASS1_BITS+3) - & RANGE_MASK)]; - - outptr[0+outptr_offset] = dcval; - outptr[1+outptr_offset] = dcval; - outptr[2+outptr_offset] = dcval; - outptr[3+outptr_offset] = dcval; - outptr[4+outptr_offset] = dcval; - outptr[5+outptr_offset] = dcval; - outptr[6+outptr_offset] = dcval; - outptr[7+outptr_offset] = dcval; - - wsptr_offset += DCTSIZE; /* advance pointer to next row */ - continue; - } + if (wsptr[1+wsptr_offset] == 0 && wsptr[2+wsptr_offset] == 0 && wsptr[3+wsptr_offset] == 0 && wsptr[4+wsptr_offset] == 0 && + wsptr[5+wsptr_offset] == 0 && wsptr[6+wsptr_offset] == 0 && wsptr[7+wsptr_offset] == 0) + { + /* AC terms all zero */ +// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) + byte dcval = range_limit[range_limit_offset + ((((wsptr[0+wsptr_offset]) + (1 << ((PASS1_BITS+3)-1))) >> PASS1_BITS+3) + & RANGE_MASK)]; + + outptr[0+outptr_offset] = dcval; + outptr[1+outptr_offset] = dcval; + outptr[2+outptr_offset] = dcval; + outptr[3+outptr_offset] = dcval; + outptr[4+outptr_offset] = dcval; + outptr[5+outptr_offset] = dcval; + outptr[6+outptr_offset] = dcval; + outptr[7+outptr_offset] = dcval; + + wsptr_offset += DCTSIZE; /* advance pointer to next row */ + continue; + } //#endif - /* Even part: reverse the even part of the forward DCT. */ - /* The rotator is sqrt(2)*c(-6). */ - - z2 = wsptr[2+wsptr_offset]; - z3 = wsptr[6+wsptr_offset]; - - z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/); - tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/); - tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/); - - tmp0 = (wsptr[0+wsptr_offset] + wsptr[4+wsptr_offset]) << CONST_BITS; - tmp1 = (wsptr[0+wsptr_offset] - wsptr[4+wsptr_offset]) << CONST_BITS; - - tmp10 = tmp0 + tmp3; - tmp13 = tmp0 - tmp3; - tmp11 = tmp1 + tmp2; - tmp12 = tmp1 - tmp2; - - /* Odd part per figure 8; the matrix is unitary and hence its - * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. - */ - - tmp0 = wsptr[7+wsptr_offset]; - tmp1 = wsptr[5+wsptr_offset]; - tmp2 = wsptr[3+wsptr_offset]; - tmp3 = wsptr[1+wsptr_offset]; - - z1 = tmp0 + tmp3; - z2 = tmp1 + tmp2; - z3 = tmp0 + tmp2; - z4 = tmp1 + tmp3; - z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */ - - tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */ - tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */ - tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */ - tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */ - z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */ - z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */ - z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */ - z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */ - - z3 += z5; - z4 += z5; - - tmp0 += z1 + z3; - tmp1 += z2 + z4; - tmp2 += z2 + z3; - tmp3 += z1 + z4; - - /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ - - -// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) - outptr[0+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 + tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[7+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 - tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[1+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 + tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[6+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 - tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[2+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 + tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[5+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 - tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[3+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 + tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - outptr[4+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 - tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> - CONST_BITS+PASS1_BITS+3) - & RANGE_MASK)]; - - wsptr_offset += DCTSIZE; /* advance pointer to next row */ - } + /* Even part: reverse the even part of the forward DCT. */ + /* The rotator is sqrt(2)*c(-6). */ + + z2 = wsptr[2+wsptr_offset]; + z3 = wsptr[6+wsptr_offset]; + + z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/); + tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/); + tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/); + + tmp0 = (wsptr[0+wsptr_offset] + wsptr[4+wsptr_offset]) << CONST_BITS; + tmp1 = (wsptr[0+wsptr_offset] - wsptr[4+wsptr_offset]) << CONST_BITS; + + tmp10 = tmp0 + tmp3; + tmp13 = tmp0 - tmp3; + tmp11 = tmp1 + tmp2; + tmp12 = tmp1 - tmp2; + + /* Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + + tmp0 = wsptr[7+wsptr_offset]; + tmp1 = wsptr[5+wsptr_offset]; + tmp2 = wsptr[3+wsptr_offset]; + tmp3 = wsptr[1+wsptr_offset]; + + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + z4 = tmp1 + tmp3; + z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */ + + tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */ + z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */ + z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */ + z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */ + + z3 += z5; + z4 += z5; + + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; + + /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ + + +// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n) + outptr[0+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 + tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[7+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 - tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[1+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 + tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[6+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 - tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[2+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 + tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[5+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 - tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[3+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 + tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + outptr[4+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 - tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >> + CONST_BITS+PASS1_BITS+3) + & RANGE_MASK)]; + + wsptr_offset += DCTSIZE; /* advance pointer to next row */ + } } static void upsample (jpeg_decompress_struct cinfo, - byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr, - int in_row_groups_avail, - byte[][] output_buf, int[] out_row_ctr, - int out_rows_avail) + byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr, + int in_row_groups_avail, + byte[][] output_buf, int[] out_row_ctr, + int out_rows_avail) { - sep_upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail); + sep_upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail); } static bool smoothing_ok (jpeg_decompress_struct cinfo) { - jpeg_d_coef_controller coef = cinfo.coef; - bool smoothing_useful = false; - int ci, coefi; - jpeg_component_info compptr; - JQUANT_TBL qtable; - int[] coef_bits; - int[] coef_bits_latch; - - if (! cinfo.progressive_mode || cinfo.coef_bits == null) - return false; - - /* Allocate latch area if not already done */ - if (coef.coef_bits_latch == null) - coef.coef_bits_latch = new int[cinfo.num_components * SAVED_COEFS]; - coef_bits_latch = coef.coef_bits_latch; - int coef_bits_latch_offset = 0; - - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* All components' quantization values must already be latched. */ - if ((qtable = compptr.quant_table) == null) - return false; - /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ - if (qtable.quantval[0] == 0 || - qtable.quantval[Q01_POS] == 0 || - qtable.quantval[Q10_POS] == 0 || - qtable.quantval[Q20_POS] == 0 || - qtable.quantval[Q11_POS] == 0 || - qtable.quantval[Q02_POS] == 0) - return false; - /* DC values must be at least partly known for all components. */ - coef_bits = cinfo.coef_bits[ci]; - if (coef_bits[0] < 0) - return false; - /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ - for (coefi = 1; coefi <= 5; coefi++) { - coef_bits_latch[coefi+coef_bits_latch_offset] = coef_bits[coefi]; - if (coef_bits[coefi] != 0) - smoothing_useful = true; - } - coef_bits_latch_offset += SAVED_COEFS; - } - - return smoothing_useful; + jpeg_d_coef_controller coef = cinfo.coef; + bool smoothing_useful = false; + int ci, coefi; + jpeg_component_info compptr; + JQUANT_TBL qtable; + int[] coef_bits; + int[] coef_bits_latch; + + if (! cinfo.progressive_mode || cinfo.coef_bits == null) + return false; + + /* Allocate latch area if not already done */ + if (coef.coef_bits_latch == null) + coef.coef_bits_latch = new int[cinfo.num_components * SAVED_COEFS]; + coef_bits_latch = coef.coef_bits_latch; + int coef_bits_latch_offset = 0; + + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* All components' quantization values must already be latched. */ + if ((qtable = compptr.quant_table) == null) + return false; + /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */ + if (qtable.quantval[0] == 0 || + qtable.quantval[Q01_POS] == 0 || + qtable.quantval[Q10_POS] == 0 || + qtable.quantval[Q20_POS] == 0 || + qtable.quantval[Q11_POS] == 0 || + qtable.quantval[Q02_POS] == 0) + return false; + /* DC values must be at least partly known for all components. */ + coef_bits = cinfo.coef_bits[ci]; + if (coef_bits[0] < 0) + return false; + /* Block smoothing is helpful if some AC coefficients remain inaccurate. */ + for (coefi = 1; coefi <= 5; coefi++) { + coef_bits_latch[coefi+coef_bits_latch_offset] = coef_bits[coefi]; + if (coef_bits[coefi] != 0) + smoothing_useful = true; + } + coef_bits_latch_offset += SAVED_COEFS; + } + + return smoothing_useful; } static void master_selection (jpeg_decompress_struct cinfo) { - jpeg_decomp_master master = cinfo.master; - bool use_c_buffer; - long samplesperrow; - int jd_samplesperrow; - - /* Initialize dimensions and other stuff */ - jpeg_calc_output_dimensions(cinfo); - prepare_range_limit_table(cinfo); - - /* Width of an output scanline must be representable as JDIMENSION. */ - samplesperrow = cast(long) cinfo.output_width * cast(long) cinfo.out_color_components; - jd_samplesperrow = cast(int) samplesperrow; - if ( jd_samplesperrow != samplesperrow) - error(); -// ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); - - /* Initialize my private state */ - master.pass_number = 0; - master.using_merged_upsample = use_merged_upsample(cinfo); - - /* Color quantizer selection */ - master.quantizer_1pass = null; - master.quantizer_2pass = null; - /* No mode changes if not using buffered-image mode. */ - if (! cinfo.quantize_colors || ! cinfo.buffered_image) { - cinfo.enable_1pass_quant = false; - cinfo.enable_external_quant = false; - cinfo.enable_2pass_quant = false; - } - if (cinfo.quantize_colors) { - error(SWT.ERROR_NOT_IMPLEMENTED); -// if (cinfo.raw_data_out) -// ERREXIT(cinfo, JERR_NOTIMPL); -// /* 2-pass quantizer only works in 3-component color space. */ -// if (cinfo.out_color_components != 3) { -// cinfo.enable_1pass_quant = true; -// cinfo.enable_external_quant = false; -// cinfo.enable_2pass_quant = false; -// cinfo.colormap = null; -// } else if (cinfo.colormap != null) { -// cinfo.enable_external_quant = true; -// } else if (cinfo.two_pass_quantize) { -// cinfo.enable_2pass_quant = true; -// } else { -// cinfo.enable_1pass_quant = true; -// } + jpeg_decomp_master master = cinfo.master; + bool use_c_buffer; + long samplesperrow; + int jd_samplesperrow; + + /* Initialize dimensions and other stuff */ + jpeg_calc_output_dimensions(cinfo); + prepare_range_limit_table(cinfo); + + /* Width of an output scanline must be representable as JDIMENSION. */ + samplesperrow = cast(long) cinfo.output_width * cast(long) cinfo.out_color_components; + jd_samplesperrow = cast(int) samplesperrow; + if ( jd_samplesperrow != samplesperrow) + error(); +// ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); + + /* Initialize my private state */ + master.pass_number = 0; + master.using_merged_upsample = use_merged_upsample(cinfo); + + /* Color quantizer selection */ + master.quantizer_1pass = null; + master.quantizer_2pass = null; + /* No mode changes if not using buffered-image mode. */ + if (! cinfo.quantize_colors || ! cinfo.buffered_image) { + cinfo.enable_1pass_quant = false; + cinfo.enable_external_quant = false; + cinfo.enable_2pass_quant = false; + } + if (cinfo.quantize_colors) { + error(SWT.ERROR_NOT_IMPLEMENTED); +// if (cinfo.raw_data_out) +// ERREXIT(cinfo, JERR_NOTIMPL); +// /* 2-pass quantizer only works in 3-component color space. */ +// if (cinfo.out_color_components != 3) { +// cinfo.enable_1pass_quant = true; +// cinfo.enable_external_quant = false; +// cinfo.enable_2pass_quant = false; +// cinfo.colormap = null; +// } else if (cinfo.colormap != null) { +// cinfo.enable_external_quant = true; +// } else if (cinfo.two_pass_quantize) { +// cinfo.enable_2pass_quant = true; +// } else { +// cinfo.enable_1pass_quant = true; +// } // -// if (cinfo.enable_1pass_quant) { +// if (cinfo.enable_1pass_quant) { //#ifdef QUANT_1PASS_SUPPORTED -// jinit_1pass_quantizer(cinfo); -// master.quantizer_1pass = cinfo.cquantize; +// jinit_1pass_quantizer(cinfo); +// master.quantizer_1pass = cinfo.cquantize; //#else -// ERREXIT(cinfo, JERR_NOT_COMPILED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif -// } +// } // -// /* We use the 2-pass code to map to external colormaps. */ -// if (cinfo.enable_2pass_quant || cinfo.enable_external_quant) { +// /* We use the 2-pass code to map to external colormaps. */ +// if (cinfo.enable_2pass_quant || cinfo.enable_external_quant) { //#ifdef QUANT_2PASS_SUPPORTED -// jinit_2pass_quantizer(cinfo); -// master.quantizer_2pass = cinfo.cquantize; +// jinit_2pass_quantizer(cinfo); +// master.quantizer_2pass = cinfo.cquantize; //#else -// ERREXIT(cinfo, JERR_NOT_COMPILED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif -// } -// /* If both quantizers are initialized, the 2-pass one is left active; -// * this is necessary for starting with quantization to an external map. -// */ - } - - /* Post-processing: in particular, color conversion first */ - if (! cinfo.raw_data_out) { - if (master.using_merged_upsample) { +// } +// /* If both quantizers are initialized, the 2-pass one is left active; +// * this is necessary for starting with quantization to an external map. +// */ + } + + /* Post-processing: in particular, color conversion first */ + if (! cinfo.raw_data_out) { + if (master.using_merged_upsample) { //#ifdef UPSAMPLE_MERGING_SUPPORTED -// jinit_merged_upsampler(cinfo); /* does color conversion too */ +// jinit_merged_upsampler(cinfo); /* does color conversion too */ //#else - error(); -// ERREXIT(cinfo, JERR_NOT_COMPILED); + error(); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif - } else { - jinit_color_deconverter(cinfo); - jinit_upsampler(cinfo); - } - jinit_d_post_controller(cinfo, cinfo.enable_2pass_quant); - } - /* Inverse DCT */ - jinit_inverse_dct(cinfo); - /* Entropy decoding: either Huffman or arithmetic coding. */ - if (cinfo.arith_code) { - error(); -// ERREXIT(cinfo, JERR_ARITH_NOTIMPL); - } else { - if (cinfo.progressive_mode) { + } else { + jinit_color_deconverter(cinfo); + jinit_upsampler(cinfo); + } + jinit_d_post_controller(cinfo, cinfo.enable_2pass_quant); + } + /* Inverse DCT */ + jinit_inverse_dct(cinfo); + /* Entropy decoding: either Huffman or arithmetic coding. */ + if (cinfo.arith_code) { + error(); +// ERREXIT(cinfo, JERR_ARITH_NOTIMPL); + } else { + if (cinfo.progressive_mode) { //#ifdef D_PROGRESSIVE_SUPPORTED - jinit_phuff_decoder(cinfo); + jinit_phuff_decoder(cinfo); //#else -// ERREXIT(cinfo, JERR_NOT_COMPILED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif - } else - jinit_huff_decoder(cinfo); - } - - /* Initialize principal buffer controllers. */ - use_c_buffer = cinfo.inputctl.has_multiple_scans || cinfo.buffered_image; - jinit_d_coef_controller(cinfo, use_c_buffer); - - if (! cinfo.raw_data_out) - jinit_d_main_controller(cinfo, false /* never need full buffer here */); - - /* Initialize input side of decompressor to consume first scan. */ - start_input_pass (cinfo); + } else + jinit_huff_decoder(cinfo); + } + + /* Initialize principal buffer controllers. */ + use_c_buffer = cinfo.inputctl.has_multiple_scans || cinfo.buffered_image; + jinit_d_coef_controller(cinfo, use_c_buffer); + + if (! cinfo.raw_data_out) + jinit_d_main_controller(cinfo, false /* never need full buffer here */); + + /* Initialize input side of decompressor to consume first scan. */ + start_input_pass (cinfo); //#ifdef D_MULTISCAN_FILES_SUPPORTED - /* If jpeg_start_decompress will read the whole file, initialize - * progress monitoring appropriately. The input step is counted - * as one pass. - */ -// if (cinfo.progress != null && ! cinfo.buffered_image && -// cinfo.inputctl.has_multiple_scans) { -// int nscans; -// /* Estimate number of scans to set pass_limit. */ -// if (cinfo.progressive_mode) { -// /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ -// nscans = 2 + 3 * cinfo.num_components; -// } else { -// /* For a nonprogressive multiscan file, estimate 1 scan per component. */ -// nscans = cinfo.num_components; -// } -// cinfo.progress.pass_counter = 0L; -// cinfo.progress.pass_limit = cast(long) cinfo.total_iMCU_rows * nscans; -// cinfo.progress.completed_passes = 0; -// cinfo.progress.total_passes = (cinfo.enable_2pass_quant ? 3 : 2); -// /* Count the input pass as done */ -// master.pass_number++; -// } + /* If jpeg_start_decompress will read the whole file, initialize + * progress monitoring appropriately. The input step is counted + * as one pass. + */ +// if (cinfo.progress != null && ! cinfo.buffered_image && +// cinfo.inputctl.has_multiple_scans) { +// int nscans; +// /* Estimate number of scans to set pass_limit. */ +// if (cinfo.progressive_mode) { +// /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */ +// nscans = 2 + 3 * cinfo.num_components; +// } else { +// /* For a nonprogressive multiscan file, estimate 1 scan per component. */ +// nscans = cinfo.num_components; +// } +// cinfo.progress.pass_counter = 0L; +// cinfo.progress.pass_limit = cast(long) cinfo.total_iMCU_rows * nscans; +// cinfo.progress.completed_passes = 0; +// cinfo.progress.total_passes = (cinfo.enable_2pass_quant ? 3 : 2); +// /* Count the input pass as done */ +// master.pass_number++; +// } //#endif /* D_MULTISCAN_FILES_SUPPORTED */ } static void jinit_master_decompress (jpeg_decompress_struct cinfo) { - jpeg_decomp_master master = new jpeg_decomp_master(); - cinfo.master = master; -// master.prepare_for_output_pass = prepare_for_output_pass; -// master.finish_output_pass = finish_output_pass; - - master.is_dummy_pass = false; - - master_selection(cinfo); + jpeg_decomp_master master = new jpeg_decomp_master(); + cinfo.master = master; +// master.prepare_for_output_pass = prepare_for_output_pass; +// master.finish_output_pass = finish_output_pass; + + master.is_dummy_pass = false; + + master_selection(cinfo); } static void jcopy_sample_rows (byte[][] input_array, int source_row, - byte[][] output_array, int dest_row, - int num_rows, int num_cols) + byte[][] output_array, int dest_row, + int num_rows, int num_cols) /* Copy some rows of samples from one place to another. * num_rows rows are copied from input_array[source_row++] * to output_array[dest_row++]; these areas may overlap for duplication. @@ -3434,737 +3434,737 @@ } static bool jpeg_start_decompress (jpeg_decompress_struct cinfo) { - if (cinfo.global_state == DSTATE_READY) { - /* First call: initialize master control, select active modules */ - jinit_master_decompress(cinfo); - if (cinfo.buffered_image) { - /* No more work here; expecting jpeg_start_output next */ - cinfo.global_state = DSTATE_BUFIMAGE; - return true; - } - cinfo.global_state = DSTATE_PRELOAD; - } - if (cinfo.global_state == DSTATE_PRELOAD) { - /* If file has multiple scans, absorb them all into the coef buffer */ - if (cinfo.inputctl.has_multiple_scans) { + if (cinfo.global_state == DSTATE_READY) { + /* First call: initialize master control, select active modules */ + jinit_master_decompress(cinfo); + if (cinfo.buffered_image) { + /* No more work here; expecting jpeg_start_output next */ + cinfo.global_state = DSTATE_BUFIMAGE; + return true; + } + cinfo.global_state = DSTATE_PRELOAD; + } + if (cinfo.global_state == DSTATE_PRELOAD) { + /* If file has multiple scans, absorb them all into the coef buffer */ + if (cinfo.inputctl.has_multiple_scans) { //#ifdef D_MULTISCAN_FILES_SUPPORTED - for (;;) { - int retcode; - /* Call progress monitor hook if present */ -// if (cinfo.progress != null) -// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); - /* Absorb some more input */ - retcode = consume_input (cinfo); - if (retcode == JPEG_SUSPENDED) - return false; - if (retcode == JPEG_REACHED_EOI) - break; - /* Advance progress counter if appropriate */ -// if (cinfo.progress != null && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { -// if (++cinfo.progress.pass_counter >= cinfo.progress.pass_limit) { -// /* jdmaster underestimated number of scans; ratchet up one scan */ -// cinfo.progress.pass_limit += cast(long) cinfo.total_iMCU_rows; -// } -// } - } + for (;;) { + int retcode; + /* Call progress monitor hook if present */ +// if (cinfo.progress != null) +// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); + /* Absorb some more input */ + retcode = consume_input (cinfo); + if (retcode == JPEG_SUSPENDED) + return false; + if (retcode == JPEG_REACHED_EOI) + break; + /* Advance progress counter if appropriate */ +// if (cinfo.progress != null && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { +// if (++cinfo.progress.pass_counter >= cinfo.progress.pass_limit) { +// /* jdmaster underestimated number of scans; ratchet up one scan */ +// cinfo.progress.pass_limit += cast(long) cinfo.total_iMCU_rows; +// } +// } + } //#else -// ERREXIT(cinfo, JERR_NOT_COMPILED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif /* D_MULTISCAN_FILES_SUPPORTED */ - } - cinfo.output_scan_number = cinfo.input_scan_number; - } else if (cinfo.global_state != DSTATE_PRESCAN) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - /* Perform any dummy output passes, and set up for the final pass */ - return output_pass_setup(cinfo); + } + cinfo.output_scan_number = cinfo.input_scan_number; + } else if (cinfo.global_state != DSTATE_PRESCAN) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + /* Perform any dummy output passes, and set up for the final pass */ + return output_pass_setup(cinfo); } static void prepare_for_output_pass (jpeg_decompress_struct cinfo) { - jpeg_decomp_master master = cinfo.master; - - if (master.is_dummy_pass) { + jpeg_decomp_master master = cinfo.master; + + if (master.is_dummy_pass) { //#ifdef QUANT_2PASS_SUPPORTED -// /* Final pass of 2-pass quantization */ -// master.pub.is_dummy_pass = FALSE; -// (*cinfo.cquantize.start_pass) (cinfo, FALSE); -// (*cinfo.post.start_pass) (cinfo, JBUF_CRANK_DEST); -// (*cinfo.main.start_pass) (cinfo, JBUF_CRANK_DEST); +// /* Final pass of 2-pass quantization */ +// master.pub.is_dummy_pass = FALSE; +// (*cinfo.cquantize.start_pass) (cinfo, FALSE); +// (*cinfo.post.start_pass) (cinfo, JBUF_CRANK_DEST); +// (*cinfo.main.start_pass) (cinfo, JBUF_CRANK_DEST); //#else - error(SWT.ERROR_NOT_IMPLEMENTED); -// ERREXIT(cinfo, JERR_NOT_COMPILED); + error(SWT.ERROR_NOT_IMPLEMENTED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif /* QUANT_2PASS_SUPPORTED */ - } else { - if (cinfo.quantize_colors && cinfo.colormap == null) { - /* Select new quantization method */ - if (cinfo.two_pass_quantize && cinfo.enable_2pass_quant) { - cinfo.cquantize = master.quantizer_2pass; - master.is_dummy_pass = true; - } else if (cinfo.enable_1pass_quant) { - cinfo.cquantize = master.quantizer_1pass; - } else { - error(); -// ERREXIT(cinfo, JERR_MODE_CHANGE); - } - } - cinfo.idct.start_pass (cinfo); - start_output_pass (cinfo); - if (! cinfo.raw_data_out) { - if (! master.using_merged_upsample) - cinfo.cconvert.start_pass (cinfo); - cinfo.upsample.start_pass (cinfo); - if (cinfo.quantize_colors) - cinfo.cquantize.start_pass (cinfo, master.is_dummy_pass); - cinfo.post.start_pass (cinfo, (master.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); - cinfo.main.start_pass (cinfo, JBUF_PASS_THRU); - } - } - -// /* Set up progress monitor's pass info if present */ -// if (cinfo.progress != NULL) { -// cinfo.progress.completed_passes = master.pass_number; -// cinfo.progress.total_passes = master.pass_number + -// (master.pub.is_dummy_pass ? 2 : 1); -// /* In buffered-image mode, we assume one more output pass if EOI not -// * yet reached, but no more passes if EOI has been reached. -// */ -// if (cinfo.buffered_image && ! cinfo.inputctl.eoi_reached) { -// cinfo.progress.total_passes += (cinfo.enable_2pass_quant ? 2 : 1); -// } -// } + } else { + if (cinfo.quantize_colors && cinfo.colormap == null) { + /* Select new quantization method */ + if (cinfo.two_pass_quantize && cinfo.enable_2pass_quant) { + cinfo.cquantize = master.quantizer_2pass; + master.is_dummy_pass = true; + } else if (cinfo.enable_1pass_quant) { + cinfo.cquantize = master.quantizer_1pass; + } else { + error(); +// ERREXIT(cinfo, JERR_MODE_CHANGE); + } + } + cinfo.idct.start_pass (cinfo); + start_output_pass (cinfo); + if (! cinfo.raw_data_out) { + if (! master.using_merged_upsample) + cinfo.cconvert.start_pass (cinfo); + cinfo.upsample.start_pass (cinfo); + if (cinfo.quantize_colors) + cinfo.cquantize.start_pass (cinfo, master.is_dummy_pass); + cinfo.post.start_pass (cinfo, (master.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); + cinfo.main.start_pass (cinfo, JBUF_PASS_THRU); + } + } + +// /* Set up progress monitor's pass info if present */ +// if (cinfo.progress != NULL) { +// cinfo.progress.completed_passes = master.pass_number; +// cinfo.progress.total_passes = master.pass_number + +// (master.pub.is_dummy_pass ? 2 : 1); +// /* In buffered-image mode, we assume one more output pass if EOI not +// * yet reached, but no more passes if EOI has been reached. +// */ +// if (cinfo.buffered_image && ! cinfo.inputctl.eoi_reached) { +// cinfo.progress.total_passes += (cinfo.enable_2pass_quant ? 2 : 1); +// } +// } } static bool jpeg_resync_to_restart (jpeg_decompress_struct cinfo, int desired) { - int marker = cinfo.unread_marker; - int action = 1; - - /* Always put up a warning. */ -// WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired); - - /* Outer loop handles repeated decision after scanning forward. */ - for (;;) { - if (marker < M_SOF0) - action = 2; /* invalid marker */ - else if (marker < M_RST0 || marker > M_RST7) - action = 3; /* valid non-restart marker */ - else { - if (marker == (M_RST0 + ((desired+1) & 7)) || marker == ( M_RST0 + ((desired+2) & 7))) - action = 3; /* one of the next two expected restarts */ - else if (marker == (M_RST0 + ((desired-1) & 7)) || marker == ( M_RST0 + ((desired-2) & 7))) - action = 2; /* a prior restart, so advance */ - else - action = 1; /* desired restart or too far away */ - } -// TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action); - switch (action) { - case 1: - /* Discard marker and let entropy decoder resume processing. */ - cinfo.unread_marker = 0; - return true; - case 2: - /* Scan to the next marker, and repeat the decision loop. */ - if (! next_marker(cinfo)) - return false; - marker = cinfo.unread_marker; - break; - case 3: - /* Return without advancing past this marker. */ - /* Entropy decoder will be forced to process an empty segment. */ - return true; + int marker = cinfo.unread_marker; + int action = 1; + + /* Always put up a warning. */ +// WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired); + + /* Outer loop handles repeated decision after scanning forward. */ + for (;;) { + if (marker < M_SOF0) + action = 2; /* invalid marker */ + else if (marker < M_RST0 || marker > M_RST7) + action = 3; /* valid non-restart marker */ + else { + if (marker == (M_RST0 + ((desired+1) & 7)) || marker == ( M_RST0 + ((desired+2) & 7))) + action = 3; /* one of the next two expected restarts */ + else if (marker == (M_RST0 + ((desired-1) & 7)) || marker == ( M_RST0 + ((desired-2) & 7))) + action = 2; /* a prior restart, so advance */ + else + action = 1; /* desired restart or too far away */ + } +// TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action); + switch (action) { + case 1: + /* Discard marker and let entropy decoder resume processing. */ + cinfo.unread_marker = 0; + return true; + case 2: + /* Scan to the next marker, and repeat the decision loop. */ + if (! next_marker(cinfo)) + return false; + marker = cinfo.unread_marker; + break; + case 3: + /* Return without advancing past this marker. */ + /* Entropy decoder will be forced to process an empty segment. */ + return true; default: - } - } /* end loop */ + } + } /* end loop */ } static bool read_restart_marker (jpeg_decompress_struct cinfo) { - /* Obtain a marker unless we already did. */ - /* Note that next_marker will complain if it skips any data. */ - if (cinfo.unread_marker == 0) { - if (! next_marker(cinfo)) - return false; - } - - if (cinfo.unread_marker == (M_RST0 + cinfo.marker.next_restart_num)) { - /* Normal case --- swallow the marker and let entropy decoder continue */ -// TRACEMS1(cinfo, 3, JTRC_RST, cinfo.marker.next_restart_num); - cinfo.unread_marker = 0; - } else { - /* Uh-oh, the restart markers have been messed up. */ - /* Let the data source manager determine how to resync. */ - if (! jpeg_resync_to_restart (cinfo, cinfo.marker.next_restart_num)) - return false; - } - - /* Update next-restart state */ - cinfo.marker.next_restart_num = (cinfo.marker.next_restart_num + 1) & 7; - - return true; + /* Obtain a marker unless we already did. */ + /* Note that next_marker will complain if it skips any data. */ + if (cinfo.unread_marker == 0) { + if (! next_marker(cinfo)) + return false; + } + + if (cinfo.unread_marker == (M_RST0 + cinfo.marker.next_restart_num)) { + /* Normal case --- swallow the marker and let entropy decoder continue */ +// TRACEMS1(cinfo, 3, JTRC_RST, cinfo.marker.next_restart_num); + cinfo.unread_marker = 0; + } else { + /* Uh-oh, the restart markers have been messed up. */ + /* Let the data source manager determine how to resync. */ + if (! jpeg_resync_to_restart (cinfo, cinfo.marker.next_restart_num)) + return false; + } + + /* Update next-restart state */ + cinfo.marker.next_restart_num = (cinfo.marker.next_restart_num + 1) & 7; + + return true; } static bool jpeg_fill_bit_buffer (bitread_working_state state, int get_buffer, int bits_left, int nbits) /* Load up the bit buffer to a depth of at least nbits */ { - /* Copy heavily used state fields into locals (hopefully registers) */ - byte[] buffer = state.buffer; - int bytes_in_buffer = state.bytes_in_buffer; - int bytes_offset = state.bytes_offset; - jpeg_decompress_struct cinfo = state.cinfo; - - /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ - /* (It is assumed that no request will be for more than that many bits.) */ - /* We fail to do so only if we hit a marker or are forced to suspend. */ - - if (cinfo.unread_marker == 0) { /* cannot advance past a marker */ - while (bits_left < MIN_GET_BITS) { - int c; - - /* Attempt to read a byte */ - if (bytes_offset == bytes_in_buffer) { - if (! fill_input_buffer (cinfo)) - return false; - buffer = cinfo.buffer; - bytes_in_buffer = cinfo.bytes_in_buffer; - bytes_offset = cinfo.bytes_offset; - } - c = buffer[bytes_offset++] & 0xFF; - - /* If it's 0xFF, check and discard stuffed zero byte */ - if (c == 0xFF) { - /* Loop here to discard any padding FF's on terminating marker, - * so that we can save a valid unread_marker value. NOTE: we will - * accept multiple FF's followed by a 0 as meaning a single FF data - * byte. This data pattern is not valid according to the standard. - */ - do { - if (bytes_offset == bytes_in_buffer) { - if (! fill_input_buffer (cinfo)) - return false; - buffer = cinfo.buffer; - bytes_in_buffer = cinfo.bytes_in_buffer; - bytes_offset = cinfo.bytes_offset; - } - c = buffer[bytes_offset++] & 0xFF; - } while (c == 0xFF); - - if (c == 0) { - /* Found FF/00, which represents an FF data byte */ - c = 0xFF; - } else { - /* Oops, it's actually a marker indicating end of compressed data. - * Save the marker code for later use. - * Fine point: it might appear that we should save the marker into - * bitread working state, not straight into permanent state. But - * once we have hit a marker, we cannot need to suspend within the - * current MCU, because we will read no more bytes from the data - * source. So it is OK to update permanent state right away. - */ - cinfo.unread_marker = c; - /* See if we need to insert some fake zero bits. */ -// goto no_more_bytes; - if (nbits > bits_left) { - /* Uh-oh. Report corrupted data to user and stuff zeroes into - * the data stream, so that we can produce some kind of image. - * We use a nonvolatile flag to ensure that only one warning message - * appears per data segment. - */ - if (! cinfo.entropy.insufficient_data) { -// WARNMS(cinfo, JWRN_HIT_MARKER); - cinfo.entropy.insufficient_data = true; - } - /* Fill the buffer with zero bits */ - get_buffer <<= MIN_GET_BITS - bits_left; - bits_left = MIN_GET_BITS; - } - - /* Unload the local registers */ - state.buffer = buffer; - state.bytes_in_buffer = bytes_in_buffer; - state.bytes_offset = bytes_offset; - state.get_buffer = get_buffer; - state.bits_left = bits_left; - - return true; - - } - } - - /* OK, load c into get_buffer */ - get_buffer = (get_buffer << 8) | c; - bits_left += 8; - } /* end while */ - } else { -// no_more_bytes: - /* We get here if we've read the marker that terminates the compressed - * data segment. There should be enough bits in the buffer register - * to satisfy the request; if so, no problem. - */ - if (nbits > bits_left) { - /* Uh-oh. Report corrupted data to user and stuff zeroes into - * the data stream, so that we can produce some kind of image. - * We use a nonvolatile flag to ensure that only one warning message - * appears per data segment. - */ - if (! cinfo.entropy.insufficient_data) { -// WARNMS(cinfo, JWRN_HIT_MARKER); - cinfo.entropy.insufficient_data = true; - } - /* Fill the buffer with zero bits */ - get_buffer <<= MIN_GET_BITS - bits_left; - bits_left = MIN_GET_BITS; - } - } - - /* Unload the local registers */ - state.buffer = buffer; - state.bytes_in_buffer = bytes_in_buffer; - state.bytes_offset = bytes_offset; - state.get_buffer = get_buffer; - state.bits_left = bits_left; - - return true; + /* Copy heavily used state fields into locals (hopefully registers) */ + byte[] buffer = state.buffer; + int bytes_in_buffer = state.bytes_in_buffer; + int bytes_offset = state.bytes_offset; + jpeg_decompress_struct cinfo = state.cinfo; + + /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */ + /* (It is assumed that no request will be for more than that many bits.) */ + /* We fail to do so only if we hit a marker or are forced to suspend. */ + + if (cinfo.unread_marker == 0) { /* cannot advance past a marker */ + while (bits_left < MIN_GET_BITS) { + int c; + + /* Attempt to read a byte */ + if (bytes_offset == bytes_in_buffer) { + if (! fill_input_buffer (cinfo)) + return false; + buffer = cinfo.buffer; + bytes_in_buffer = cinfo.bytes_in_buffer; + bytes_offset = cinfo.bytes_offset; + } + c = buffer[bytes_offset++] & 0xFF; + + /* If it's 0xFF, check and discard stuffed zero byte */ + if (c == 0xFF) { + /* Loop here to discard any padding FF's on terminating marker, + * so that we can save a valid unread_marker value. NOTE: we will + * accept multiple FF's followed by a 0 as meaning a single FF data + * byte. This data pattern is not valid according to the standard. + */ + do { + if (bytes_offset == bytes_in_buffer) { + if (! fill_input_buffer (cinfo)) + return false; + buffer = cinfo.buffer; + bytes_in_buffer = cinfo.bytes_in_buffer; + bytes_offset = cinfo.bytes_offset; + } + c = buffer[bytes_offset++] & 0xFF; + } while (c == 0xFF); + + if (c == 0) { + /* Found FF/00, which represents an FF data byte */ + c = 0xFF; + } else { + /* Oops, it's actually a marker indicating end of compressed data. + * Save the marker code for later use. + * Fine point: it might appear that we should save the marker into + * bitread working state, not straight into permanent state. But + * once we have hit a marker, we cannot need to suspend within the + * current MCU, because we will read no more bytes from the data + * source. So it is OK to update permanent state right away. + */ + cinfo.unread_marker = c; + /* See if we need to insert some fake zero bits. */ +// goto no_more_bytes; + if (nbits > bits_left) { + /* Uh-oh. Report corrupted data to user and stuff zeroes into + * the data stream, so that we can produce some kind of image. + * We use a nonvolatile flag to ensure that only one warning message + * appears per data segment. + */ + if (! cinfo.entropy.insufficient_data) { +// WARNMS(cinfo, JWRN_HIT_MARKER); + cinfo.entropy.insufficient_data = true; + } + /* Fill the buffer with zero bits */ + get_buffer <<= MIN_GET_BITS - bits_left; + bits_left = MIN_GET_BITS; + } + + /* Unload the local registers */ + state.buffer = buffer; + state.bytes_in_buffer = bytes_in_buffer; + state.bytes_offset = bytes_offset; + state.get_buffer = get_buffer; + state.bits_left = bits_left; + + return true; + + } + } + + /* OK, load c into get_buffer */ + get_buffer = (get_buffer << 8) | c; + bits_left += 8; + } /* end while */ + } else { +// no_more_bytes: + /* We get here if we've read the marker that terminates the compressed + * data segment. There should be enough bits in the buffer register + * to satisfy the request; if so, no problem. + */ + if (nbits > bits_left) { + /* Uh-oh. Report corrupted data to user and stuff zeroes into + * the data stream, so that we can produce some kind of image. + * We use a nonvolatile flag to ensure that only one warning message + * appears per data segment. + */ + if (! cinfo.entropy.insufficient_data) { +// WARNMS(cinfo, JWRN_HIT_MARKER); + cinfo.entropy.insufficient_data = true; + } + /* Fill the buffer with zero bits */ + get_buffer <<= MIN_GET_BITS - bits_left; + bits_left = MIN_GET_BITS; + } + } + + /* Unload the local registers */ + state.buffer = buffer; + state.bytes_in_buffer = bytes_in_buffer; + state.bytes_offset = bytes_offset; + state.get_buffer = get_buffer; + state.bits_left = bits_left; + + return true; } static int jpeg_huff_decode (bitread_working_state state, int get_buffer, int bits_left, d_derived_tbl htbl, int min_bits) { - int l = min_bits; - int code; - - /* HUFF_DECODE has determined that the code is at least min_bits */ - /* bits long, so fetch that many bits in one swoop. */ - -// CHECK_BIT_BUFFER(*state, l, return -1); - { - if (bits_left < (l)) { - if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,l)) { - return -1; - } - get_buffer = state.get_buffer; bits_left = state.bits_left; - } - } -// code = GET_BITS(l); - code = (( (get_buffer >> (bits_left -= (l)))) & ((1<<(l))-1)); - - /* Collect the rest of the Huffman code one bit at a time. */ - /* This is per Figure F.16 in the JPEG spec. */ - - while (code > htbl.maxcode[l]) { - code <<= 1; -// CHECK_BIT_BUFFER(*state, 1, return -1); - { - if (bits_left < (1)) { - if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,1)) { - return -1; - } - get_buffer = state.get_buffer; bits_left = state.bits_left; - } - } -// code |= GET_BITS(1); - code |= (( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)); - l++; - } - - /* Unload the local registers */ - state.get_buffer = get_buffer; - state.bits_left = bits_left; - - /* With garbage input we may reach the sentinel value l = 17. */ - - if (l > 16) { -// WARNMS(state.cinfo, JWRN_HUFF_BAD_CODE); - return 0; /* fake a zero as the safest result */ - } - - return htbl.pub.huffval[ (code + htbl.valoffset[l]) ] & 0xFF; + int l = min_bits; + int code; + + /* HUFF_DECODE has determined that the code is at least min_bits */ + /* bits long, so fetch that many bits in one swoop. */ + +// CHECK_BIT_BUFFER(*state, l, return -1); + { + if (bits_left < (l)) { + if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,l)) { + return -1; + } + get_buffer = state.get_buffer; bits_left = state.bits_left; + } + } +// code = GET_BITS(l); + code = (( (get_buffer >> (bits_left -= (l)))) & ((1<<(l))-1)); + + /* Collect the rest of the Huffman code one bit at a time. */ + /* This is per Figure F.16 in the JPEG spec. */ + + while (code > htbl.maxcode[l]) { + code <<= 1; +// CHECK_BIT_BUFFER(*state, 1, return -1); + { + if (bits_left < (1)) { + if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,1)) { + return -1; + } + get_buffer = state.get_buffer; bits_left = state.bits_left; + } + } +// code |= GET_BITS(1); + code |= (( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)); + l++; + } + + /* Unload the local registers */ + state.get_buffer = get_buffer; + state.bits_left = bits_left; + + /* With garbage input we may reach the sentinel value l = 17. */ + + if (l > 16) { +// WARNMS(state.cinfo, JWRN_HUFF_BAD_CODE); + return 0; /* fake a zero as the safest result */ + } + + return htbl.pub.huffval[ (code + htbl.valoffset[l]) ] & 0xFF; } static int decompress_onepass (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) { - jpeg_d_coef_controller coef = cinfo.coef; - int MCU_col_num; /* index of current MCU within row */ - int last_MCU_col = cinfo.MCUs_per_row - 1; - int last_iMCU_row = cinfo.total_iMCU_rows - 1; - int blkn, ci, xindex, yindex, yoffset, useful_width; - byte[][] output_ptr; - int start_col, output_col; - jpeg_component_info compptr; -// inverse_DCT_method_ptr inverse_DCT; - - /* Loop to process as much as one whole iMCU row */ - for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) { - for (MCU_col_num = coef.MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { - /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ - for (int i = 0; i < cinfo.blocks_in_MCU; i++) { - short[] blk = coef.MCU_buffer[i]; - for (int j = 0; j < blk.length; j++) { - blk[j] = 0; - } - } - if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) { - /* Suspension forced; update state counters and exit */ - coef.MCU_vert_offset = yoffset; - coef.MCU_ctr = MCU_col_num; - return JPEG_SUSPENDED; - } - /* Determine where data should go in output_buf and do the IDCT thing. - * We skip dummy blocks at the right and bottom edges (but blkn gets - * incremented past them!). Note the inner loop relies on having - * allocated the MCU_buffer[] blocks sequentially. - */ - blkn = 0; /* index of current DCT block within MCU */ - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - /* Don't bother to IDCT an uninteresting component. */ - if (! compptr.component_needed) { - blkn += compptr.MCU_blocks; - continue; - } -// inverse_DCT = cinfo.idct.inverse_DCT[compptr.component_index]; - useful_width = (MCU_col_num < last_MCU_col) ? compptr.MCU_width : compptr.last_col_width; - output_ptr = output_buf[compptr.component_index]; - int output_ptr_offset = output_buf_offset[compptr.component_index] + yoffset * compptr.DCT_scaled_size; - start_col = MCU_col_num * compptr.MCU_sample_width; - for (yindex = 0; yindex < compptr.MCU_height; yindex++) { - if (cinfo.input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr.last_row_height) { - output_col = start_col; - for (xindex = 0; xindex < useful_width; xindex++) { - jpeg_idct_islow(cinfo, compptr, coef.MCU_buffer[blkn+xindex], output_ptr, output_ptr_offset, output_col); - output_col += compptr.DCT_scaled_size; - } - } - blkn += compptr.MCU_width; - output_ptr_offset += compptr.DCT_scaled_size; - } - } - } - /* Completed an MCU row, but perhaps not an iMCU row */ - coef.MCU_ctr = 0; - } - /* Completed the iMCU row, advance counters for next one */ - cinfo.output_iMCU_row++; - if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) { - coef.start_iMCU_row(cinfo); - return JPEG_ROW_COMPLETED; - } - /* Completed the scan */ - finish_input_pass (cinfo); - return JPEG_SCAN_COMPLETED; + jpeg_d_coef_controller coef = cinfo.coef; + int MCU_col_num; /* index of current MCU within row */ + int last_MCU_col = cinfo.MCUs_per_row - 1; + int last_iMCU_row = cinfo.total_iMCU_rows - 1; + int blkn, ci, xindex, yindex, yoffset, useful_width; + byte[][] output_ptr; + int start_col, output_col; + jpeg_component_info compptr; +// inverse_DCT_method_ptr inverse_DCT; + + /* Loop to process as much as one whole iMCU row */ + for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) { + for (MCU_col_num = coef.MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) { + /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */ + for (int i = 0; i < cinfo.blocks_in_MCU; i++) { + short[] blk = coef.MCU_buffer[i]; + for (int j = 0; j < blk.length; j++) { + blk[j] = 0; + } + } + if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef.MCU_vert_offset = yoffset; + coef.MCU_ctr = MCU_col_num; + return JPEG_SUSPENDED; + } + /* Determine where data should go in output_buf and do the IDCT thing. + * We skip dummy blocks at the right and bottom edges (but blkn gets + * incremented past them!). Note the inner loop relies on having + * allocated the MCU_buffer[] blocks sequentially. + */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + /* Don't bother to IDCT an uninteresting component. */ + if (! compptr.component_needed) { + blkn += compptr.MCU_blocks; + continue; + } +// inverse_DCT = cinfo.idct.inverse_DCT[compptr.component_index]; + useful_width = (MCU_col_num < last_MCU_col) ? compptr.MCU_width : compptr.last_col_width; + output_ptr = output_buf[compptr.component_index]; + int output_ptr_offset = output_buf_offset[compptr.component_index] + yoffset * compptr.DCT_scaled_size; + start_col = MCU_col_num * compptr.MCU_sample_width; + for (yindex = 0; yindex < compptr.MCU_height; yindex++) { + if (cinfo.input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr.last_row_height) { + output_col = start_col; + for (xindex = 0; xindex < useful_width; xindex++) { + jpeg_idct_islow(cinfo, compptr, coef.MCU_buffer[blkn+xindex], output_ptr, output_ptr_offset, output_col); + output_col += compptr.DCT_scaled_size; + } + } + blkn += compptr.MCU_width; + output_ptr_offset += compptr.DCT_scaled_size; + } + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef.MCU_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + cinfo.output_iMCU_row++; + if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) { + coef.start_iMCU_row(cinfo); + return JPEG_ROW_COMPLETED; + } + /* Completed the scan */ + finish_input_pass (cinfo); + return JPEG_SCAN_COMPLETED; } static int decompress_smooth_data (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) { - jpeg_d_coef_controller coef = cinfo.coef; - int last_iMCU_row = cinfo.total_iMCU_rows - 1; - int block_num, last_block_column; - int ci, block_row, block_rows, access_rows; - short[][][] buffer; - short[][] buffer_ptr, prev_block_row, next_block_row; - byte[][] output_ptr; - int output_col; - jpeg_component_info compptr; -// inverse_DCT_method_ptr inverse_DCT; - bool first_row, last_row; - short[] workspace = coef.workspace; - if (workspace == null) workspace = coef.workspace = new short[DCTSIZE2]; - int[] coef_bits; - JQUANT_TBL quanttbl; - int Q00,Q01,Q02,Q10,Q11,Q20, num; - int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; - int Al, pred; - - /* Force some input to be done if we are getting ahead of the input. */ - while (cinfo.input_scan_number <= cinfo.output_scan_number && ! cinfo.inputctl.eoi_reached) { - if (cinfo.input_scan_number == cinfo.output_scan_number) { - /* If input is working on current scan, we ordinarily want it to - * have completed the current row. But if input scan is DC, - * we want it to keep one row ahead so that next block row's DC - * values are up to date. - */ - int delta = (cinfo.Ss == 0) ? 1 : 0; - if (cinfo.input_iMCU_row > cinfo.output_iMCU_row+delta) - break; - } - if (consume_input(cinfo) == JPEG_SUSPENDED) - return JPEG_SUSPENDED; - } - - /* OK, output from the virtual arrays. */ - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* Don't bother to IDCT an uninteresting component. */ - if (! compptr.component_needed) - continue; - /* Count non-dummy DCT block rows in this iMCU row. */ - if (cinfo.output_iMCU_row < last_iMCU_row) { - block_rows = compptr.v_samp_factor; - access_rows = block_rows * 2; /* this and next iMCU row */ - last_row = false; - } else { - /* NB: can't use last_row_height here; it is input-side-dependent! */ - block_rows = (compptr.height_in_blocks % compptr.v_samp_factor); - if (block_rows == 0) block_rows = compptr.v_samp_factor; - access_rows = block_rows; /* this iMCU row only */ - last_row = true; - } - /* Align the virtual buffer for this component. */ - int buffer_offset; - if (cinfo.output_iMCU_row > 0) { - access_rows += compptr.v_samp_factor; /* prior iMCU row too */ - buffer = coef.whole_image[ci]; - buffer_offset = (cinfo.output_iMCU_row - 1) * compptr.v_samp_factor; - buffer_offset += compptr.v_samp_factor; /* point to current iMCU row */ - first_row = false; - } else { - buffer = coef.whole_image[ci]; - buffer_offset = 0; - first_row = true; - } - /* Fetch component-dependent info */ - coef_bits = coef.coef_bits_latch; - int coef_offset = (ci * SAVED_COEFS); - quanttbl = compptr.quant_table; - Q00 = quanttbl.quantval[0]; - Q01 = quanttbl.quantval[Q01_POS]; - Q10 = quanttbl.quantval[Q10_POS]; - Q20 = quanttbl.quantval[Q20_POS]; - Q11 = quanttbl.quantval[Q11_POS]; - Q02 = quanttbl.quantval[Q02_POS]; -// inverse_DCT = cinfo.idct.inverse_DCT[ci]; - output_ptr = output_buf[ci]; - int output_ptr_offset = output_buf_offset[ci]; - /* Loop over all DCT blocks to be processed. */ - for (block_row = 0; block_row < block_rows; block_row++) { - buffer_ptr = buffer[block_row+buffer_offset]; - int buffer_ptr_offset = 0, prev_block_row_offset = 0, next_block_row_offset = 0; - if (first_row && block_row == 0) { - prev_block_row = buffer_ptr; - prev_block_row_offset = buffer_ptr_offset; - } else { - prev_block_row = buffer[block_row-1+buffer_offset]; - prev_block_row_offset = 0; - } - if (last_row && block_row == block_rows-1) { - next_block_row = buffer_ptr; - next_block_row_offset = buffer_ptr_offset; - } else { - next_block_row = buffer[block_row+1+buffer_offset]; - next_block_row_offset = 0; - } - /* We fetch the surrounding DC values using a sliding-register approach. - * Initialize all nine here so as to do the right thing on narrow pics. - */ - DC1 = DC2 = DC3 = prev_block_row[0+prev_block_row_offset][0]; - DC4 = DC5 = DC6 = buffer_ptr[0+buffer_ptr_offset][0]; - DC7 = DC8 = DC9 = next_block_row[0+next_block_row_offset][0]; - output_col = 0; - last_block_column = compptr.width_in_blocks - 1; - for (block_num = 0; block_num <= last_block_column; block_num++) { - /* Fetch current DCT block into workspace so we can modify it. */ -// jcopy_block_row(buffer_ptr, workspace, 1); + jpeg_d_coef_controller coef = cinfo.coef; + int last_iMCU_row = cinfo.total_iMCU_rows - 1; + int block_num, last_block_column; + int ci, block_row, block_rows, access_rows; + short[][][] buffer; + short[][] buffer_ptr, prev_block_row, next_block_row; + byte[][] output_ptr; + int output_col; + jpeg_component_info compptr; +// inverse_DCT_method_ptr inverse_DCT; + bool first_row, last_row; + short[] workspace = coef.workspace; + if (workspace == null) workspace = coef.workspace = new short[DCTSIZE2]; + int[] coef_bits; + JQUANT_TBL quanttbl; + int Q00,Q01,Q02,Q10,Q11,Q20, num; + int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9; + int Al, pred; + + /* Force some input to be done if we are getting ahead of the input. */ + while (cinfo.input_scan_number <= cinfo.output_scan_number && ! cinfo.inputctl.eoi_reached) { + if (cinfo.input_scan_number == cinfo.output_scan_number) { + /* If input is working on current scan, we ordinarily want it to + * have completed the current row. But if input scan is DC, + * we want it to keep one row ahead so that next block row's DC + * values are up to date. + */ + int delta = (cinfo.Ss == 0) ? 1 : 0; + if (cinfo.input_iMCU_row > cinfo.output_iMCU_row+delta) + break; + } + if (consume_input(cinfo) == JPEG_SUSPENDED) + return JPEG_SUSPENDED; + } + + /* OK, output from the virtual arrays. */ + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* Don't bother to IDCT an uninteresting component. */ + if (! compptr.component_needed) + continue; + /* Count non-dummy DCT block rows in this iMCU row. */ + if (cinfo.output_iMCU_row < last_iMCU_row) { + block_rows = compptr.v_samp_factor; + access_rows = block_rows * 2; /* this and next iMCU row */ + last_row = false; + } else { + /* NB: can't use last_row_height here; it is input-side-dependent! */ + block_rows = (compptr.height_in_blocks % compptr.v_samp_factor); + if (block_rows == 0) block_rows = compptr.v_samp_factor; + access_rows = block_rows; /* this iMCU row only */ + last_row = true; + } + /* Align the virtual buffer for this component. */ + int buffer_offset; + if (cinfo.output_iMCU_row > 0) { + access_rows += compptr.v_samp_factor; /* prior iMCU row too */ + buffer = coef.whole_image[ci]; + buffer_offset = (cinfo.output_iMCU_row - 1) * compptr.v_samp_factor; + buffer_offset += compptr.v_samp_factor; /* point to current iMCU row */ + first_row = false; + } else { + buffer = coef.whole_image[ci]; + buffer_offset = 0; + first_row = true; + } + /* Fetch component-dependent info */ + coef_bits = coef.coef_bits_latch; + int coef_offset = (ci * SAVED_COEFS); + quanttbl = compptr.quant_table; + Q00 = quanttbl.quantval[0]; + Q01 = quanttbl.quantval[Q01_POS]; + Q10 = quanttbl.quantval[Q10_POS]; + Q20 = quanttbl.quantval[Q20_POS]; + Q11 = quanttbl.quantval[Q11_POS]; + Q02 = quanttbl.quantval[Q02_POS]; +// inverse_DCT = cinfo.idct.inverse_DCT[ci]; + output_ptr = output_buf[ci]; + int output_ptr_offset = output_buf_offset[ci]; + /* Loop over all DCT blocks to be processed. */ + for (block_row = 0; block_row < block_rows; block_row++) { + buffer_ptr = buffer[block_row+buffer_offset]; + int buffer_ptr_offset = 0, prev_block_row_offset = 0, next_block_row_offset = 0; + if (first_row && block_row == 0) { + prev_block_row = buffer_ptr; + prev_block_row_offset = buffer_ptr_offset; + } else { + prev_block_row = buffer[block_row-1+buffer_offset]; + prev_block_row_offset = 0; + } + if (last_row && block_row == block_rows-1) { + next_block_row = buffer_ptr; + next_block_row_offset = buffer_ptr_offset; + } else { + next_block_row = buffer[block_row+1+buffer_offset]; + next_block_row_offset = 0; + } + /* We fetch the surrounding DC values using a sliding-register approach. + * Initialize all nine here so as to do the right thing on narrow pics. + */ + DC1 = DC2 = DC3 = prev_block_row[0+prev_block_row_offset][0]; + DC4 = DC5 = DC6 = buffer_ptr[0+buffer_ptr_offset][0]; + DC7 = DC8 = DC9 = next_block_row[0+next_block_row_offset][0]; + output_col = 0; + last_block_column = compptr.width_in_blocks - 1; + for (block_num = 0; block_num <= last_block_column; block_num++) { + /* Fetch current DCT block into workspace so we can modify it. */ +// jcopy_block_row(buffer_ptr, workspace, 1); System.arraycopy(buffer_ptr[buffer_ptr_offset], 0, workspace, 0, workspace.length); - /* Update DC values */ - if (block_num < last_block_column) { - DC3 = prev_block_row[1+prev_block_row_offset][0]; - DC6 = buffer_ptr[1+buffer_ptr_offset][0]; - DC9 = next_block_row[1+next_block_row_offset][0]; - } - /* Compute coefficient estimates per K.8. - * An estimate is applied only if coefficient is still zero, - * and is not known to be fully accurate. - */ - /* AC01 */ - if ((Al=coef_bits[1+coef_offset]) != 0 && workspace[1] == 0) { - num = 36 * Q00 * (DC4 - DC6); - if (num >= 0) { - pred = (((Q01<<7) + num) / (Q01<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (((Q10<<7) + num) / (Q10<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (((Q20<<7) + num) / (Q20<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (((Q11<<7) + num) / (Q11<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (((Q02<<7) + num) / (Q02<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (((Q01<<7) + num) / (Q01<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (((Q10<<7) + num) / (Q10<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (((Q20<<7) + num) / (Q20<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (((Q11<<7) + num) / (Q11<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (((Q02<<7) + num) / (Q02<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= out_rows_avail) - return; /* Postprocessor exactly filled output buf */ - /*FALLTHROUGH*/ - case CTX_PREPARE_FOR_IMCU: - /* Prepare to process first M-1 row groups of this iMCU row */ - main.rowgroup_ctr[0] = 0; - main.rowgroups_avail = (cinfo.min_DCT_scaled_size - 1); - /* Check for bottom of image: if so, tweak pointers to "duplicate" - * the last sample row, and adjust rowgroups_avail to ignore padding rows. - */ - if (main.iMCU_row_ctr == cinfo.total_iMCU_rows) - set_bottom_pointers(cinfo); - main.context_state = CTX_PROCESS_IMCU; - /*FALLTHROUGH*/ - case CTX_PROCESS_IMCU: - /* Call postprocessor using previously set pointers */ - post_process_data (cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr], main.rowgroup_ctr, main.rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); - if (main.rowgroup_ctr[0] < main.rowgroups_avail) - return; /* Need to suspend */ - /* After the first iMCU, change wraparound pointers to normal state */ - if (main.iMCU_row_ctr == 1) - set_wraparound_pointers(cinfo); - /* Prepare to load new iMCU row using other xbuffer list */ - main.whichptr ^= 1; /* 0=>1 or 1=>0 */ - main.buffer_full = false; - /* Still need to process last row group of this iMCU row, */ - /* which is saved at index M+1 of the other xbuffer */ - main.rowgroup_ctr[0] = (cinfo.min_DCT_scaled_size + 1); - main.rowgroups_avail = (cinfo.min_DCT_scaled_size + 2); - main.context_state = CTX_POSTPONED_ROW; + jpeg_d_main_controller main = cinfo.main; + + /* Read input data if we haven't filled the main buffer yet */ + if (! main.buffer_full) { + int result; + switch (cinfo.coef.decompress_data) { + case DECOMPRESS_DATA: + result = decompress_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]); + break; + case DECOMPRESS_SMOOTH_DATA: + result = decompress_smooth_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]); + break; + case DECOMPRESS_ONEPASS: + result = decompress_onepass(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]); + break; + default: result = 0; + } + if (result == 0) + return; /* suspension forced, can do nothing more */ + main.buffer_full = true; /* OK, we have an iMCU row to work with */ + main.iMCU_row_ctr++; /* count rows received */ + } + + /* Postprocessor typically will not swallow all the input data it is handed + * in one call (due to filling the output buffer first). Must be prepared + * to exit and restart. This switch lets us keep track of how far we got. + * Note that each case falls through to the next on successful completion. + */ + switch (main.context_state) { + case CTX_POSTPONED_ROW: + /* Call postprocessor using previously set pointers for postponed row */ + post_process_data (cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr], main.rowgroup_ctr, main.rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); + if (main.rowgroup_ctr[0] < main.rowgroups_avail) + return; /* Need to suspend */ + main.context_state = CTX_PREPARE_FOR_IMCU; + if (out_row_ctr[0] >= out_rows_avail) + return; /* Postprocessor exactly filled output buf */ + /*FALLTHROUGH*/ + case CTX_PREPARE_FOR_IMCU: + /* Prepare to process first M-1 row groups of this iMCU row */ + main.rowgroup_ctr[0] = 0; + main.rowgroups_avail = (cinfo.min_DCT_scaled_size - 1); + /* Check for bottom of image: if so, tweak pointers to "duplicate" + * the last sample row, and adjust rowgroups_avail to ignore padding rows. + */ + if (main.iMCU_row_ctr == cinfo.total_iMCU_rows) + set_bottom_pointers(cinfo); + main.context_state = CTX_PROCESS_IMCU; + /*FALLTHROUGH*/ + case CTX_PROCESS_IMCU: + /* Call postprocessor using previously set pointers */ + post_process_data (cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr], main.rowgroup_ctr, main.rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); + if (main.rowgroup_ctr[0] < main.rowgroups_avail) + return; /* Need to suspend */ + /* After the first iMCU, change wraparound pointers to normal state */ + if (main.iMCU_row_ctr == 1) + set_wraparound_pointers(cinfo); + /* Prepare to load new iMCU row using other xbuffer list */ + main.whichptr ^= 1; /* 0=>1 or 1=>0 */ + main.buffer_full = false; + /* Still need to process last row group of this iMCU row, */ + /* which is saved at index M+1 of the other xbuffer */ + main.rowgroup_ctr[0] = (cinfo.min_DCT_scaled_size + 1); + main.rowgroups_avail = (cinfo.min_DCT_scaled_size + 2); + main.context_state = CTX_POSTPONED_ROW; default: - } + } } static void process_data_simple_main (jpeg_decompress_struct cinfo, byte[][] output_buf, int[] out_row_ctr, int out_rows_avail) { - jpeg_d_main_controller main = cinfo.main; - int rowgroups_avail; - - /* Read input data if we haven't filled the main buffer yet */ - if (! main.buffer_full) { - int result; - switch (cinfo.coef.decompress_data) { - case DECOMPRESS_DATA: - result = decompress_data(cinfo, main.buffer, main.buffer_offset); - break; - case DECOMPRESS_SMOOTH_DATA: - result = decompress_smooth_data(cinfo, main.buffer, main.buffer_offset); - break; - case DECOMPRESS_ONEPASS: - result = decompress_onepass(cinfo, main.buffer, main.buffer_offset); - break; - default: result = 0; - } - if (result == 0) - return; /* suspension forced, can do nothing more */ - main.buffer_full = true; /* OK, we have an iMCU row to work with */ - } - - /* There are always min_DCT_scaled_size row groups in an iMCU row. */ - rowgroups_avail = cinfo.min_DCT_scaled_size; - /* Note: at the bottom of the image, we may pass extra garbage row groups - * to the postprocessor. The postprocessor has to check for bottom - * of image anyway (at row resolution), so no point in us doing it too. - */ - - /* Feed the postprocessor */ - post_process_data (cinfo, main.buffer, main.buffer_offset, main.rowgroup_ctr, rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); - - /* Has postprocessor consumed all the data yet? If so, mark buffer empty */ - if (main.rowgroup_ctr[0] >= rowgroups_avail) { - main.buffer_full = false; - main.rowgroup_ctr[0] = 0; - } + jpeg_d_main_controller main = cinfo.main; + int rowgroups_avail; + + /* Read input data if we haven't filled the main buffer yet */ + if (! main.buffer_full) { + int result; + switch (cinfo.coef.decompress_data) { + case DECOMPRESS_DATA: + result = decompress_data(cinfo, main.buffer, main.buffer_offset); + break; + case DECOMPRESS_SMOOTH_DATA: + result = decompress_smooth_data(cinfo, main.buffer, main.buffer_offset); + break; + case DECOMPRESS_ONEPASS: + result = decompress_onepass(cinfo, main.buffer, main.buffer_offset); + break; + default: result = 0; + } + if (result == 0) + return; /* suspension forced, can do nothing more */ + main.buffer_full = true; /* OK, we have an iMCU row to work with */ + } + + /* There are always min_DCT_scaled_size row groups in an iMCU row. */ + rowgroups_avail = cinfo.min_DCT_scaled_size; + /* Note: at the bottom of the image, we may pass extra garbage row groups + * to the postprocessor. The postprocessor has to check for bottom + * of image anyway (at row resolution), so no point in us doing it too. + */ + + /* Feed the postprocessor */ + post_process_data (cinfo, main.buffer, main.buffer_offset, main.rowgroup_ctr, rowgroups_avail, output_buf, out_row_ctr, out_rows_avail); + + /* Has postprocessor consumed all the data yet? If so, mark buffer empty */ + if (main.rowgroup_ctr[0] >= rowgroups_avail) { + main.buffer_full = false; + main.rowgroup_ctr[0] = 0; + } } static int jpeg_read_scanlines (jpeg_decompress_struct cinfo, byte[][] scanlines, int max_lines) { - if (cinfo.global_state != DSTATE_SCANNING) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - if (cinfo.output_scanline >= cinfo.output_height) { -// WARNMS(cinfo, JWRN_TOO_MUCH_DATA); - return 0; - } - - /* Call progress monitor hook if present */ -// if (cinfo.progress != NULL) { -// cinfo.progress.pass_counter = cast(long) cinfo.output_scanline; -// cinfo.progress.pass_limit = cast(long) cinfo.output_height; -// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); -// } - - /* Process some data */ - cinfo.row_ctr[0] = 0; - switch (cinfo.main.process_data) { - case PROCESS_DATA_SIMPLE_MAIN: - process_data_simple_main (cinfo, scanlines, cinfo.row_ctr, max_lines); - break; - case PROCESS_DATA_CONTEXT_MAIN: - process_data_context_main (cinfo, scanlines, cinfo.row_ctr, max_lines); - break; - case PROCESS_DATA_CRANK_POST: - process_data_crank_post (cinfo, scanlines, cinfo.row_ctr, max_lines); - break; - default: error(); - } - cinfo.output_scanline += cinfo.row_ctr[0]; - return cinfo.row_ctr[0]; + if (cinfo.global_state != DSTATE_SCANNING) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + if (cinfo.output_scanline >= cinfo.output_height) { +// WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ +// if (cinfo.progress != NULL) { +// cinfo.progress.pass_counter = cast(long) cinfo.output_scanline; +// cinfo.progress.pass_limit = cast(long) cinfo.output_height; +// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); +// } + + /* Process some data */ + cinfo.row_ctr[0] = 0; + switch (cinfo.main.process_data) { + case PROCESS_DATA_SIMPLE_MAIN: + process_data_simple_main (cinfo, scanlines, cinfo.row_ctr, max_lines); + break; + case PROCESS_DATA_CONTEXT_MAIN: + process_data_context_main (cinfo, scanlines, cinfo.row_ctr, max_lines); + break; + case PROCESS_DATA_CRANK_POST: + process_data_crank_post (cinfo, scanlines, cinfo.row_ctr, max_lines); + break; + default: error(); + } + cinfo.output_scanline += cinfo.row_ctr[0]; + return cinfo.row_ctr[0]; } static bool output_pass_setup (jpeg_decompress_struct cinfo) { - if (cinfo.global_state != DSTATE_PRESCAN) { - /* First call: do pass setup */ - prepare_for_output_pass (cinfo); - cinfo.output_scanline = 0; - cinfo.global_state = DSTATE_PRESCAN; - } - /* Loop over any required dummy passes */ - while (cinfo.master.is_dummy_pass) { - error(); + if (cinfo.global_state != DSTATE_PRESCAN) { + /* First call: do pass setup */ + prepare_for_output_pass (cinfo); + cinfo.output_scanline = 0; + cinfo.global_state = DSTATE_PRESCAN; + } + /* Loop over any required dummy passes */ + while (cinfo.master.is_dummy_pass) { + error(); //#ifdef QUANT_2PASS_SUPPORTED -// /* Crank through the dummy pass */ -// while (cinfo.output_scanline < cinfo.output_height) { -// JDIMENSION last_scanline; -// /* Call progress monitor hook if present */ -// if (cinfo.progress != NULL) { -// cinfo.progress.pass_counter = cast(long) cinfo.output_scanline; -// cinfo.progress.pass_limit = cast(long) cinfo.output_height; -// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); -// } -// /* Process some data */ -// last_scanline = cinfo.output_scanline; -// (*cinfo.main.process_data) (cinfo, (JSAMPARRAY) NULL, -// &cinfo.output_scanline, (JDIMENSION) 0); -// if (cinfo.output_scanline == last_scanline) -// return FALSE; /* No progress made, must suspend */ -// } -// /* Finish up dummy pass, and set up for another one */ -// (*cinfo.master.finish_output_pass) (cinfo); -// (*cinfo.master.prepare_for_output_pass) (cinfo); -// cinfo.output_scanline = 0; +// /* Crank through the dummy pass */ +// while (cinfo.output_scanline < cinfo.output_height) { +// JDIMENSION last_scanline; +// /* Call progress monitor hook if present */ +// if (cinfo.progress != NULL) { +// cinfo.progress.pass_counter = cast(long) cinfo.output_scanline; +// cinfo.progress.pass_limit = cast(long) cinfo.output_height; +// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo); +// } +// /* Process some data */ +// last_scanline = cinfo.output_scanline; +// (*cinfo.main.process_data) (cinfo, (JSAMPARRAY) NULL, +// &cinfo.output_scanline, (JDIMENSION) 0); +// if (cinfo.output_scanline == last_scanline) +// return FALSE; /* No progress made, must suspend */ +// } +// /* Finish up dummy pass, and set up for another one */ +// (*cinfo.master.finish_output_pass) (cinfo); +// (*cinfo.master.prepare_for_output_pass) (cinfo); +// cinfo.output_scanline = 0; //#else -// ERREXIT(cinfo, JERR_NOT_COMPILED); +// ERREXIT(cinfo, JERR_NOT_COMPILED); //#endif /* QUANT_2PASS_SUPPORTED */ - } - /* Ready for application to drive output pass through - * jpeg_read_scanlines or jpeg_read_raw_data. - */ - cinfo.global_state = cinfo.raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; - return true; + } + /* Ready for application to drive output pass through + * jpeg_read_scanlines or jpeg_read_raw_data. + */ + cinfo.global_state = cinfo.raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; + return true; } static bool get_dht (jpeg_decompress_struct cinfo) /* Process a DHT marker */ { - int length; - byte[] bits = new byte[17]; - byte[] huffval = new byte[256]; - int i, index, count; - JHUFF_TBL htblptr; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - length -= 2; - - while (length > 16) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - -// TRACEMS1(cinfo, 1, JTRC_DHT, index); - - bits[0] = 0; - count = 0; - for (i = 1; i <= 16; i++) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - bits[i] = cinfo.buffer[cinfo.bytes_offset++]; - count += bits[i] & 0xFF; - } - - length -= 1 + 16; - -// TRACEMS8(cinfo, 2, JTRC_HUFFBITS, -// bits[1], bits[2], bits[3], bits[4], -// bits[5], bits[6], bits[7], bits[8]); -// TRACEMS8(cinfo, 2, JTRC_HUFFBITS, -// bits[9], bits[10], bits[11], bits[12], -// bits[13], bits[14], bits[15], bits[16]); - - /* Here we just do minimal validation of the counts to avoid walking - * off the end of our table space. jdhuff.c will check more carefully. - */ - if (count > 256 || (count) > length) - error(); -// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); - - for (i = 0; i < count; i++) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - huffval[i] = cinfo.buffer[cinfo.bytes_offset++]; - } - - length -= count; - - if ((index & 0x10) != 0) { /* AC table definition */ - index -= 0x10; - htblptr = cinfo.ac_huff_tbl_ptrs[index] = new JHUFF_TBL(); - } else { /* DC table definition */ - htblptr = cinfo.dc_huff_tbl_ptrs[index] = new JHUFF_TBL(); - } - - if (index < 0 || index >= NUM_HUFF_TBLS) - error(); -// ERREXIT1(cinfo, JERR_DHT_INDEX, index); + int length; + byte[] bits = new byte[17]; + byte[] huffval = new byte[256]; + int i, index, count; + JHUFF_TBL htblptr; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + length -= 2; + + while (length > 16) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + +// TRACEMS1(cinfo, 1, JTRC_DHT, index); + + bits[0] = 0; + count = 0; + for (i = 1; i <= 16; i++) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + bits[i] = cinfo.buffer[cinfo.bytes_offset++]; + count += bits[i] & 0xFF; + } + + length -= 1 + 16; + +// TRACEMS8(cinfo, 2, JTRC_HUFFBITS, +// bits[1], bits[2], bits[3], bits[4], +// bits[5], bits[6], bits[7], bits[8]); +// TRACEMS8(cinfo, 2, JTRC_HUFFBITS, +// bits[9], bits[10], bits[11], bits[12], +// bits[13], bits[14], bits[15], bits[16]); + + /* Here we just do minimal validation of the counts to avoid walking + * off the end of our table space. jdhuff.c will check more carefully. + */ + if (count > 256 || (count) > length) + error(); +// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + + for (i = 0; i < count; i++) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + huffval[i] = cinfo.buffer[cinfo.bytes_offset++]; + } + + length -= count; + + if ((index & 0x10) != 0) { /* AC table definition */ + index -= 0x10; + htblptr = cinfo.ac_huff_tbl_ptrs[index] = new JHUFF_TBL(); + } else { /* DC table definition */ + htblptr = cinfo.dc_huff_tbl_ptrs[index] = new JHUFF_TBL(); + } + + if (index < 0 || index >= NUM_HUFF_TBLS) + error(); +// ERREXIT1(cinfo, JERR_DHT_INDEX, index); System.arraycopy(bits, 0, htblptr.bits, 0, bits.length); System.arraycopy(huffval, 0, htblptr.huffval, 0, huffval.length); - } - - if (length != 0) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - return true; + } + + if (length != 0) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + return true; } static bool get_dqt (jpeg_decompress_struct cinfo) /* Process a DQT marker */ { - int length; - int n, i, prec; - int tmp; - JQUANT_TBL quant_ptr; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - length -= 2; - - while (length > 0) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - prec = n >> 4; - n &= 0x0F; - -// TRACEMS2(cinfo, 1, JTRC_DQT, n, prec); - - if (n >= NUM_QUANT_TBLS) - error(); -// ERREXIT1(cinfo, JERR_DQT_INDEX, n); - - if (cinfo.quant_tbl_ptrs[n] == null) - cinfo.quant_tbl_ptrs[n] = new JQUANT_TBL(); - quant_ptr = cinfo.quant_tbl_ptrs[n]; - - for (i = 0; i < DCTSIZE2; i++) { - if (prec != 0) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - } else { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - tmp = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - } - /* We convert the zigzag-order table to natural array order. */ - quant_ptr.quantval[jpeg_natural_order[i]] = cast(short) tmp; - } - -// if (cinfo.err.trace_level >= 2) { -// for (i = 0; i < DCTSIZE2; i += 8) { -// TRACEMS8(cinfo, 2, JTRC_QUANTVALS, -// quant_ptr.quantval[i], quant_ptr.quantval[i+1], -// quant_ptr.quantval[i+2], quant_ptr.quantval[i+3], -// quant_ptr.quantval[i+4], quant_ptr.quantval[i+5], -// quant_ptr.quantval[i+6], quant_ptr.quantval[i+7]); -// } -// } - - length -= (DCTSIZE2+1); - if (prec != 0) length -= DCTSIZE2; - } - - if (length != 0) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - return true; + int length; + int n, i, prec; + int tmp; + JQUANT_TBL quant_ptr; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + length -= 2; + + while (length > 0) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + prec = n >> 4; + n &= 0x0F; + +// TRACEMS2(cinfo, 1, JTRC_DQT, n, prec); + + if (n >= NUM_QUANT_TBLS) + error(); +// ERREXIT1(cinfo, JERR_DQT_INDEX, n); + + if (cinfo.quant_tbl_ptrs[n] == null) + cinfo.quant_tbl_ptrs[n] = new JQUANT_TBL(); + quant_ptr = cinfo.quant_tbl_ptrs[n]; + + for (i = 0; i < DCTSIZE2; i++) { + if (prec != 0) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + } else { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + tmp = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + } + /* We convert the zigzag-order table to natural array order. */ + quant_ptr.quantval[jpeg_natural_order[i]] = cast(short) tmp; + } + +// if (cinfo.err.trace_level >= 2) { +// for (i = 0; i < DCTSIZE2; i += 8) { +// TRACEMS8(cinfo, 2, JTRC_QUANTVALS, +// quant_ptr.quantval[i], quant_ptr.quantval[i+1], +// quant_ptr.quantval[i+2], quant_ptr.quantval[i+3], +// quant_ptr.quantval[i+4], quant_ptr.quantval[i+5], +// quant_ptr.quantval[i+6], quant_ptr.quantval[i+7]); +// } +// } + + length -= (DCTSIZE2+1); + if (prec != 0) length -= DCTSIZE2; + } + + if (length != 0) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + return true; } static bool get_dri (jpeg_decompress_struct cinfo) /* Process a DRI marker */ { - int length; - int tmp; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (length != 4) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - -// TRACEMS1(cinfo, 1, JTRC_DRI, tmp); - - cinfo.restart_interval = tmp; - - return true; + int length; + int tmp; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (length != 4) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + +// TRACEMS1(cinfo, 1, JTRC_DRI, tmp); + + cinfo.restart_interval = tmp; + + return true; } static bool get_dac (jpeg_decompress_struct cinfo) /* Process a DAC marker */ { - int length; - int index, val; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - length -= 2; - - while (length > 0) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - val = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - length -= 2; - -// TRACEMS2(cinfo, 1, JTRC_DAC, index, val); - - if (index < 0 || index >= (2*NUM_ARITH_TBLS)) - error(); -// ERREXIT1(cinfo, JERR_DAC_INDEX, index); - - if (index >= NUM_ARITH_TBLS) { /* define AC table */ - cinfo.arith_ac_K[index-NUM_ARITH_TBLS] = cast(byte) val; - } else { /* define DC table */ - cinfo.arith_dc_L[index] = cast(byte) (val & 0x0F); - cinfo.arith_dc_U[index] = cast(byte) (val >> 4); - if (cinfo.arith_dc_L[index] > cinfo.arith_dc_U[index]) - error(); -// ERREXIT1(cinfo, JERR_DAC_VALUE, val); - } - } - - if (length != 0) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - return true; + int length; + int index, val; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + length -= 2; + + while (length > 0) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + val = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + length -= 2; + +// TRACEMS2(cinfo, 1, JTRC_DAC, index, val); + + if (index < 0 || index >= (2*NUM_ARITH_TBLS)) + error(); +// ERREXIT1(cinfo, JERR_DAC_INDEX, index); + + if (index >= NUM_ARITH_TBLS) { /* define AC table */ + cinfo.arith_ac_K[index-NUM_ARITH_TBLS] = cast(byte) val; + } else { /* define DC table */ + cinfo.arith_dc_L[index] = cast(byte) (val & 0x0F); + cinfo.arith_dc_U[index] = cast(byte) (val >> 4); + if (cinfo.arith_dc_L[index] > cinfo.arith_dc_U[index]) + error(); +// ERREXIT1(cinfo, JERR_DAC_VALUE, val); + } + } + + if (length != 0) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + return true; } static bool get_sos (jpeg_decompress_struct cinfo) /* Process a SOS marker */ { - int length; - int i, ci, n, c, cc; - jpeg_component_info compptr = null; - - if (! cinfo.marker.saw_SOF) - error(); -// ERREXIT(cinfo, JERR_SOS_NO_SOF); - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - -// TRACEMS1(cinfo, 1, JTRC_SOS, n); - - if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - cinfo.comps_in_scan = n; - - /* Collect the component-spec parameters */ - - for (i = 0; i < n; i++) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cc = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - if (cc == compptr.component_id) - break; - } - - if (ci == cinfo.num_components) - error(); -// ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc); - - cinfo.cur_comp_info[i] = compptr; - compptr.dc_tbl_no = (c >> 4) & 15; - compptr.ac_tbl_no = (c ) & 15; - -// TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc, compptr.dc_tbl_no, compptr.ac_tbl_no); - } - - /* Collect the additional scan parameters Ss, Se, Ah/Al. */ - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - cinfo.Ss = c; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - cinfo.Se = c; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - cinfo.Ah = (c >> 4) & 15; - cinfo.Al = (c ) & 15; - -// TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al); - - /* Prepare to scan data & restart markers */ - cinfo.marker.next_restart_num = 0; - - /* Count another SOS marker */ - cinfo.input_scan_number++; - - return true; + int length; + int i, ci, n, c, cc; + jpeg_component_info compptr = null; + + if (! cinfo.marker.saw_SOF) + error(); +// ERREXIT(cinfo, JERR_SOS_NO_SOF); + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + +// TRACEMS1(cinfo, 1, JTRC_SOS, n); + + if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + cinfo.comps_in_scan = n; + + /* Collect the component-spec parameters */ + + for (i = 0; i < n; i++) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cc = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + if (cc == compptr.component_id) + break; + } + + if (ci == cinfo.num_components) + error(); +// ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc); + + cinfo.cur_comp_info[i] = compptr; + compptr.dc_tbl_no = (c >> 4) & 15; + compptr.ac_tbl_no = (c ) & 15; + +// TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc, compptr.dc_tbl_no, compptr.ac_tbl_no); + } + + /* Collect the additional scan parameters Ss, Se, Ah/Al. */ + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + cinfo.Ss = c; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + cinfo.Se = c; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + cinfo.Ah = (c >> 4) & 15; + cinfo.Al = (c ) & 15; + +// TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al); + + /* Prepare to scan data & restart markers */ + cinfo.marker.next_restart_num = 0; + + /* Count another SOS marker */ + cinfo.input_scan_number++; + + return true; } static bool get_sof (jpeg_decompress_struct cinfo, bool is_prog, bool is_arith) { - int length; - int c, ci; - - cinfo.progressive_mode = is_prog; - cinfo.arith_code = is_arith; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.data_precision = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.image_height = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.image_height |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.image_width = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.image_width |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - cinfo.num_components = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - length -= 8; - -// TRACEMS4(cinfo, 1, JTRC_SOF, cinfo.unread_marker, -// cast(int) cinfo.image_width, cast(int) cinfo.image_height, -// cinfo.num_components); - - if (cinfo.marker.saw_SOF) - error(); -// ERREXIT(cinfo, JERR_SOF_DUPLICATE); - - /* We don't support files in which the image height is initially specified */ - /* as 0 and is later redefined by DNL. As long as we have to check that, */ - /* might as well have a general sanity check. */ - if (cinfo.image_height <= 0 || cinfo.image_width <= 0 || cinfo.num_components <= 0) - error(); -// ERREXIT(cinfo, JERR_EMPTY_IMAGE); - - if (length != (cinfo.num_components * 3)) - error(); -// ERREXIT(cinfo, JERR_BAD_LENGTH); - - if (cinfo.comp_info == null) /* do only once, even if suspend */ - cinfo.comp_info = new jpeg_component_info[cinfo.num_components]; - - for (ci = 0; ci < cinfo.num_components; ci++) { - jpeg_component_info compptr = cinfo.comp_info[ci] = new jpeg_component_info(); - compptr.component_index = ci; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - compptr.component_id = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - compptr.h_samp_factor = (c >> 4) & 15; - compptr.v_samp_factor = (c ) & 15; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - compptr.quant_tbl_no = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - -// TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT, -// compptr.component_id, compptr.h_samp_factor, -// compptr.v_samp_factor, compptr.quant_tbl_no); - } - - cinfo.marker.saw_SOF = true; - - return true; + int length; + int c, ci; + + cinfo.progressive_mode = is_prog; + cinfo.arith_code = is_arith; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.data_precision = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.image_height = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.image_height |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.image_width = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.image_width |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + cinfo.num_components = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + length -= 8; + +// TRACEMS4(cinfo, 1, JTRC_SOF, cinfo.unread_marker, +// cast(int) cinfo.image_width, cast(int) cinfo.image_height, +// cinfo.num_components); + + if (cinfo.marker.saw_SOF) + error(); +// ERREXIT(cinfo, JERR_SOF_DUPLICATE); + + /* We don't support files in which the image height is initially specified */ + /* as 0 and is later redefined by DNL. As long as we have to check that, */ + /* might as well have a general sanity check. */ + if (cinfo.image_height <= 0 || cinfo.image_width <= 0 || cinfo.num_components <= 0) + error(); +// ERREXIT(cinfo, JERR_EMPTY_IMAGE); + + if (length != (cinfo.num_components * 3)) + error(); +// ERREXIT(cinfo, JERR_BAD_LENGTH); + + if (cinfo.comp_info == null) /* do only once, even if suspend */ + cinfo.comp_info = new jpeg_component_info[cinfo.num_components]; + + for (ci = 0; ci < cinfo.num_components; ci++) { + jpeg_component_info compptr = cinfo.comp_info[ci] = new jpeg_component_info(); + compptr.component_index = ci; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + compptr.component_id = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + compptr.h_samp_factor = (c >> 4) & 15; + compptr.v_samp_factor = (c ) & 15; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + compptr.quant_tbl_no = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + +// TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT, +// compptr.component_id, compptr.h_samp_factor, +// compptr.v_samp_factor, compptr.quant_tbl_no); + } + + cinfo.marker.saw_SOF = true; + + return true; } static void sep_upsample (jpeg_decompress_struct cinfo, byte[][][] input_buf, int[] input_buf_offset, - int[] in_row_group_ctr, int in_row_groups_avail, - byte[][] output_buf, int[] out_row_ctr, int out_rows_avail) + int[] in_row_group_ctr, int in_row_groups_avail, + byte[][] output_buf, int[] out_row_ctr, int out_rows_avail) { - jpeg_upsampler upsample = cinfo.upsample; - int ci; - jpeg_component_info compptr; - int num_rows; - - /* Fill the conversion buffer, if it's empty */ - if (upsample.next_row_out >= cinfo.max_v_samp_factor) { - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - /* Invoke per-component upsample method. Notice we pass a POINTER - * to color_buf[ci], so that fullsize_upsample can change it. - */ - int offset = input_buf_offset[ci] + (in_row_group_ctr[0] * upsample.rowgroup_height[ci]); - switch (upsample.methods[ci]) { - case NOOP_UPSAMPLE: noop_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case FULLSIZE_UPSAMPLE: fullsize_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case H2V1_FANCY_UPSAMPLE: h2v1_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case H2V1_UPSAMPLE: h2v1_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case H2V2_FANCY_UPSAMPLE: h2v2_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case H2V2_UPSAMPLE: h2v2_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; - case INT_UPSAMPLE: int_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + jpeg_upsampler upsample = cinfo.upsample; + int ci; + jpeg_component_info compptr; + int num_rows; + + /* Fill the conversion buffer, if it's empty */ + if (upsample.next_row_out >= cinfo.max_v_samp_factor) { + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + /* Invoke per-component upsample method. Notice we pass a POINTER + * to color_buf[ci], so that fullsize_upsample can change it. + */ + int offset = input_buf_offset[ci] + (in_row_group_ctr[0] * upsample.rowgroup_height[ci]); + switch (upsample.methods[ci]) { + case NOOP_UPSAMPLE: noop_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case FULLSIZE_UPSAMPLE: fullsize_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case H2V1_FANCY_UPSAMPLE: h2v1_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case H2V1_UPSAMPLE: h2v1_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case H2V2_FANCY_UPSAMPLE: h2v2_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case H2V2_UPSAMPLE: h2v2_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; + case INT_UPSAMPLE: int_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break; default: - } - } - upsample.next_row_out = 0; - } - - /* Color-convert and emit rows */ - - /* How many we have in the buffer: */ - num_rows = (cinfo.max_v_samp_factor - upsample.next_row_out); - /* Not more than the distance to the end of the image. Need this test - * in case the image height is not a multiple of max_v_samp_factor: - */ - if (num_rows > upsample.rows_to_go) - num_rows = upsample.rows_to_go; - /* And not more than what the client can accept: */ - out_rows_avail -= out_row_ctr[0]; - if (num_rows > out_rows_avail) - num_rows = out_rows_avail; - - switch (cinfo.cconvert.color_convert) { - case NULL_CONVERT: null_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; - case GRAYSCALE_CONVERT: grayscale_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; - case YCC_RGB_CONVERT: ycc_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; - case GRAY_RGB_CONVERT: gray_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; - case YCCK_CMYK_CONVERT: error(); break; + } + } + upsample.next_row_out = 0; + } + + /* Color-convert and emit rows */ + + /* How many we have in the buffer: */ + num_rows = (cinfo.max_v_samp_factor - upsample.next_row_out); + /* Not more than the distance to the end of the image. Need this test + * in case the image height is not a multiple of max_v_samp_factor: + */ + if (num_rows > upsample.rows_to_go) + num_rows = upsample.rows_to_go; + /* And not more than what the client can accept: */ + out_rows_avail -= out_row_ctr[0]; + if (num_rows > out_rows_avail) + num_rows = out_rows_avail; + + switch (cinfo.cconvert.color_convert) { + case NULL_CONVERT: null_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; + case GRAYSCALE_CONVERT: grayscale_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; + case YCC_RGB_CONVERT: ycc_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; + case GRAY_RGB_CONVERT: gray_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break; + case YCCK_CMYK_CONVERT: error(); break; default: - } - - /* Adjust counts */ - out_row_ctr[0] += num_rows; - upsample.rows_to_go -= num_rows; - upsample.next_row_out += num_rows; - /* When the buffer is emptied, declare this input row group consumed */ - if (upsample.next_row_out >= cinfo.max_v_samp_factor) { - in_row_group_ctr[0]++; - } + } + + /* Adjust counts */ + out_row_ctr[0] += num_rows; + upsample.rows_to_go -= num_rows; + upsample.next_row_out += num_rows; + /* When the buffer is emptied, declare this input row group consumed */ + if (upsample.next_row_out >= cinfo.max_v_samp_factor) { + in_row_group_ctr[0]++; + } } static void noop_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - output_data_ptr[output_data_index] = null; /* safety check */ + output_data_ptr[output_data_index] = null; /* safety check */ } static void fullsize_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - output_data_ptr[output_data_index] = input_data; - output_data_offset[output_data_index] = input_data_offset; + output_data_ptr[output_data_index] = input_data; + output_data_offset[output_data_index] = input_data_offset; } static void h2v1_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - byte[][] output_data = output_data_ptr[output_data_index]; - byte[] inptr, outptr; - byte invalue; - int outend; - int inrow; - output_data_offset[output_data_index] = 0; - - for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) { - inptr = input_data[inrow+input_data_offset]; - outptr = output_data[inrow]; - int inptr_offset = 0, outptr_offset = 0; - outend = outptr_offset + cinfo.output_width; - while (outptr_offset < outend) { - invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ - outptr[outptr_offset++] = invalue; - outptr[outptr_offset++] = invalue; - } - } + byte[][] output_data = output_data_ptr[output_data_index]; + byte[] inptr, outptr; + byte invalue; + int outend; + int inrow; + output_data_offset[output_data_index] = 0; + + for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) { + inptr = input_data[inrow+input_data_offset]; + outptr = output_data[inrow]; + int inptr_offset = 0, outptr_offset = 0; + outend = outptr_offset + cinfo.output_width; + while (outptr_offset < outend) { + invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ + outptr[outptr_offset++] = invalue; + outptr[outptr_offset++] = invalue; + } + } } static void h2v2_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - byte[][] output_data = output_data_ptr[output_data_index]; - byte[] inptr, outptr; - byte invalue; - int outend; - int inrow, outrow; - output_data_offset[output_data_index] = 0; - - inrow = outrow = 0; - while (outrow < cinfo.max_v_samp_factor) { - inptr = input_data[inrow+input_data_offset]; - outptr = output_data[outrow]; - int inptr_offset = 0, outptr_offset = 0; - outend = outptr_offset + cinfo.output_width; - while (outptr_offset < outend) { - invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ - outptr[outptr_offset++] = invalue; - outptr[outptr_offset++] = invalue; - } - jcopy_sample_rows(output_data, outrow, output_data, outrow+1, 1, cinfo.output_width); - inrow++; - outrow += 2; - } + byte[][] output_data = output_data_ptr[output_data_index]; + byte[] inptr, outptr; + byte invalue; + int outend; + int inrow, outrow; + output_data_offset[output_data_index] = 0; + + inrow = outrow = 0; + while (outrow < cinfo.max_v_samp_factor) { + inptr = input_data[inrow+input_data_offset]; + outptr = output_data[outrow]; + int inptr_offset = 0, outptr_offset = 0; + outend = outptr_offset + cinfo.output_width; + while (outptr_offset < outend) { + invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ + outptr[outptr_offset++] = invalue; + outptr[outptr_offset++] = invalue; + } + jcopy_sample_rows(output_data, outrow, output_data, outrow+1, 1, cinfo.output_width); + inrow++; + outrow += 2; + } } static void h2v1_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - byte[][] output_data = output_data_ptr[output_data_index]; - byte[] inptr, outptr; - int invalue; - int colctr; - int inrow; - output_data_offset[output_data_index] = 0; - - for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) { - inptr = input_data[inrow+input_data_offset]; - outptr = output_data[inrow]; - int inptr_offset = 0, outptr_offset = 0; - /* Special case for first column */ - invalue = inptr[inptr_offset++] & 0xFF; - outptr[outptr_offset++] = cast(byte) invalue; - outptr[outptr_offset++] = cast(byte) ((invalue * 3 + (inptr[inptr_offset] & 0xFF) + 2) >> 2); - - for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) { - /* General case: 3/4 * nearer pixel + 1/4 * further pixel */ - invalue = (inptr[inptr_offset++] & 0xFF) * 3; - outptr[outptr_offset++] = cast(byte) ((invalue + (inptr[inptr_offset-2] & 0xFF) + 1) >> 2); - outptr[outptr_offset++] = cast(byte) ((invalue + (inptr[inptr_offset] & 0xFF) + 2) >> 2); - } - - /* Special case for last column */ - invalue = (inptr[inptr_offset] & 0xFF); - outptr[outptr_offset++] = cast(byte) ((invalue * 3 + (inptr[inptr_offset-1] & 0xFF) + 1) >> 2); - outptr[outptr_offset++] = cast(byte) invalue; - } + byte[][] output_data = output_data_ptr[output_data_index]; + byte[] inptr, outptr; + int invalue; + int colctr; + int inrow; + output_data_offset[output_data_index] = 0; + + for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) { + inptr = input_data[inrow+input_data_offset]; + outptr = output_data[inrow]; + int inptr_offset = 0, outptr_offset = 0; + /* Special case for first column */ + invalue = inptr[inptr_offset++] & 0xFF; + outptr[outptr_offset++] = cast(byte) invalue; + outptr[outptr_offset++] = cast(byte) ((invalue * 3 + (inptr[inptr_offset] & 0xFF) + 2) >> 2); + + for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) { + /* General case: 3/4 * nearer pixel + 1/4 * further pixel */ + invalue = (inptr[inptr_offset++] & 0xFF) * 3; + outptr[outptr_offset++] = cast(byte) ((invalue + (inptr[inptr_offset-2] & 0xFF) + 1) >> 2); + outptr[outptr_offset++] = cast(byte) ((invalue + (inptr[inptr_offset] & 0xFF) + 2) >> 2); + } + + /* Special case for last column */ + invalue = (inptr[inptr_offset] & 0xFF); + outptr[outptr_offset++] = cast(byte) ((invalue * 3 + (inptr[inptr_offset-1] & 0xFF) + 1) >> 2); + outptr[outptr_offset++] = cast(byte) invalue; + } } static void h2v2_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - byte[][] output_data = output_data_ptr[output_data_index]; - byte[] inptr0, inptr1, outptr; - int thiscolsum, lastcolsum, nextcolsum; - int colctr; - int inrow, outrow, v; - output_data_offset[output_data_index] = 0; - - inrow = outrow = 0; - while (outrow < cinfo.max_v_samp_factor) { - for (v = 0; v < 2; v++) { - /* inptr0 points to nearest input row, inptr1 points to next nearest */ - inptr0 = input_data[inrow+input_data_offset]; - if (v == 0) /* next nearest is row above */ - inptr1 = input_data[inrow-1+input_data_offset]; - else /* next nearest is row below */ - inptr1 = input_data[inrow+1+input_data_offset]; - outptr = output_data[outrow++]; - - int inptr0_offset = 0, inptr1_offset = 0, outptr_offset = 0; - - /* Special case for first column */ - thiscolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); - nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 4 + 8) >> 4); - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4); - lastcolsum = thiscolsum; thiscolsum = nextcolsum; - - for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) { - /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */ - /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */ - nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4); - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4); - lastcolsum = thiscolsum; thiscolsum = nextcolsum; - } - - /* Special case for last column */ - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4); - outptr[outptr_offset++] = cast(byte) ((thiscolsum * 4 + 7) >> 4); - } - inrow++; - } + byte[][] output_data = output_data_ptr[output_data_index]; + byte[] inptr0, inptr1, outptr; + int thiscolsum, lastcolsum, nextcolsum; + int colctr; + int inrow, outrow, v; + output_data_offset[output_data_index] = 0; + + inrow = outrow = 0; + while (outrow < cinfo.max_v_samp_factor) { + for (v = 0; v < 2; v++) { + /* inptr0 points to nearest input row, inptr1 points to next nearest */ + inptr0 = input_data[inrow+input_data_offset]; + if (v == 0) /* next nearest is row above */ + inptr1 = input_data[inrow-1+input_data_offset]; + else /* next nearest is row below */ + inptr1 = input_data[inrow+1+input_data_offset]; + outptr = output_data[outrow++]; + + int inptr0_offset = 0, inptr1_offset = 0, outptr_offset = 0; + + /* Special case for first column */ + thiscolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); + nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 4 + 8) >> 4); + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4); + lastcolsum = thiscolsum; thiscolsum = nextcolsum; + + for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) { + /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */ + /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */ + nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF); + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4); + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4); + lastcolsum = thiscolsum; thiscolsum = nextcolsum; + } + + /* Special case for last column */ + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4); + outptr[outptr_offset++] = cast(byte) ((thiscolsum * 4 + 7) >> 4); + } + inrow++; + } } static void int_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr, - byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) + byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index) { - jpeg_upsampler upsample = cinfo.upsample; - byte[][] output_data = output_data_ptr[output_data_index]; - byte[] inptr, outptr; - byte invalue; - int h; - int outend; - int h_expand, v_expand; - int inrow, outrow; - output_data_offset[output_data_index] = 0; - - h_expand = upsample.h_expand[compptr.component_index]; - v_expand = upsample.v_expand[compptr.component_index]; - - inrow = outrow = 0; - while (outrow < cinfo.max_v_samp_factor) { - /* Generate one output row with proper horizontal expansion */ - inptr = input_data[inrow+input_data_offset]; - int inptr_offset = 0; - outptr = output_data[outrow]; - int outptr_offset = 0; - outend = outptr_offset + cinfo.output_width; - while (outptr_offset < outend) { - invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ - for (h = h_expand; h > 0; h--) { - outptr[outptr_offset++] = invalue; - } - } - /* Generate any additional output rows by duplicating the first one */ - if (v_expand > 1) { - jcopy_sample_rows(output_data, outrow, output_data, outrow+1, v_expand-1, cinfo.output_width); - } - inrow++; - outrow += v_expand; - } + jpeg_upsampler upsample = cinfo.upsample; + byte[][] output_data = output_data_ptr[output_data_index]; + byte[] inptr, outptr; + byte invalue; + int h; + int outend; + int h_expand, v_expand; + int inrow, outrow; + output_data_offset[output_data_index] = 0; + + h_expand = upsample.h_expand[compptr.component_index]; + v_expand = upsample.v_expand[compptr.component_index]; + + inrow = outrow = 0; + while (outrow < cinfo.max_v_samp_factor) { + /* Generate one output row with proper horizontal expansion */ + inptr = input_data[inrow+input_data_offset]; + int inptr_offset = 0; + outptr = output_data[outrow]; + int outptr_offset = 0; + outend = outptr_offset + cinfo.output_width; + while (outptr_offset < outend) { + invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */ + for (h = h_expand; h > 0; h--) { + outptr[outptr_offset++] = invalue; + } + } + /* Generate any additional output rows by duplicating the first one */ + if (v_expand > 1) { + jcopy_sample_rows(output_data, outrow, output_data, outrow+1, v_expand-1, cinfo.output_width); + } + inrow++; + outrow += v_expand; + } } static void null_convert (jpeg_decompress_struct cinfo, - byte[][][] input_buf, int[] input_buf_offset, int input_row, - byte[][] output_buf, int output_buf_offset, int num_rows) + byte[][][] input_buf, int[] input_buf_offset, int input_row, + byte[][] output_buf, int output_buf_offset, int num_rows) { - byte[] inptr, outptr; - int count; - int num_components = cinfo.num_components; - int num_cols = cinfo.output_width; - int ci; - - while (--num_rows >= 0) { - for (ci = 0; ci < num_components; ci++) { - inptr = input_buf[ci][input_row+input_buf_offset[0]]; - outptr = output_buf[output_buf_offset]; - /* BGR instead of RGB */ - int offset = 0; - switch (ci) { - case 2: offset = RGB_BLUE; break; - case 1: offset = RGB_GREEN; break; - case 0: offset = RGB_RED; break; + byte[] inptr, outptr; + int count; + int num_components = cinfo.num_components; + int num_cols = cinfo.output_width; + int ci; + + while (--num_rows >= 0) { + for (ci = 0; ci < num_components; ci++) { + inptr = input_buf[ci][input_row+input_buf_offset[0]]; + outptr = output_buf[output_buf_offset]; + /* BGR instead of RGB */ + int offset = 0; + switch (ci) { + case 2: offset = RGB_BLUE; break; + case 1: offset = RGB_GREEN; break; + case 0: offset = RGB_RED; break; default: - } - int outptr_offset = offset, inptr_offset = 0; - for (count = num_cols; count > 0; count--) { - outptr[outptr_offset] = inptr[inptr_offset++]; /* needn't bother with GETJSAMPLE() here */ - outptr_offset += num_components; - } - } - input_row++; - output_buf_offset++; - } + } + int outptr_offset = offset, inptr_offset = 0; + for (count = num_cols; count > 0; count--) { + outptr[outptr_offset] = inptr[inptr_offset++]; /* needn't bother with GETJSAMPLE() here */ + outptr_offset += num_components; + } + } + input_row++; + output_buf_offset++; + } } static void grayscale_convert (jpeg_decompress_struct cinfo, - byte[][][] input_buf, int[] input_buf_offset, int input_row, - byte[][] output_buf, int output_buf_offset, int num_rows) + byte[][][] input_buf, int[] input_buf_offset, int input_row, + byte[][] output_buf, int output_buf_offset, int num_rows) { jcopy_sample_rows(input_buf[0], input_row+input_buf_offset[0], output_buf, output_buf_offset, - num_rows, cinfo.output_width); + num_rows, cinfo.output_width); } static void gray_rgb_convert (jpeg_decompress_struct cinfo, - byte[][][] input_buf, int[] input_buf_offset, int input_row, - byte[][] output_buf, int output_buf_offset, int num_rows) + byte[][][] input_buf, int[] input_buf_offset, int input_row, + byte[][] output_buf, int output_buf_offset, int num_rows) { - byte[] inptr, outptr; - int col; - int num_cols = cinfo.output_width; - - while (--num_rows >= 0) { - inptr = input_buf[0][input_row+++input_buf_offset[0]]; - outptr = output_buf[output_buf_offset++]; - int outptr_offset = 0; - for (col = 0; col < num_cols; col++) { - /* We can dispense with GETJSAMPLE() here */ - outptr[RGB_RED+outptr_offset] = outptr[RGB_GREEN+outptr_offset] = outptr[RGB_BLUE+outptr_offset] = inptr[col]; - outptr_offset += RGB_PIXELSIZE; - } - } + byte[] inptr, outptr; + int col; + int num_cols = cinfo.output_width; + + while (--num_rows >= 0) { + inptr = input_buf[0][input_row+++input_buf_offset[0]]; + outptr = output_buf[output_buf_offset++]; + int outptr_offset = 0; + for (col = 0; col < num_cols; col++) { + /* We can dispense with GETJSAMPLE() here */ + outptr[RGB_RED+outptr_offset] = outptr[RGB_GREEN+outptr_offset] = outptr[RGB_BLUE+outptr_offset] = inptr[col]; + outptr_offset += RGB_PIXELSIZE; + } + } } static void ycc_rgb_convert (jpeg_decompress_struct cinfo, - byte[][][] input_buf, int[] input_buf_offset, int input_row, - byte[][] output_buf, int output_buf_offset, int num_rows) + byte[][][] input_buf, int[] input_buf_offset, int input_row, + byte[][] output_buf, int output_buf_offset, int num_rows) { - jpeg_color_deconverter cconvert = cinfo.cconvert; - int y, cb, cr; - byte[] outptr; - byte[] inptr0, inptr1, inptr2; - int col; - int num_cols = cinfo.output_width; - /* copy these pointers into registers if possible */ - byte[] range_limit = cinfo.sample_range_limit; - int range_limit_offset = cinfo.sample_range_limit_offset; - int[] Crrtab = cconvert.Cr_r_tab; - int[] Cbbtab = cconvert.Cb_b_tab; - int[] Crgtab = cconvert.Cr_g_tab; - int[] Cbgtab = cconvert.Cb_g_tab; -// SHIFT_TEMPS - - while (--num_rows >= 0) { - inptr0 = input_buf[0][input_row+input_buf_offset[0]]; - inptr1 = input_buf[1][input_row+input_buf_offset[1]]; - inptr2 = input_buf[2][input_row+input_buf_offset[2]]; - input_row++; - outptr = output_buf[output_buf_offset++]; - int outptr_offset = 0; - for (col = 0; col < num_cols; col++) { - y = (inptr0[col] & 0xFF); - cb = (inptr1[col] & 0xFF); - cr = (inptr2[col] & 0xFF); - /* Range-limiting is essential due to noise introduced by DCT losses. */ - outptr[outptr_offset + RGB_RED] = range_limit[y + Crrtab[cr] + range_limit_offset]; - outptr[outptr_offset + RGB_GREEN] = range_limit[y + ((Cbgtab[cb] + Crgtab[cr]>>SCALEBITS)) + range_limit_offset]; - outptr[outptr_offset + RGB_BLUE] = range_limit[y + Cbbtab[cb] + range_limit_offset]; - outptr_offset += RGB_PIXELSIZE; - } - } + jpeg_color_deconverter cconvert = cinfo.cconvert; + int y, cb, cr; + byte[] outptr; + byte[] inptr0, inptr1, inptr2; + int col; + int num_cols = cinfo.output_width; + /* copy these pointers into registers if possible */ + byte[] range_limit = cinfo.sample_range_limit; + int range_limit_offset = cinfo.sample_range_limit_offset; + int[] Crrtab = cconvert.Cr_r_tab; + int[] Cbbtab = cconvert.Cb_b_tab; + int[] Crgtab = cconvert.Cr_g_tab; + int[] Cbgtab = cconvert.Cb_g_tab; +// SHIFT_TEMPS + + while (--num_rows >= 0) { + inptr0 = input_buf[0][input_row+input_buf_offset[0]]; + inptr1 = input_buf[1][input_row+input_buf_offset[1]]; + inptr2 = input_buf[2][input_row+input_buf_offset[2]]; + input_row++; + outptr = output_buf[output_buf_offset++]; + int outptr_offset = 0; + for (col = 0; col < num_cols; col++) { + y = (inptr0[col] & 0xFF); + cb = (inptr1[col] & 0xFF); + cr = (inptr2[col] & 0xFF); + /* Range-limiting is essential due to noise introduced by DCT losses. */ + outptr[outptr_offset + RGB_RED] = range_limit[y + Crrtab[cr] + range_limit_offset]; + outptr[outptr_offset + RGB_GREEN] = range_limit[y + ((Cbgtab[cb] + Crgtab[cr]>>SCALEBITS)) + range_limit_offset]; + outptr[outptr_offset + RGB_BLUE] = range_limit[y + Cbbtab[cb] + range_limit_offset]; + outptr_offset += RGB_PIXELSIZE; + } + } } static bool process_APPn(int n, jpeg_decompress_struct cinfo) { - if (n == 0 || n == 14) { - return get_interesting_appn(cinfo); - } - return skip_variable(cinfo); + if (n == 0 || n == 14) { + return get_interesting_appn(cinfo); + } + return skip_variable(cinfo); } static bool process_COM(jpeg_decompress_struct cinfo) { - return skip_variable(cinfo); + return skip_variable(cinfo); } static void skip_input_data (jpeg_decompress_struct cinfo, int num_bytes) { - if (num_bytes > 0) { - while (num_bytes > cinfo.bytes_in_buffer - cinfo.bytes_offset) { - num_bytes -= cinfo.bytes_in_buffer - cinfo.bytes_offset; - if (!fill_input_buffer(cinfo)) error(); - /* note we assume that fill_input_buffer will never return FALSE, - * so suspension need not be handled. - */ - } - cinfo.bytes_offset += num_bytes; - } + if (num_bytes > 0) { + while (num_bytes > cinfo.bytes_in_buffer - cinfo.bytes_offset) { + num_bytes -= cinfo.bytes_in_buffer - cinfo.bytes_offset; + if (!fill_input_buffer(cinfo)) error(); + /* note we assume that fill_input_buffer will never return FALSE, + * so suspension need not be handled. + */ + } + cinfo.bytes_offset += num_bytes; + } } static bool skip_variable (jpeg_decompress_struct cinfo) /* Skip over an unknown or uninteresting variable-length marker */ { - int length; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - - length -= 2; - -// TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo.unread_marker, cast(int) length); - - if (length > 0) { - skip_input_data (cinfo, length); - } - - return true; + int length; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + + length -= 2; + +// TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo.unread_marker, cast(int) length); + + if (length > 0) { + skip_input_data (cinfo, length); + } + + return true; } static bool get_interesting_appn (jpeg_decompress_struct cinfo) /* Process an APP0 or APP14 marker without saving it */ { - int length; - byte[] b = new byte[APPN_DATA_LEN]; - int i, numtoread; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - length -= 2; - - /* get the interesting part of the marker data */ - if (length >= APPN_DATA_LEN) - numtoread = APPN_DATA_LEN; - else if (length > 0) - numtoread = length; - else - numtoread = 0; - for (i = 0; i < numtoread; i++) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - b[i] = cinfo.buffer[cinfo.bytes_offset++]; - } - length -= numtoread; - - /* process it */ - switch (cinfo.unread_marker) { - case M_APP0: - examine_app0(cinfo, b, numtoread, length); - break; - case M_APP14: - examine_app14(cinfo, b, numtoread, length); - break; - default: - /* can't get here unless jpeg_save_markers chooses wrong processor */ - error(); -// ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker); - break; - } - - /* skip any remaining data -- could be lots */ - if (length > 0) - skip_input_data (cinfo, length); - - return true; + int length; + byte[] b = new byte[APPN_DATA_LEN]; + int i, numtoread; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + length -= 2; + + /* get the interesting part of the marker data */ + if (length >= APPN_DATA_LEN) + numtoread = APPN_DATA_LEN; + else if (length > 0) + numtoread = length; + else + numtoread = 0; + for (i = 0; i < numtoread; i++) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + b[i] = cinfo.buffer[cinfo.bytes_offset++]; + } + length -= numtoread; + + /* process it */ + switch (cinfo.unread_marker) { + case M_APP0: + examine_app0(cinfo, b, numtoread, length); + break; + case M_APP14: + examine_app14(cinfo, b, numtoread, length); + break; + default: + /* can't get here unless jpeg_save_markers chooses wrong processor */ + error(); +// ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker); + break; + } + + /* skip any remaining data -- could be lots */ + if (length > 0) + skip_input_data (cinfo, length); + + return true; } static void examine_app0 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining) @@ -5198,74 +5198,74 @@ * datalen is # of bytes at data[], remaining is length of rest of marker data. */ { - int totallen = datalen + remaining; - - if (datalen >= APP0_DATA_LEN && - (data[0] & 0xFF) == 0x4A && - (data[1] & 0xFF) == 0x46 && - (data[2] & 0xFF) == 0x49 && - (data[3] & 0xFF) == 0x46 && - (data[4] & 0xFF) == 0) - { - /* Found JFIF APP0 marker: save info */ - cinfo.saw_JFIF_marker = true; - cinfo.JFIF_major_version = (data[5]); - cinfo.JFIF_minor_version = cast(byte)(data[6] & 0xFF); - cinfo.density_unit = cast(byte)(data[7] & 0xFF); - cinfo.X_density = cast(short)(((data[8] & 0xFF) << 8) + (data[9] & 0xFF)); - cinfo.Y_density = cast(short)(((data[10] & 0xFF) << 8) + (data[11] & 0xFF)); - /* Check version. - * Major version must be 1, anything else signals an incompatible change. - * (We used to treat this as an error, but now it's a nonfatal warning, - * because some bozo at Hijaak couldn't read the spec.) - * Minor version should be 0..2, but process anyway if newer. - */ - if (cinfo.JFIF_major_version != 1) { -// WARNMS2(cinfo, JWRN_JFIF_MAJOR, -// cinfo.JFIF_major_version, cinfo.JFIF_minor_version); - } - /* Generate trace messages */ -// TRACEMS5(cinfo, 1, JTRC_JFIF, -// cinfo.JFIF_major_version, cinfo.JFIF_minor_version, -// cinfo.X_density, cinfo.Y_density, cinfo.density_unit); - /* Validate thumbnail dimensions and issue appropriate messages */ - if (((data[12] & 0xFF) | (data[13]) & 0xFF) != 0) { -// TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, -// GETJOCTET(data[12]), GETJOCTET(data[13])); - } - totallen -= APP0_DATA_LEN; - if (totallen != ((data[12] & 0xFF) * (data[13] & 0xFF) * 3)) { -// TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, cast(int) totallen); - } - } else if (datalen >= 6 && - (data[0] & 0xFF) == 0x4A && - (data[1] & 0xFF) == 0x46 && - (data[2] & 0xFF) == 0x58 && - (data[3] & 0xFF) == 0x58 && - (data[4] & 0xFF) == 0) - { - /* Found JFIF "JFXX" extension APP0 marker */ - /* The library doesn't actually do anything with these, - * but we try to produce a helpful trace message. - */ - switch ((data[5]) & 0xFF) { - case 0x10: -// TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, cast(int) totallen); - break; - case 0x11: -// TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, cast(int) totallen); - break; - case 0x13: -// TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, cast(int) totallen); - break; - default: -// TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, GETJOCTET(data[5]), cast(int) totallen); - break; - } - } else { - /* Start of APP0 does not match "JFIF" or "JFXX", or too short */ -// TRACEMS1(cinfo, 1, JTRC_APP0, cast(int) totallen); - } + int totallen = datalen + remaining; + + if (datalen >= APP0_DATA_LEN && + (data[0] & 0xFF) == 0x4A && + (data[1] & 0xFF) == 0x46 && + (data[2] & 0xFF) == 0x49 && + (data[3] & 0xFF) == 0x46 && + (data[4] & 0xFF) == 0) + { + /* Found JFIF APP0 marker: save info */ + cinfo.saw_JFIF_marker = true; + cinfo.JFIF_major_version = (data[5]); + cinfo.JFIF_minor_version = cast(byte)(data[6] & 0xFF); + cinfo.density_unit = cast(byte)(data[7] & 0xFF); + cinfo.X_density = cast(short)(((data[8] & 0xFF) << 8) + (data[9] & 0xFF)); + cinfo.Y_density = cast(short)(((data[10] & 0xFF) << 8) + (data[11] & 0xFF)); + /* Check version. + * Major version must be 1, anything else signals an incompatible change. + * (We used to treat this as an error, but now it's a nonfatal warning, + * because some bozo at Hijaak couldn't read the spec.) + * Minor version should be 0..2, but process anyway if newer. + */ + if (cinfo.JFIF_major_version != 1) { +// WARNMS2(cinfo, JWRN_JFIF_MAJOR, +// cinfo.JFIF_major_version, cinfo.JFIF_minor_version); + } + /* Generate trace messages */ +// TRACEMS5(cinfo, 1, JTRC_JFIF, +// cinfo.JFIF_major_version, cinfo.JFIF_minor_version, +// cinfo.X_density, cinfo.Y_density, cinfo.density_unit); + /* Validate thumbnail dimensions and issue appropriate messages */ + if (((data[12] & 0xFF) | (data[13]) & 0xFF) != 0) { +// TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL, +// GETJOCTET(data[12]), GETJOCTET(data[13])); + } + totallen -= APP0_DATA_LEN; + if (totallen != ((data[12] & 0xFF) * (data[13] & 0xFF) * 3)) { +// TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, cast(int) totallen); + } + } else if (datalen >= 6 && + (data[0] & 0xFF) == 0x4A && + (data[1] & 0xFF) == 0x46 && + (data[2] & 0xFF) == 0x58 && + (data[3] & 0xFF) == 0x58 && + (data[4] & 0xFF) == 0) + { + /* Found JFIF "JFXX" extension APP0 marker */ + /* The library doesn't actually do anything with these, + * but we try to produce a helpful trace message. + */ + switch ((data[5]) & 0xFF) { + case 0x10: +// TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, cast(int) totallen); + break; + case 0x11: +// TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, cast(int) totallen); + break; + case 0x13: +// TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, cast(int) totallen); + break; + default: +// TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, GETJOCTET(data[5]), cast(int) totallen); + break; + } + } else { + /* Start of APP0 does not match "JFIF" or "JFXX", or too short */ +// TRACEMS1(cinfo, 1, JTRC_APP0, cast(int) totallen); + } } static void examine_app14 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining) @@ -5274,616 +5274,616 @@ * datalen is # of bytes at data[], remaining is length of rest of marker data. */ { - int /*version, flags0, flags1, */transform; - - if (datalen >= APP14_DATA_LEN && - (data[0] & 0xFF) == 0x41 && - (data[1] & 0xFF) == 0x64 && - (data[2] & 0xFF) == 0x6F && - (data[3] & 0xFF) == 0x62 && - (data[4] & 0xFF) == 0x65) - { - /* Found Adobe APP14 marker */ -// version = ((data[5] & 0xFF) << 8) + (data[6] & 0xFF); -// flags0 = ((data[7] & 0xFF) << 8) + (data[8] & 0xFF); -// flags1 = ((data[9] & 0xFF) << 8) + (data[10] & 0xFF); - transform = (data[11] & 0xFF); -// TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform); - cinfo.saw_Adobe_marker = true; - cinfo.Adobe_transform = cast(byte) transform; - } else { - /* Start of APP14 does not match "Adobe", or too short */ -// TRACEMS1(cinfo, 1, JTRC_APP14, cast(int) (datalen + remaining)); - } + int /*version, flags0, flags1, */transform; + + if (datalen >= APP14_DATA_LEN && + (data[0] & 0xFF) == 0x41 && + (data[1] & 0xFF) == 0x64 && + (data[2] & 0xFF) == 0x6F && + (data[3] & 0xFF) == 0x62 && + (data[4] & 0xFF) == 0x65) + { + /* Found Adobe APP14 marker */ +// version = ((data[5] & 0xFF) << 8) + (data[6] & 0xFF); +// flags0 = ((data[7] & 0xFF) << 8) + (data[8] & 0xFF); +// flags1 = ((data[9] & 0xFF) << 8) + (data[10] & 0xFF); + transform = (data[11] & 0xFF); +// TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform); + cinfo.saw_Adobe_marker = true; + cinfo.Adobe_transform = cast(byte) transform; + } else { + /* Start of APP14 does not match "Adobe", or too short */ +// TRACEMS1(cinfo, 1, JTRC_APP14, cast(int) (datalen + remaining)); + } } static bool get_soi (jpeg_decompress_struct cinfo) /* Process an SOI marker */ { - int i; - -// TRACEMS(cinfo, 1, JTRC_SOI); - - if (cinfo.marker.saw_SOI) - error(); -// ERREXIT(cinfo, JERR_SOI_DUPLICATE); - - /* Reset all parameters that are defined to be reset by SOI */ - - for (i = 0; i < NUM_ARITH_TBLS; i++) { - cinfo.arith_dc_L[i] = 0; - cinfo.arith_dc_U[i] = 1; - cinfo.arith_ac_K[i] = 5; - } - cinfo.restart_interval = 0; - - /* Set initial assumptions for colorspace etc */ - - cinfo.jpeg_color_space = JCS_UNKNOWN; - cinfo.CCIR601_sampling = false; /* Assume non-CCIR sampling??? */ - - cinfo.saw_JFIF_marker = false; - cinfo.JFIF_major_version = 1; /* set default JFIF APP0 values */ - cinfo.JFIF_minor_version = 1; - cinfo.density_unit = 0; - cinfo.X_density = 1; - cinfo.Y_density = 1; - cinfo.saw_Adobe_marker = false; - cinfo.Adobe_transform = 0; - - cinfo.marker.saw_SOI = true; - - return true; + int i; + +// TRACEMS(cinfo, 1, JTRC_SOI); + + if (cinfo.marker.saw_SOI) + error(); +// ERREXIT(cinfo, JERR_SOI_DUPLICATE); + + /* Reset all parameters that are defined to be reset by SOI */ + + for (i = 0; i < NUM_ARITH_TBLS; i++) { + cinfo.arith_dc_L[i] = 0; + cinfo.arith_dc_U[i] = 1; + cinfo.arith_ac_K[i] = 5; + } + cinfo.restart_interval = 0; + + /* Set initial assumptions for colorspace etc */ + + cinfo.jpeg_color_space = JCS_UNKNOWN; + cinfo.CCIR601_sampling = false; /* Assume non-CCIR sampling??? */ + + cinfo.saw_JFIF_marker = false; + cinfo.JFIF_major_version = 1; /* set default JFIF APP0 values */ + cinfo.JFIF_minor_version = 1; + cinfo.density_unit = 0; + cinfo.X_density = 1; + cinfo.Y_density = 1; + cinfo.saw_Adobe_marker = false; + cinfo.Adobe_transform = 0; + + cinfo.marker.saw_SOI = true; + + return true; } static void jinit_input_controller (jpeg_decompress_struct cinfo) { - /* Initialize state: can't use reset_input_controller since we don't - * want to try to reset other modules yet. - */ - jpeg_input_controller inputctl = cinfo.inputctl = new jpeg_input_controller(); - inputctl.has_multiple_scans = false; /* "unknown" would be better */ - inputctl.eoi_reached = false; - inputctl.inheaders = true; + /* Initialize state: can't use reset_input_controller since we don't + * want to try to reset other modules yet. + */ + jpeg_input_controller inputctl = cinfo.inputctl = new jpeg_input_controller(); + inputctl.has_multiple_scans = false; /* "unknown" would be better */ + inputctl.eoi_reached = false; + inputctl.inheaders = true; } static void reset_marker_reader (jpeg_decompress_struct cinfo) { - jpeg_marker_reader marker = cinfo.marker; - - cinfo.comp_info = null; /* until allocated by get_sof */ - cinfo.input_scan_number = 0; /* no SOS seen yet */ - cinfo.unread_marker = 0; /* no pending marker */ - marker.saw_SOI = false; /* set internal state too */ - marker.saw_SOF = false; - marker.discarded_bytes = 0; -// marker.cur_marker = null; + jpeg_marker_reader marker = cinfo.marker; + + cinfo.comp_info = null; /* until allocated by get_sof */ + cinfo.input_scan_number = 0; /* no SOS seen yet */ + cinfo.unread_marker = 0; /* no pending marker */ + marker.saw_SOI = false; /* set internal state too */ + marker.saw_SOF = false; + marker.discarded_bytes = 0; +// marker.cur_marker = null; } static void reset_input_controller (jpeg_decompress_struct cinfo) { - jpeg_input_controller inputctl = cinfo.inputctl; - - inputctl.has_multiple_scans = false; /* "unknown" would be better */ - inputctl.eoi_reached = false; - inputctl.inheaders = true; - /* Reset other modules */ - reset_marker_reader (cinfo); - /* Reset progression state -- would be cleaner if entropy decoder did this */ - cinfo.coef_bits = null; + jpeg_input_controller inputctl = cinfo.inputctl; + + inputctl.has_multiple_scans = false; /* "unknown" would be better */ + inputctl.eoi_reached = false; + inputctl.inheaders = true; + /* Reset other modules */ + reset_marker_reader (cinfo); + /* Reset progression state -- would be cleaner if entropy decoder did this */ + cinfo.coef_bits = null; } static void finish_output_pass (jpeg_decompress_struct cinfo) { - jpeg_decomp_master master = cinfo.master; - - if (cinfo.quantize_colors) { - error(SWT.ERROR_NOT_IMPLEMENTED); -// (*cinfo.cquantize.finish_pass) (cinfo); - } - master.pass_number++; + jpeg_decomp_master master = cinfo.master; + + if (cinfo.quantize_colors) { + error(SWT.ERROR_NOT_IMPLEMENTED); +// (*cinfo.cquantize.finish_pass) (cinfo); + } + master.pass_number++; } static void jpeg_destroy (jpeg_decompress_struct cinfo) { - /* We need only tell the memory manager to release everything. */ - /* NB: mem pointer is NULL if memory mgr failed to initialize. */ -// if (cinfo.mem != NULL) -// (*cinfo.mem.self_destruct) (cinfo); -// cinfo.mem = NULL; /* be safe if jpeg_destroy is called twice */ - cinfo.global_state = 0; /* mark it destroyed */ + /* We need only tell the memory manager to release everything. */ + /* NB: mem pointer is NULL if memory mgr failed to initialize. */ +// if (cinfo.mem != NULL) +// (*cinfo.mem.self_destruct) (cinfo); +// cinfo.mem = NULL; /* be safe if jpeg_destroy is called twice */ + cinfo.global_state = 0; /* mark it destroyed */ } static void jpeg_destroy_decompress (jpeg_decompress_struct cinfo) { - jpeg_destroy(cinfo); /* use common routine */ + jpeg_destroy(cinfo); /* use common routine */ } static bool jpeg_input_complete (jpeg_decompress_struct cinfo) { - /* Check for valid jpeg object */ - if (cinfo.global_state < DSTATE_START || cinfo.global_state > DSTATE_STOPPING) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - return cinfo.inputctl.eoi_reached; + /* Check for valid jpeg object */ + if (cinfo.global_state < DSTATE_START || cinfo.global_state > DSTATE_STOPPING) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + return cinfo.inputctl.eoi_reached; } static bool jpeg_start_output (jpeg_decompress_struct cinfo, int scan_number) { - if (cinfo.global_state != DSTATE_BUFIMAGE && cinfo.global_state != DSTATE_PRESCAN) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - /* Limit scan number to valid range */ - if (scan_number <= 0) - scan_number = 1; - if (cinfo.inputctl.eoi_reached && scan_number > cinfo.input_scan_number) - scan_number = cinfo.input_scan_number; - cinfo.output_scan_number = scan_number; - /* Perform any dummy output passes, and set up for the real pass */ - return output_pass_setup(cinfo); + if (cinfo.global_state != DSTATE_BUFIMAGE && cinfo.global_state != DSTATE_PRESCAN) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + /* Limit scan number to valid range */ + if (scan_number <= 0) + scan_number = 1; + if (cinfo.inputctl.eoi_reached && scan_number > cinfo.input_scan_number) + scan_number = cinfo.input_scan_number; + cinfo.output_scan_number = scan_number; + /* Perform any dummy output passes, and set up for the real pass */ + return output_pass_setup(cinfo); } static bool jpeg_finish_output (jpeg_decompress_struct cinfo) { - if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && cinfo.buffered_image) { - /* Terminate this pass. */ - /* We do not require the whole pass to have been completed. */ - finish_output_pass (cinfo); - cinfo.global_state = DSTATE_BUFPOST; - } else if (cinfo.global_state != DSTATE_BUFPOST) { - /* BUFPOST = repeat call after a suspension, anything else is error */ - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - } - /* Read markers looking for SOS or EOI */ - while (cinfo.input_scan_number <= cinfo.output_scan_number && !cinfo.inputctl.eoi_reached) { - if (consume_input (cinfo) == JPEG_SUSPENDED) - return false; /* Suspend, come back later */ - } - cinfo.global_state = DSTATE_BUFIMAGE; - return true; + if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && cinfo.buffered_image) { + /* Terminate this pass. */ + /* We do not require the whole pass to have been completed. */ + finish_output_pass (cinfo); + cinfo.global_state = DSTATE_BUFPOST; + } else if (cinfo.global_state != DSTATE_BUFPOST) { + /* BUFPOST = repeat call after a suspension, anything else is error */ + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + } + /* Read markers looking for SOS or EOI */ + while (cinfo.input_scan_number <= cinfo.output_scan_number && !cinfo.inputctl.eoi_reached) { + if (consume_input (cinfo) == JPEG_SUSPENDED) + return false; /* Suspend, come back later */ + } + cinfo.global_state = DSTATE_BUFIMAGE; + return true; } static bool jpeg_finish_decompress (jpeg_decompress_struct cinfo) { - if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && ! cinfo.buffered_image) { - /* Terminate final pass of non-buffered mode */ - if (cinfo.output_scanline < cinfo.output_height) - error(); -// ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); - finish_output_pass (cinfo); - cinfo.global_state = DSTATE_STOPPING; - } else if (cinfo.global_state == DSTATE_BUFIMAGE) { - /* Finishing after a buffered-image operation */ - cinfo.global_state = DSTATE_STOPPING; - } else if (cinfo.global_state != DSTATE_STOPPING) { - /* STOPPING = repeat call after a suspension, anything else is error */ - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - } - /* Read until EOI */ - while (! cinfo.inputctl.eoi_reached) { - if (consume_input (cinfo) == JPEG_SUSPENDED) - return false; /* Suspend, come back later */ - } - /* Do final cleanup */ -// (*cinfo.src.term_source) (cinfo); - /* We can use jpeg_abort to release memory and reset global_state */ - jpeg_abort(cinfo); - return true; + if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && ! cinfo.buffered_image) { + /* Terminate final pass of non-buffered mode */ + if (cinfo.output_scanline < cinfo.output_height) + error(); +// ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); + finish_output_pass (cinfo); + cinfo.global_state = DSTATE_STOPPING; + } else if (cinfo.global_state == DSTATE_BUFIMAGE) { + /* Finishing after a buffered-image operation */ + cinfo.global_state = DSTATE_STOPPING; + } else if (cinfo.global_state != DSTATE_STOPPING) { + /* STOPPING = repeat call after a suspension, anything else is error */ + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + } + /* Read until EOI */ + while (! cinfo.inputctl.eoi_reached) { + if (consume_input (cinfo) == JPEG_SUSPENDED) + return false; /* Suspend, come back later */ + } + /* Do final cleanup */ +// (*cinfo.src.term_source) (cinfo); + /* We can use jpeg_abort to release memory and reset global_state */ + jpeg_abort(cinfo); + return true; } static int jpeg_read_header (jpeg_decompress_struct cinfo, bool require_image) { - int retcode; - - if (cinfo.global_state != DSTATE_START && cinfo.global_state != DSTATE_INHEADER) - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - - retcode = jpeg_consume_input(cinfo); - - switch (retcode) { - case JPEG_REACHED_SOS: - retcode = JPEG_HEADER_OK; - break; - case JPEG_REACHED_EOI: - if (require_image) /* Complain if application wanted an image */ - error(); -// ERREXIT(cinfo, JERR_NO_IMAGE); - /* Reset to start state; it would be safer to require the application to - * call jpeg_abort, but we can't change it now for compatibility reasons. - * A side effect is to free any temporary memory (there shouldn't be any). - */ - jpeg_abort(cinfo); /* sets state = DSTATE_START */ - retcode = JPEG_HEADER_TABLES_ONLY; - break; - case JPEG_SUSPENDED: - /* no work */ - break; + int retcode; + + if (cinfo.global_state != DSTATE_START && cinfo.global_state != DSTATE_INHEADER) + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + + retcode = jpeg_consume_input(cinfo); + + switch (retcode) { + case JPEG_REACHED_SOS: + retcode = JPEG_HEADER_OK; + break; + case JPEG_REACHED_EOI: + if (require_image) /* Complain if application wanted an image */ + error(); +// ERREXIT(cinfo, JERR_NO_IMAGE); + /* Reset to start state; it would be safer to require the application to + * call jpeg_abort, but we can't change it now for compatibility reasons. + * A side effect is to free any temporary memory (there shouldn't be any). + */ + jpeg_abort(cinfo); /* sets state = DSTATE_START */ + retcode = JPEG_HEADER_TABLES_ONLY; + break; + case JPEG_SUSPENDED: + /* no work */ + break; default: - } - - return retcode; + } + + return retcode; } static int dummy_consume_data (jpeg_decompress_struct cinfo) { - return JPEG_SUSPENDED; /* Always indicate nothing was done */ + return JPEG_SUSPENDED; /* Always indicate nothing was done */ } static int consume_data (jpeg_decompress_struct cinfo) { - jpeg_d_coef_controller coef = cinfo.coef; - int MCU_col_num; /* index of current MCU within row */ - int blkn, ci, xindex, yindex, yoffset; - int start_col; -// short[][][][] buffer = new short[MAX_COMPS_IN_SCAN][][][]; - short[][] buffer_ptr; - jpeg_component_info compptr; - -// /* Align the virtual buffers for the components used in this scan. */ -// for (ci = 0; ci < cinfo.comps_in_scan; ci++) { -// compptr = cinfo.cur_comp_info[ci]; -// buffer[ci] = coef.whole_image[compptr.component_index]; -// /* Note: entropy decoder expects buffer to be zeroed, -// * but this is handled automatically by the memory manager -// * because we requested a pre-zeroed array. -// */ -// } - - /* Loop to process one whole iMCU row */ - for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) { - for (MCU_col_num = coef.MCU_ctr; MCU_col_num < cinfo.MCUs_per_row; MCU_col_num++) { - /* Construct list of pointers to DCT blocks belonging to this MCU */ - blkn = 0; /* index of current DCT block within MCU */ - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - start_col = MCU_col_num * compptr.MCU_width; - for (yindex = 0; yindex < compptr.MCU_height; yindex++) { -// buffer_ptr = buffer[ci][yindex+yoffset] + start_col; - buffer_ptr = coef.whole_image[compptr.component_index][yindex+yoffset+cinfo.input_iMCU_row*compptr.v_samp_factor]; - int buffer_ptr_offset = start_col; - for (xindex = 0; xindex < compptr.MCU_width; xindex++) { - coef.MCU_buffer[blkn++] = buffer_ptr[buffer_ptr_offset++]; - } - } - } - /* Try to fetch the MCU. */ - if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) { - /* Suspension forced; update state counters and exit */ - coef.MCU_vert_offset = yoffset; - coef.MCU_ctr = MCU_col_num; - return JPEG_SUSPENDED; - } - } - /* Completed an MCU row, but perhaps not an iMCU row */ - coef.MCU_ctr = 0; - } - /* Completed the iMCU row, advance counters for next one */ - if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) { - coef.start_iMCU_row(cinfo); - return JPEG_ROW_COMPLETED; - } - /* Completed the scan */ - finish_input_pass (cinfo); - return JPEG_SCAN_COMPLETED; + jpeg_d_coef_controller coef = cinfo.coef; + int MCU_col_num; /* index of current MCU within row */ + int blkn, ci, xindex, yindex, yoffset; + int start_col; +// short[][][][] buffer = new short[MAX_COMPS_IN_SCAN][][][]; + short[][] buffer_ptr; + jpeg_component_info compptr; + +// /* Align the virtual buffers for the components used in this scan. */ +// for (ci = 0; ci < cinfo.comps_in_scan; ci++) { +// compptr = cinfo.cur_comp_info[ci]; +// buffer[ci] = coef.whole_image[compptr.component_index]; +// /* Note: entropy decoder expects buffer to be zeroed, +// * but this is handled automatically by the memory manager +// * because we requested a pre-zeroed array. +// */ +// } + + /* Loop to process one whole iMCU row */ + for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) { + for (MCU_col_num = coef.MCU_ctr; MCU_col_num < cinfo.MCUs_per_row; MCU_col_num++) { + /* Construct list of pointers to DCT blocks belonging to this MCU */ + blkn = 0; /* index of current DCT block within MCU */ + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + start_col = MCU_col_num * compptr.MCU_width; + for (yindex = 0; yindex < compptr.MCU_height; yindex++) { +// buffer_ptr = buffer[ci][yindex+yoffset] + start_col; + buffer_ptr = coef.whole_image[compptr.component_index][yindex+yoffset+cinfo.input_iMCU_row*compptr.v_samp_factor]; + int buffer_ptr_offset = start_col; + for (xindex = 0; xindex < compptr.MCU_width; xindex++) { + coef.MCU_buffer[blkn++] = buffer_ptr[buffer_ptr_offset++]; + } + } + } + /* Try to fetch the MCU. */ + if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) { + /* Suspension forced; update state counters and exit */ + coef.MCU_vert_offset = yoffset; + coef.MCU_ctr = MCU_col_num; + return JPEG_SUSPENDED; + } + } + /* Completed an MCU row, but perhaps not an iMCU row */ + coef.MCU_ctr = 0; + } + /* Completed the iMCU row, advance counters for next one */ + if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) { + coef.start_iMCU_row(cinfo); + return JPEG_ROW_COMPLETED; + } + /* Completed the scan */ + finish_input_pass (cinfo); + return JPEG_SCAN_COMPLETED; } static int consume_input (jpeg_decompress_struct cinfo) { - switch (cinfo.inputctl.consume_input) { - case COEF_CONSUME_INPUT: - switch (cinfo.coef.consume_data) { - case CONSUME_DATA: return consume_data(cinfo); - case DUMMY_CONSUME_DATA: return dummy_consume_data(cinfo); - default: error(); - } - break; - case INPUT_CONSUME_INPUT: - return consume_markers(cinfo); - default: - error(); - } - return 0; + switch (cinfo.inputctl.consume_input) { + case COEF_CONSUME_INPUT: + switch (cinfo.coef.consume_data) { + case CONSUME_DATA: return consume_data(cinfo); + case DUMMY_CONSUME_DATA: return dummy_consume_data(cinfo); + default: error(); + } + break; + case INPUT_CONSUME_INPUT: + return consume_markers(cinfo); + default: + error(); + } + return 0; } static bool fill_input_buffer(jpeg_decompress_struct cinfo) { - try { - InputStream inputStream = cinfo.inputStream; - int nbytes = inputStream.read(cinfo.buffer); - if (nbytes <= 0) { - if (cinfo.start_of_file) /* Treat empty input file as fatal error */ - error(); -// ERREXIT(cinfo, JERR_INPUT_EMPTY); -// WARNMS(cinfo, JWRN_JPEG_EOF); - /* Insert a fake EOI marker */ - cinfo.buffer[0] = cast(byte)0xFF; - cinfo.buffer[1] = cast(byte)M_EOI; - nbytes = 2; - } - cinfo.bytes_in_buffer = nbytes; - cinfo.bytes_offset = 0; - cinfo.start_of_file = false; - } catch (IOException e) { - error(SWT.ERROR_IO); - return false; - } - return true; + try { + InputStream inputStream = cinfo.inputStream; + int nbytes = inputStream.read(cinfo.buffer); + if (nbytes <= 0) { + if (cinfo.start_of_file) /* Treat empty input file as fatal error */ + error(); +// ERREXIT(cinfo, JERR_INPUT_EMPTY); +// WARNMS(cinfo, JWRN_JPEG_EOF); + /* Insert a fake EOI marker */ + cinfo.buffer[0] = cast(byte)0xFF; + cinfo.buffer[1] = cast(byte)M_EOI; + nbytes = 2; + } + cinfo.bytes_in_buffer = nbytes; + cinfo.bytes_offset = 0; + cinfo.start_of_file = false; + } catch (IOException e) { + error(SWT.ERROR_IO); + return false; + } + return true; } static bool first_marker (jpeg_decompress_struct cinfo) { - /* Like next_marker, but used to obtain the initial SOI marker. */ - /* For this marker, we do not allow preceding garbage or fill; otherwise, - * we might well scan an entire input file before realizing it ain't JPEG. - * If an application wants to process non-JFIF files, it must seek to the - * SOI before calling the JPEG library. - */ - int c, c2; - - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c2 = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - if (c != 0xFF || c2 != M_SOI) - error(); -// ERREXIT2(cinfo, JERR_NO_SOI, c, c2); - - cinfo.unread_marker = c2; - - return true; + /* Like next_marker, but used to obtain the initial SOI marker. */ + /* For this marker, we do not allow preceding garbage or fill; otherwise, + * we might well scan an entire input file before realizing it ain't JPEG. + * If an application wants to process non-JFIF files, it must seek to the + * SOI before calling the JPEG library. + */ + int c, c2; + + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c2 = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + if (c != 0xFF || c2 != M_SOI) + error(); +// ERREXIT2(cinfo, JERR_NO_SOI, c, c2); + + cinfo.unread_marker = c2; + + return true; } static bool next_marker (jpeg_decompress_struct cinfo) { - int c; - - for (;;) { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - /* Skip any non-FF bytes. - * This may look a bit inefficient, but it will not occur in a valid file. - * We sync after each discarded byte so that a suspending data source - * can discard the byte from its buffer. - */ - while (c != 0xFF) { - cinfo.marker.discarded_bytes++; - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - } - /* This loop swallows any duplicate FF bytes. Extra FFs are legal as - * pad bytes, so don't count them in discarded_bytes. We assume there - * will not be so many consecutive FF bytes as to overflow a suspending - * data source's input buffer. - */ - do { - if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); - c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; - } while (c == 0xFF); - if (c != 0) - break; /* found a valid marker, exit loop */ - /* Reach here if we found a stuffed-zero data sequence (FF/00). - * Discard it and loop back to try again. - */ - cinfo.marker.discarded_bytes += 2; - } - - if (cinfo.marker.discarded_bytes != 0) { -// WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo.marker.discarded_bytes, c); - cinfo.marker.discarded_bytes = 0; - } - - cinfo.unread_marker = c; - - return true; + int c; + + for (;;) { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + /* Skip any non-FF bytes. + * This may look a bit inefficient, but it will not occur in a valid file. + * We sync after each discarded byte so that a suspending data source + * can discard the byte from its buffer. + */ + while (c != 0xFF) { + cinfo.marker.discarded_bytes++; + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + } + /* This loop swallows any duplicate FF bytes. Extra FFs are legal as + * pad bytes, so don't count them in discarded_bytes. We assume there + * will not be so many consecutive FF bytes as to overflow a suspending + * data source's input buffer. + */ + do { + if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo); + c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF; + } while (c == 0xFF); + if (c != 0) + break; /* found a valid marker, exit loop */ + /* Reach here if we found a stuffed-zero data sequence (FF/00). + * Discard it and loop back to try again. + */ + cinfo.marker.discarded_bytes += 2; + } + + if (cinfo.marker.discarded_bytes != 0) { +// WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo.marker.discarded_bytes, c); + cinfo.marker.discarded_bytes = 0; + } + + cinfo.unread_marker = c; + + return true; } static int read_markers (jpeg_decompress_struct cinfo) { - /* Outer loop repeats once for each marker. */ - for (;;) { - /* Collect the marker proper, unless we already did. */ - /* NB: first_marker() enforces the requirement that SOI appear first. */ - if (cinfo.unread_marker == 0) { - if (! cinfo.marker.saw_SOI) { - if (! first_marker(cinfo)) - return JPEG_SUSPENDED; - } else { - if (! next_marker(cinfo)) - return JPEG_SUSPENDED; - } - } - /* At this point cinfo.unread_marker contains the marker code and the - * input point is just past the marker proper, but before any parameters. - * A suspension will cause us to return with this state still true. - */ - switch (cinfo.unread_marker) { - case M_SOI: - if (! get_soi(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_SOF0: /* Baseline */ - case M_SOF1: /* Extended sequential, Huffman */ - if (! get_sof(cinfo, false, false)) - return JPEG_SUSPENDED; - break; - - case M_SOF2: /* Progressive, Huffman */ - if (! get_sof(cinfo, true, false)) - return JPEG_SUSPENDED; - break; - - case M_SOF9: /* Extended sequential, arithmetic */ - if (! get_sof(cinfo, false, true)) - return JPEG_SUSPENDED; - break; - - case M_SOF10: /* Progressive, arithmetic */ - if (! get_sof(cinfo, true, true)) - return JPEG_SUSPENDED; - break; - - /* Currently unsupported SOFn types */ - case M_SOF3: /* Lossless, Huffman */ - case M_SOF5: /* Differential sequential, Huffman */ - case M_SOF6: /* Differential progressive, Huffman */ - case M_SOF7: /* Differential lossless, Huffman */ - case M_JPG: /* Reserved for JPEG extensions */ - case M_SOF11: /* Lossless, arithmetic */ - case M_SOF13: /* Differential sequential, arithmetic */ - case M_SOF14: /* Differential progressive, arithmetic */ - case M_SOF15: /* Differential lossless, arithmetic */ - error(); -// ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo.unread_marker); - break; - - case M_SOS: - if (! get_sos(cinfo)) - return JPEG_SUSPENDED; - cinfo.unread_marker = 0; /* processed the marker */ - return JPEG_REACHED_SOS; - - case M_EOI: -// TRACEMS(cinfo, 1, JTRC_EOI); - cinfo.unread_marker = 0; /* processed the marker */ - return JPEG_REACHED_EOI; - - case M_DAC: - if (! get_dac(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_DHT: - if (! get_dht(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_DQT: - if (! get_dqt(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_DRI: - if (! get_dri(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_APP0: - case M_APP1: - case M_APP2: - case M_APP3: - case M_APP4: - case M_APP5: - case M_APP6: - case M_APP7: - case M_APP8: - case M_APP9: - case M_APP10: - case M_APP11: - case M_APP12: - case M_APP13: - case M_APP14: - case M_APP15: - if (! process_APPn(cinfo.unread_marker - M_APP0, cinfo)) - return JPEG_SUSPENDED; - break; - - case M_COM: - if (! process_COM(cinfo)) - return JPEG_SUSPENDED; - break; - - case M_RST0: /* these are all parameterless */ - case M_RST1: - case M_RST2: - case M_RST3: - case M_RST4: - case M_RST5: - case M_RST6: - case M_RST7: - case M_TEM: -// TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo.unread_marker); - break; - - case M_DNL: /* Ignore DNL ... perhaps the wrong thing */ - if (! skip_variable(cinfo)) - return JPEG_SUSPENDED; - break; - - default: /* must be DHP, EXP, JPGn, or RESn */ - /* For now, we treat the reserved markers as fatal errors since they are - * likely to be used to signal incompatible JPEG Part 3 extensions. - * Once the JPEG 3 version-number marker is well defined, this code - * ought to change! - */ - error(); - // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker); - break; - } - /* Successfully processed marker, so reset state variable */ - cinfo.unread_marker = 0; - } /* end loop */ + /* Outer loop repeats once for each marker. */ + for (;;) { + /* Collect the marker proper, unless we already did. */ + /* NB: first_marker() enforces the requirement that SOI appear first. */ + if (cinfo.unread_marker == 0) { + if (! cinfo.marker.saw_SOI) { + if (! first_marker(cinfo)) + return JPEG_SUSPENDED; + } else { + if (! next_marker(cinfo)) + return JPEG_SUSPENDED; + } + } + /* At this point cinfo.unread_marker contains the marker code and the + * input point is just past the marker proper, but before any parameters. + * A suspension will cause us to return with this state still true. + */ + switch (cinfo.unread_marker) { + case M_SOI: + if (! get_soi(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_SOF0: /* Baseline */ + case M_SOF1: /* Extended sequential, Huffman */ + if (! get_sof(cinfo, false, false)) + return JPEG_SUSPENDED; + break; + + case M_SOF2: /* Progressive, Huffman */ + if (! get_sof(cinfo, true, false)) + return JPEG_SUSPENDED; + break; + + case M_SOF9: /* Extended sequential, arithmetic */ + if (! get_sof(cinfo, false, true)) + return JPEG_SUSPENDED; + break; + + case M_SOF10: /* Progressive, arithmetic */ + if (! get_sof(cinfo, true, true)) + return JPEG_SUSPENDED; + break; + + /* Currently unsupported SOFn types */ + case M_SOF3: /* Lossless, Huffman */ + case M_SOF5: /* Differential sequential, Huffman */ + case M_SOF6: /* Differential progressive, Huffman */ + case M_SOF7: /* Differential lossless, Huffman */ + case M_JPG: /* Reserved for JPEG extensions */ + case M_SOF11: /* Lossless, arithmetic */ + case M_SOF13: /* Differential sequential, arithmetic */ + case M_SOF14: /* Differential progressive, arithmetic */ + case M_SOF15: /* Differential lossless, arithmetic */ + error(); +// ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo.unread_marker); + break; + + case M_SOS: + if (! get_sos(cinfo)) + return JPEG_SUSPENDED; + cinfo.unread_marker = 0; /* processed the marker */ + return JPEG_REACHED_SOS; + + case M_EOI: +// TRACEMS(cinfo, 1, JTRC_EOI); + cinfo.unread_marker = 0; /* processed the marker */ + return JPEG_REACHED_EOI; + + case M_DAC: + if (! get_dac(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DHT: + if (! get_dht(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DQT: + if (! get_dqt(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_DRI: + if (! get_dri(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_APP0: + case M_APP1: + case M_APP2: + case M_APP3: + case M_APP4: + case M_APP5: + case M_APP6: + case M_APP7: + case M_APP8: + case M_APP9: + case M_APP10: + case M_APP11: + case M_APP12: + case M_APP13: + case M_APP14: + case M_APP15: + if (! process_APPn(cinfo.unread_marker - M_APP0, cinfo)) + return JPEG_SUSPENDED; + break; + + case M_COM: + if (! process_COM(cinfo)) + return JPEG_SUSPENDED; + break; + + case M_RST0: /* these are all parameterless */ + case M_RST1: + case M_RST2: + case M_RST3: + case M_RST4: + case M_RST5: + case M_RST6: + case M_RST7: + case M_TEM: +// TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo.unread_marker); + break; + + case M_DNL: /* Ignore DNL ... perhaps the wrong thing */ + if (! skip_variable(cinfo)) + return JPEG_SUSPENDED; + break; + + default: /* must be DHP, EXP, JPGn, or RESn */ + /* For now, we treat the reserved markers as fatal errors since they are + * likely to be used to signal incompatible JPEG Part 3 extensions. + * Once the JPEG 3 version-number marker is well defined, this code + * ought to change! + */ + error(); + // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker); + break; + } + /* Successfully processed marker, so reset state variable */ + cinfo.unread_marker = 0; + } /* end loop */ } static long jdiv_round_up (long a, long b) /* Compute a/b rounded up to next integer, ie, ceil(a/b) */ /* Assumes a >= 0, b > 0 */ { - return (a + b - 1) / b; + return (a + b - 1) / b; } static void initial_setup (jpeg_decompress_struct cinfo) /* Called once, when first SOS marker is reached */ { - int ci; - jpeg_component_info compptr; - - /* Make sure image isn't bigger than I can handle */ - if (cinfo.image_height > JPEG_MAX_DIMENSION || cinfo.image_width > JPEG_MAX_DIMENSION) - error(); -// ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); - - /* For now, precision must match compiled-in value... */ - if (cinfo.data_precision != BITS_IN_JSAMPLE) - error(" [data precision=" ~ to!(char[])(cinfo.data_precision) ~ "]"); -// ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo.data_precision); - - /* Check that number of components won't exceed internal array sizes */ - if (cinfo.num_components > MAX_COMPONENTS) - error(); -// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.num_components, MAX_COMPONENTS); - - /* Compute maximum sampling factors; check factor validity */ - cinfo.max_h_samp_factor = 1; - cinfo.max_v_samp_factor = 1; - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - if (compptr.h_samp_factor<=0 || compptr.h_samp_factor>MAX_SAMP_FACTOR || compptr.v_samp_factor<=0 || compptr.v_samp_factor>MAX_SAMP_FACTOR) - error(); -// ERREXIT(cinfo, JERR_BAD_SAMPLING); - cinfo.max_h_samp_factor = Math.max(cinfo.max_h_samp_factor, compptr.h_samp_factor); - cinfo.max_v_samp_factor = Math.max(cinfo.max_v_samp_factor, compptr.v_samp_factor); - } - - /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE. - * In the full decompressor, this will be overridden by jdmaster.c; - * but in the transcoder, jdmaster.c is not used, so we must do it here. - */ - cinfo.min_DCT_scaled_size = DCTSIZE; - - /* Compute dimensions of components */ - for (ci = 0; ci < cinfo.num_components; ci++) { - compptr = cinfo.comp_info[ci]; - compptr.DCT_scaled_size = DCTSIZE; - /* Size in DCT blocks */ - compptr.width_in_blocks = cast(int)jdiv_round_up(cast(long) cinfo.image_width * cast(long) compptr.h_samp_factor, (cinfo.max_h_samp_factor * DCTSIZE)); - compptr.height_in_blocks = cast(int)jdiv_round_up(cast(long) cinfo.image_height * cast(long) compptr.v_samp_factor, (cinfo.max_v_samp_factor * DCTSIZE)); - /* downsampled_width and downsampled_height will also be overridden by - * jdmaster.c if we are doing full decompression. The transcoder library - * doesn't use these values, but the calling application might. - */ - /* Size in samples */ - compptr.downsampled_width = cast(int)jdiv_round_up(cast(long) cinfo.image_width * cast(long) compptr.h_samp_factor, cinfo.max_h_samp_factor); - compptr.downsampled_height = cast(int)jdiv_round_up(cast(long) cinfo.image_height * cast(long) compptr.v_samp_factor, cinfo.max_v_samp_factor); - /* Mark component needed, until color conversion says otherwise */ - compptr.component_needed = true; - /* Mark no quantization table yet saved for component */ - compptr.quant_table = null; - } - - /* Compute number of fully interleaved MCU rows. */ - cinfo.total_iMCU_rows = cast(int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE)); - - /* Decide whether file contains multiple scans */ - if (cinfo.comps_in_scan < cinfo.num_components || cinfo.progressive_mode) - cinfo.inputctl.has_multiple_scans = true; - else - cinfo.inputctl.has_multiple_scans = false; + int ci; + jpeg_component_info compptr; + + /* Make sure image isn't bigger than I can handle */ + if (cinfo.image_height > JPEG_MAX_DIMENSION || cinfo.image_width > JPEG_MAX_DIMENSION) + error(); +// ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); + + /* For now, precision must match compiled-in value... */ + if (cinfo.data_precision != BITS_IN_JSAMPLE) + error(" [data precision=" ~ to!(char[])(cinfo.data_precision) ~ "]"); +// ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo.data_precision); + + /* Check that number of components won't exceed internal array sizes */ + if (cinfo.num_components > MAX_COMPONENTS) + error(); +// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.num_components, MAX_COMPONENTS); + + /* Compute maximum sampling factors; check factor validity */ + cinfo.max_h_samp_factor = 1; + cinfo.max_v_samp_factor = 1; + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + if (compptr.h_samp_factor<=0 || compptr.h_samp_factor>MAX_SAMP_FACTOR || compptr.v_samp_factor<=0 || compptr.v_samp_factor>MAX_SAMP_FACTOR) + error(); +// ERREXIT(cinfo, JERR_BAD_SAMPLING); + cinfo.max_h_samp_factor = Math.max(cinfo.max_h_samp_factor, compptr.h_samp_factor); + cinfo.max_v_samp_factor = Math.max(cinfo.max_v_samp_factor, compptr.v_samp_factor); + } + + /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE. + * In the full decompressor, this will be overridden by jdmaster.c; + * but in the transcoder, jdmaster.c is not used, so we must do it here. + */ + cinfo.min_DCT_scaled_size = DCTSIZE; + + /* Compute dimensions of components */ + for (ci = 0; ci < cinfo.num_components; ci++) { + compptr = cinfo.comp_info[ci]; + compptr.DCT_scaled_size = DCTSIZE; + /* Size in DCT blocks */ + compptr.width_in_blocks = cast(int)jdiv_round_up(cast(long) cinfo.image_width * cast(long) compptr.h_samp_factor, (cinfo.max_h_samp_factor * DCTSIZE)); + compptr.height_in_blocks = cast(int)jdiv_round_up(cast(long) cinfo.image_height * cast(long) compptr.v_samp_factor, (cinfo.max_v_samp_factor * DCTSIZE)); + /* downsampled_width and downsampled_height will also be overridden by + * jdmaster.c if we are doing full decompression. The transcoder library + * doesn't use these values, but the calling application might. + */ + /* Size in samples */ + compptr.downsampled_width = cast(int)jdiv_round_up(cast(long) cinfo.image_width * cast(long) compptr.h_samp_factor, cinfo.max_h_samp_factor); + compptr.downsampled_height = cast(int)jdiv_round_up(cast(long) cinfo.image_height * cast(long) compptr.v_samp_factor, cinfo.max_v_samp_factor); + /* Mark component needed, until color conversion says otherwise */ + compptr.component_needed = true; + /* Mark no quantization table yet saved for component */ + compptr.quant_table = null; + } + + /* Compute number of fully interleaved MCU rows. */ + cinfo.total_iMCU_rows = cast(int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE)); + + /* Decide whether file contains multiple scans */ + if (cinfo.comps_in_scan < cinfo.num_components || cinfo.progressive_mode) + cinfo.inputctl.has_multiple_scans = true; + else + cinfo.inputctl.has_multiple_scans = false; } @@ -5891,502 +5891,502 @@ /* Do computations that are needed before processing a JPEG scan */ /* cinfo.comps_in_scan and cinfo.cur_comp_info[] were set from SOS marker */ { - int ci, mcublks, tmp = 0; - jpeg_component_info compptr; - - if (cinfo.comps_in_scan == 1) { - - /* Noninterleaved (single-component) scan */ - compptr = cinfo.cur_comp_info[0]; - - /* Overall image size in MCUs */ - cinfo.MCUs_per_row = compptr.width_in_blocks; - cinfo.MCU_rows_in_scan = compptr.height_in_blocks; - - /* For noninterleaved scan, always one block per MCU */ - compptr.MCU_width = 1; - compptr.MCU_height = 1; - compptr.MCU_blocks = 1; - compptr.MCU_sample_width = compptr.DCT_scaled_size; - compptr.last_col_width = 1; - /* For noninterleaved scans, it is convenient to define last_row_height - * as the number of block rows present in the last iMCU row. - */ - tmp = (compptr.height_in_blocks % compptr.v_samp_factor); - if (tmp == 0) tmp = compptr.v_samp_factor; - compptr.last_row_height = tmp; - - /* Prepare array describing MCU composition */ - cinfo.blocks_in_MCU = 1; - cinfo.MCU_membership[0] = 0; - - } else { - - /* Interleaved (multi-component) scan */ - if (cinfo.comps_in_scan <= 0 || cinfo.comps_in_scan > MAX_COMPS_IN_SCAN) - error(); -// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.comps_in_scan, MAX_COMPS_IN_SCAN); - - /* Overall image size in MCUs */ - cinfo.MCUs_per_row = cast(int)jdiv_round_up( cinfo.image_width, (cinfo.max_h_samp_factor*DCTSIZE)); - cinfo.MCU_rows_in_scan = cast(int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE)); - - cinfo.blocks_in_MCU = 0; - - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - /* Sampling factors give # of blocks of component in each MCU */ - compptr.MCU_width = compptr.h_samp_factor; - compptr.MCU_height = compptr.v_samp_factor; - compptr.MCU_blocks = compptr.MCU_width * compptr.MCU_height; - compptr.MCU_sample_width = compptr.MCU_width * compptr.DCT_scaled_size; - /* Figure number of non-dummy blocks in last MCU column & row */ - tmp = (compptr.width_in_blocks % compptr.MCU_width); - if (tmp == 0) tmp = compptr.MCU_width; - compptr.last_col_width = tmp; - tmp = (compptr.height_in_blocks % compptr.MCU_height); - if (tmp == 0) tmp = compptr.MCU_height; - compptr.last_row_height = tmp; - /* Prepare array describing MCU composition */ - mcublks = compptr.MCU_blocks; - if (cinfo.blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU) - error(); -// ERREXIT(cinfo, JERR_BAD_MCU_SIZE); - while (mcublks-- > 0) { - cinfo.MCU_membership[cinfo.blocks_in_MCU++] = ci; - } - } - - } + int ci, mcublks, tmp = 0; + jpeg_component_info compptr; + + if (cinfo.comps_in_scan == 1) { + + /* Noninterleaved (single-component) scan */ + compptr = cinfo.cur_comp_info[0]; + + /* Overall image size in MCUs */ + cinfo.MCUs_per_row = compptr.width_in_blocks; + cinfo.MCU_rows_in_scan = compptr.height_in_blocks; + + /* For noninterleaved scan, always one block per MCU */ + compptr.MCU_width = 1; + compptr.MCU_height = 1; + compptr.MCU_blocks = 1; + compptr.MCU_sample_width = compptr.DCT_scaled_size; + compptr.last_col_width = 1; + /* For noninterleaved scans, it is convenient to define last_row_height + * as the number of block rows present in the last iMCU row. + */ + tmp = (compptr.height_in_blocks % compptr.v_samp_factor); + if (tmp == 0) tmp = compptr.v_samp_factor; + compptr.last_row_height = tmp; + + /* Prepare array describing MCU composition */ + cinfo.blocks_in_MCU = 1; + cinfo.MCU_membership[0] = 0; + + } else { + + /* Interleaved (multi-component) scan */ + if (cinfo.comps_in_scan <= 0 || cinfo.comps_in_scan > MAX_COMPS_IN_SCAN) + error(); +// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.comps_in_scan, MAX_COMPS_IN_SCAN); + + /* Overall image size in MCUs */ + cinfo.MCUs_per_row = cast(int)jdiv_round_up( cinfo.image_width, (cinfo.max_h_samp_factor*DCTSIZE)); + cinfo.MCU_rows_in_scan = cast(int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE)); + + cinfo.blocks_in_MCU = 0; + + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + /* Sampling factors give # of blocks of component in each MCU */ + compptr.MCU_width = compptr.h_samp_factor; + compptr.MCU_height = compptr.v_samp_factor; + compptr.MCU_blocks = compptr.MCU_width * compptr.MCU_height; + compptr.MCU_sample_width = compptr.MCU_width * compptr.DCT_scaled_size; + /* Figure number of non-dummy blocks in last MCU column & row */ + tmp = (compptr.width_in_blocks % compptr.MCU_width); + if (tmp == 0) tmp = compptr.MCU_width; + compptr.last_col_width = tmp; + tmp = (compptr.height_in_blocks % compptr.MCU_height); + if (tmp == 0) tmp = compptr.MCU_height; + compptr.last_row_height = tmp; + /* Prepare array describing MCU composition */ + mcublks = compptr.MCU_blocks; + if (cinfo.blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU) + error(); +// ERREXIT(cinfo, JERR_BAD_MCU_SIZE); + while (mcublks-- > 0) { + cinfo.MCU_membership[cinfo.blocks_in_MCU++] = ci; + } + } + + } } static void latch_quant_tables (jpeg_decompress_struct cinfo) { - int ci, qtblno; - jpeg_component_info compptr; - JQUANT_TBL qtbl; - - for (ci = 0; ci < cinfo.comps_in_scan; ci++) { - compptr = cinfo.cur_comp_info[ci]; - /* No work if we already saved Q-table for this component */ - if (compptr.quant_table != null) - continue; - /* Make sure specified quantization table is present */ - qtblno = compptr.quant_tbl_no; - if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo.quant_tbl_ptrs[qtblno] == null) - error(); -// ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); - /* OK, save away the quantization table */ - qtbl = new JQUANT_TBL(); + int ci, qtblno; + jpeg_component_info compptr; + JQUANT_TBL qtbl; + + for (ci = 0; ci < cinfo.comps_in_scan; ci++) { + compptr = cinfo.cur_comp_info[ci]; + /* No work if we already saved Q-table for this component */ + if (compptr.quant_table != null) + continue; + /* Make sure specified quantization table is present */ + qtblno = compptr.quant_tbl_no; + if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo.quant_tbl_ptrs[qtblno] == null) + error(); +// ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); + /* OK, save away the quantization table */ + qtbl = new JQUANT_TBL(); System.arraycopy(cinfo.quant_tbl_ptrs[qtblno].quantval, 0, qtbl.quantval, 0, qtbl.quantval.length); - qtbl.sent_table = cinfo.quant_tbl_ptrs[qtblno].sent_table; - compptr.quant_table = qtbl; - } + qtbl.sent_table = cinfo.quant_tbl_ptrs[qtblno].sent_table; + compptr.quant_table = qtbl; + } } static void jpeg_make_d_derived_tbl (jpeg_decompress_struct cinfo, bool isDC, int tblno, d_derived_tbl dtbl) { - JHUFF_TBL htbl; - int p, i = 0, l, si, numsymbols; - int lookbits, ctr; - byte[] huffsize = new byte[257]; - int[] huffcode = new int[257]; - int code; - - /* Note that huffsize[] and huffcode[] are filled in code-length order, - * paralleling the order of the symbols themselves in htbl.huffval[]. - */ - - /* Find the input Huffman table */ - if (tblno < 0 || tblno >= NUM_HUFF_TBLS) - error(); -// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); - htbl = isDC ? cinfo.dc_huff_tbl_ptrs[tblno] : cinfo.ac_huff_tbl_ptrs[tblno]; - if (htbl == null) - error(); -// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); - - /* Allocate a workspace if we haven't already done so. */ - dtbl.pub = htbl; /* fill in back link */ - - /* Figure C.1: make table of Huffman code length for each symbol */ - - p = 0; - for (l = 1; l <= 16; l++) { - i = htbl.bits[l] & 0xFF; - if (i < 0 || p + i > 256) /* protect against table overrun */ - error(); -// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); - while (i-- != 0) - huffsize[p++] = cast(byte) l; - } - huffsize[p] = 0; - numsymbols = p; - - /* Figure C.2: generate the codes themselves */ - /* We also validate that the counts represent a legal Huffman code tree. */ - - code = 0; - si = huffsize[0]; - p = 0; - while ((huffsize[p]) != 0) { - while (( huffsize[p]) == si) { - huffcode[p++] = code; - code++; - } - /* code is now 1 more than the last code used for codelength si; but - * it must still fit in si bits, since no code is allowed to be all ones. - */ - if (( code) >= (( 1) << si)) - error(); -// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); - code <<= 1; - si++; - } - - /* Figure F.15: generate decoding tables for bit-sequential decoding */ - - p = 0; - for (l = 1; l <= 16; l++) { - if ((htbl.bits[l] & 0xFF) != 0) { - /* valoffset[l] = huffval[] index of 1st symbol of code length l, - * minus the minimum code of length l - */ - dtbl.valoffset[l] = p - huffcode[p]; - p += (htbl.bits[l] & 0xFF); - dtbl.maxcode[l] = huffcode[p-1]; /* maximum code of length l */ - } else { - dtbl.maxcode[l] = -1; /* -1 if no codes of this length */ - } - } - dtbl.maxcode[17] = 0xFFFFF; /* ensures jpeg_huff_decode terminates */ - - /* Compute lookahead tables to speed up decoding. - * First we set all the table entries to 0, indicating "too long"; - * then we iterate through the Huffman codes that are short enough and - * fill in all the entries that correspond to bit sequences starting - * with that code. - */ - - for (int j = 0; j < dtbl.look_nbits.length; j++) { - dtbl.look_nbits[j] = 0; - } - - p = 0; - for (l = 1; l <= HUFF_LOOKAHEAD; l++) { - for (i = 1; i <= (htbl.bits[l] & 0xFF); i++, p++) { - /* l = current code's length, p = its index in huffcode[] & huffval[]. */ - /* Generate left-justified code followed by all possible bit sequences */ - lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l); - for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) { - dtbl.look_nbits[lookbits] = l; - dtbl.look_sym[lookbits] = htbl.huffval[p]; - lookbits++; - } - } - } - - /* Validate symbols as being reasonable. - * For AC tables, we make no check, but accept all byte values 0..255. - * For DC tables, we require the symbols to be in range 0..15. - * (Tighter bounds could be applied depending on the data depth and mode, - * but this is sufficient to ensure safe decoding.) - */ - if (isDC) { - for (i = 0; i < numsymbols; i++) { - int sym = htbl.huffval[i] & 0xFF; - if (sym < 0 || sym > 15) - error(); -// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); - } - } + JHUFF_TBL htbl; + int p, i = 0, l, si, numsymbols; + int lookbits, ctr; + byte[] huffsize = new byte[257]; + int[] huffcode = new int[257]; + int code; + + /* Note that huffsize[] and huffcode[] are filled in code-length order, + * paralleling the order of the symbols themselves in htbl.huffval[]. + */ + + /* Find the input Huffman table */ + if (tblno < 0 || tblno >= NUM_HUFF_TBLS) + error(); +// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + htbl = isDC ? cinfo.dc_huff_tbl_ptrs[tblno] : cinfo.ac_huff_tbl_ptrs[tblno]; + if (htbl == null) + error(); +// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno); + + /* Allocate a workspace if we haven't already done so. */ + dtbl.pub = htbl; /* fill in back link */ + + /* Figure C.1: make table of Huffman code length for each symbol */ + + p = 0; + for (l = 1; l <= 16; l++) { + i = htbl.bits[l] & 0xFF; + if (i < 0 || p + i > 256) /* protect against table overrun */ + error(); +// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + while (i-- != 0) + huffsize[p++] = cast(byte) l; + } + huffsize[p] = 0; + numsymbols = p; + + /* Figure C.2: generate the codes themselves */ + /* We also validate that the counts represent a legal Huffman code tree. */ + + code = 0; + si = huffsize[0]; + p = 0; + while ((huffsize[p]) != 0) { + while (( huffsize[p]) == si) { + huffcode[p++] = code; + code++; + } + /* code is now 1 more than the last code used for codelength si; but + * it must still fit in si bits, since no code is allowed to be all ones. + */ + if (( code) >= (( 1) << si)) + error(); +// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + code <<= 1; + si++; + } + + /* Figure F.15: generate decoding tables for bit-sequential decoding */ + + p = 0; + for (l = 1; l <= 16; l++) { + if ((htbl.bits[l] & 0xFF) != 0) { + /* valoffset[l] = huffval[] index of 1st symbol of code length l, + * minus the minimum code of length l + */ + dtbl.valoffset[l] = p - huffcode[p]; + p += (htbl.bits[l] & 0xFF); + dtbl.maxcode[l] = huffcode[p-1]; /* maximum code of length l */ + } else { + dtbl.maxcode[l] = -1; /* -1 if no codes of this length */ + } + } + dtbl.maxcode[17] = 0xFFFFF; /* ensures jpeg_huff_decode terminates */ + + /* Compute lookahead tables to speed up decoding. + * First we set all the table entries to 0, indicating "too long"; + * then we iterate through the Huffman codes that are short enough and + * fill in all the entries that correspond to bit sequences starting + * with that code. + */ + + for (int j = 0; j < dtbl.look_nbits.length; j++) { + dtbl.look_nbits[j] = 0; + } + + p = 0; + for (l = 1; l <= HUFF_LOOKAHEAD; l++) { + for (i = 1; i <= (htbl.bits[l] & 0xFF); i++, p++) { + /* l = current code's length, p = its index in huffcode[] & huffval[]. */ + /* Generate left-justified code followed by all possible bit sequences */ + lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l); + for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) { + dtbl.look_nbits[lookbits] = l; + dtbl.look_sym[lookbits] = htbl.huffval[p]; + lookbits++; + } + } + } + + /* Validate symbols as being reasonable. + * For AC tables, we make no check, but accept all byte values 0..255. + * For DC tables, we require the symbols to be in range 0..15. + * (Tighter bounds could be applied depending on the data depth and mode, + * but this is sufficient to ensure safe decoding.) + */ + if (isDC) { + for (i = 0; i < numsymbols; i++) { + int sym = htbl.huffval[i] & 0xFF; + if (sym < 0 || sym > 15) + error(); +// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE); + } + } } static void start_input_pass (jpeg_decompress_struct cinfo) { - per_scan_setup(cinfo); - latch_quant_tables(cinfo); - cinfo.entropy.start_pass(cinfo); - cinfo.coef.start_input_pass (cinfo); - cinfo.inputctl.consume_input = COEF_CONSUME_INPUT; + per_scan_setup(cinfo); + latch_quant_tables(cinfo); + cinfo.entropy.start_pass(cinfo); + cinfo.coef.start_input_pass (cinfo); + cinfo.inputctl.consume_input = COEF_CONSUME_INPUT; } static void finish_input_pass (jpeg_decompress_struct cinfo) { - cinfo.inputctl.consume_input = INPUT_CONSUME_INPUT; + cinfo.inputctl.consume_input = INPUT_CONSUME_INPUT; } static int consume_markers (jpeg_decompress_struct cinfo) { - jpeg_input_controller inputctl = cinfo.inputctl; - int val; - - if (inputctl.eoi_reached) /* After hitting EOI, read no further */ - return JPEG_REACHED_EOI; - - val = read_markers (cinfo); - - switch (val) { - case JPEG_REACHED_SOS: /* Found SOS */ - if (inputctl.inheaders) { /* 1st SOS */ - initial_setup(cinfo); - inputctl.inheaders = false; - /* Note: start_input_pass must be called by jdmaster.c - * before any more input can be consumed. jdapimin.c is - * responsible for enforcing this sequencing. - */ - } else { /* 2nd or later SOS marker */ - if (! inputctl.has_multiple_scans) - error(); -// ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */ - start_input_pass(cinfo); - } - break; - case JPEG_REACHED_EOI: /* Found EOI */ - inputctl.eoi_reached = true; - if (inputctl.inheaders) { /* Tables-only datastream, apparently */ - if (cinfo.marker.saw_SOF) - error(); -// ERREXIT(cinfo, JERR_SOF_NO_SOS); - } else { - /* Prevent infinite loop in coef ctlr's decompress_data routine - * if user set output_scan_number larger than number of scans. - */ - if (cinfo.output_scan_number > cinfo.input_scan_number) - cinfo.output_scan_number = cinfo.input_scan_number; - } - break; - case JPEG_SUSPENDED: - break; + jpeg_input_controller inputctl = cinfo.inputctl; + int val; + + if (inputctl.eoi_reached) /* After hitting EOI, read no further */ + return JPEG_REACHED_EOI; + + val = read_markers (cinfo); + + switch (val) { + case JPEG_REACHED_SOS: /* Found SOS */ + if (inputctl.inheaders) { /* 1st SOS */ + initial_setup(cinfo); + inputctl.inheaders = false; + /* Note: start_input_pass must be called by jdmaster.c + * before any more input can be consumed. jdapimin.c is + * responsible for enforcing this sequencing. + */ + } else { /* 2nd or later SOS marker */ + if (! inputctl.has_multiple_scans) + error(); +// ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */ + start_input_pass(cinfo); + } + break; + case JPEG_REACHED_EOI: /* Found EOI */ + inputctl.eoi_reached = true; + if (inputctl.inheaders) { /* Tables-only datastream, apparently */ + if (cinfo.marker.saw_SOF) + error(); +// ERREXIT(cinfo, JERR_SOF_NO_SOS); + } else { + /* Prevent infinite loop in coef ctlr's decompress_data routine + * if user set output_scan_number larger than number of scans. + */ + if (cinfo.output_scan_number > cinfo.input_scan_number) + cinfo.output_scan_number = cinfo.input_scan_number; + } + break; + case JPEG_SUSPENDED: + break; default: } - return val; + return val; } static void default_decompress_parms (jpeg_decompress_struct cinfo) { - /* Guess the input colorspace, and set output colorspace accordingly. */ - /* (Wish JPEG committee had provided a real way to specify this...) */ - /* Note application may override our guesses. */ - switch (cinfo.num_components) { - case 1: - cinfo.jpeg_color_space = JCS_GRAYSCALE; - cinfo.out_color_space = JCS_GRAYSCALE; - break; - - case 3: - if (cinfo.saw_JFIF_marker) { - cinfo.jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */ - } else if (cinfo.saw_Adobe_marker) { - switch (cinfo.Adobe_transform) { - case 0: - cinfo.jpeg_color_space = JCS_RGB; - break; - case 1: - cinfo.jpeg_color_space = JCS_YCbCr; - break; - default: -// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform); - cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ - break; - } - } else { - /* Saw no special markers, try to guess from the component IDs */ - int cid0 = cinfo.comp_info[0].component_id; - int cid1 = cinfo.comp_info[1].component_id; - int cid2 = cinfo.comp_info[2].component_id; - - if (cid0 == 1 && cid1 == 2 && cid2 == 3) - cinfo.jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */ - else if (cid0 == 82 && cid1 == 71 && cid2 == 66) - cinfo.jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ - else { -// TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2); - cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ - } - } - /* Always guess RGB is proper output colorspace. */ - cinfo.out_color_space = JCS_RGB; - break; - - case 4: - if (cinfo.saw_Adobe_marker) { - switch (cinfo.Adobe_transform) { - case 0: - cinfo.jpeg_color_space = JCS_CMYK; - break; - case 2: - cinfo.jpeg_color_space = JCS_YCCK; - break; - default: -// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform); - cinfo.jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ - break; - } - } else { - /* No special markers, assume straight CMYK. */ - cinfo.jpeg_color_space = JCS_CMYK; - } - cinfo.out_color_space = JCS_CMYK; - break; - - default: - cinfo.jpeg_color_space = JCS_UNKNOWN; - cinfo.out_color_space = JCS_UNKNOWN; - break; - } - - /* Set defaults for other decompression parameters. */ - cinfo.scale_num = 1; /* 1:1 scaling */ - cinfo.scale_denom = 1; - cinfo.output_gamma = 1.0; - cinfo.buffered_image = false; - cinfo.raw_data_out = false; - cinfo.dct_method = JDCT_DEFAULT; - cinfo.do_fancy_upsampling = true; - cinfo.do_block_smoothing = true; - cinfo.quantize_colors = false; - /* We set these in case application only sets quantize_colors. */ - cinfo.dither_mode = JDITHER_FS; - cinfo.two_pass_quantize = true; - cinfo.desired_number_of_colors = 256; - cinfo.colormap = null; - /* Initialize for no mode change in buffered-image mode. */ - cinfo.enable_1pass_quant = false; - cinfo.enable_external_quant = false; - cinfo.enable_2pass_quant = false; + /* Guess the input colorspace, and set output colorspace accordingly. */ + /* (Wish JPEG committee had provided a real way to specify this...) */ + /* Note application may override our guesses. */ + switch (cinfo.num_components) { + case 1: + cinfo.jpeg_color_space = JCS_GRAYSCALE; + cinfo.out_color_space = JCS_GRAYSCALE; + break; + + case 3: + if (cinfo.saw_JFIF_marker) { + cinfo.jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */ + } else if (cinfo.saw_Adobe_marker) { + switch (cinfo.Adobe_transform) { + case 0: + cinfo.jpeg_color_space = JCS_RGB; + break; + case 1: + cinfo.jpeg_color_space = JCS_YCbCr; + break; + default: +// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform); + cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ + break; + } + } else { + /* Saw no special markers, try to guess from the component IDs */ + int cid0 = cinfo.comp_info[0].component_id; + int cid1 = cinfo.comp_info[1].component_id; + int cid2 = cinfo.comp_info[2].component_id; + + if (cid0 == 1 && cid1 == 2 && cid2 == 3) + cinfo.jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */ + else if (cid0 == 82 && cid1 == 71 && cid2 == 66) + cinfo.jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ + else { +// TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2); + cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ + } + } + /* Always guess RGB is proper output colorspace. */ + cinfo.out_color_space = JCS_RGB; + break; + + case 4: + if (cinfo.saw_Adobe_marker) { + switch (cinfo.Adobe_transform) { + case 0: + cinfo.jpeg_color_space = JCS_CMYK; + break; + case 2: + cinfo.jpeg_color_space = JCS_YCCK; + break; + default: +// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform); + cinfo.jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ + break; + } + } else { + /* No special markers, assume straight CMYK. */ + cinfo.jpeg_color_space = JCS_CMYK; + } + cinfo.out_color_space = JCS_CMYK; + break; + + default: + cinfo.jpeg_color_space = JCS_UNKNOWN; + cinfo.out_color_space = JCS_UNKNOWN; + break; + } + + /* Set defaults for other decompression parameters. */ + cinfo.scale_num = 1; /* 1:1 scaling */ + cinfo.scale_denom = 1; + cinfo.output_gamma = 1.0; + cinfo.buffered_image = false; + cinfo.raw_data_out = false; + cinfo.dct_method = JDCT_DEFAULT; + cinfo.do_fancy_upsampling = true; + cinfo.do_block_smoothing = true; + cinfo.quantize_colors = false; + /* We set these in case application only sets quantize_colors. */ + cinfo.dither_mode = JDITHER_FS; + cinfo.two_pass_quantize = true; + cinfo.desired_number_of_colors = 256; + cinfo.colormap = null; + /* Initialize for no mode change in buffered-image mode. */ + cinfo.enable_1pass_quant = false; + cinfo.enable_external_quant = false; + cinfo.enable_2pass_quant = false; } static void init_source(jpeg_decompress_struct cinfo) { - cinfo.buffer = new byte[INPUT_BUFFER_SIZE]; - cinfo.bytes_in_buffer = 0; - cinfo.bytes_offset = 0; - cinfo.start_of_file = true; + cinfo.buffer = new byte[INPUT_BUFFER_SIZE]; + cinfo.bytes_in_buffer = 0; + cinfo.bytes_offset = 0; + cinfo.start_of_file = true; } static int jpeg_consume_input (jpeg_decompress_struct cinfo) { - int retcode = JPEG_SUSPENDED; - - /* NB: every possible DSTATE value should be listed in this switch */ - switch (cinfo.global_state) { - case DSTATE_START: - /* Start-of-datastream actions: reset appropriate modules */ - reset_input_controller(cinfo); - /* Initialize application's data source module */ - init_source (cinfo); - cinfo.global_state = DSTATE_INHEADER; - /*FALLTHROUGH*/ - case DSTATE_INHEADER: - retcode = consume_input(cinfo); - if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */ - /* Set up default parameters based on header data */ - default_decompress_parms(cinfo); - /* Set global state: ready for start_decompress */ - cinfo.global_state = DSTATE_READY; - } - break; - case DSTATE_READY: - /* Can't advance past first SOS until start_decompress is called */ - retcode = JPEG_REACHED_SOS; - break; - case DSTATE_PRELOAD: - case DSTATE_PRESCAN: - case DSTATE_SCANNING: - case DSTATE_RAW_OK: - case DSTATE_BUFIMAGE: - case DSTATE_BUFPOST: - case DSTATE_STOPPING: - retcode = consume_input (cinfo); - break; - default: - error(); -// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); - } - return retcode; + int retcode = JPEG_SUSPENDED; + + /* NB: every possible DSTATE value should be listed in this switch */ + switch (cinfo.global_state) { + case DSTATE_START: + /* Start-of-datastream actions: reset appropriate modules */ + reset_input_controller(cinfo); + /* Initialize application's data source module */ + init_source (cinfo); + cinfo.global_state = DSTATE_INHEADER; + /*FALLTHROUGH*/ + case DSTATE_INHEADER: + retcode = consume_input(cinfo); + if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */ + /* Set up default parameters based on header data */ + default_decompress_parms(cinfo); + /* Set global state: ready for start_decompress */ + cinfo.global_state = DSTATE_READY; + } + break; + case DSTATE_READY: + /* Can't advance past first SOS until start_decompress is called */ + retcode = JPEG_REACHED_SOS; + break; + case DSTATE_PRELOAD: + case DSTATE_PRESCAN: + case DSTATE_SCANNING: + case DSTATE_RAW_OK: + case DSTATE_BUFIMAGE: + case DSTATE_BUFPOST: + case DSTATE_STOPPING: + retcode = consume_input (cinfo); + break; + default: + error(); +// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state); + } + return retcode; } static void jpeg_abort (jpeg_decompress_struct cinfo) { -// int pool; +// int pool; // -// /* Releasing pools in reverse order might help avoid fragmentation -// * with some (brain-damaged) malloc libraries. -// */ -// for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) { -// (*cinfo.mem.free_pool) (cinfo, pool); -// } - - /* Reset overall state for possible reuse of object */ - if (cinfo.is_decompressor) { - cinfo.global_state = DSTATE_START; - /* Try to keep application from accessing now-deleted marker list. - * A bit kludgy to do it here, but this is the most central place. - */ -// ((j_decompress_ptr) cinfo).marker_list = null; - } else { - cinfo.global_state = CSTATE_START; - } +// /* Releasing pools in reverse order might help avoid fragmentation +// * with some (brain-damaged) malloc libraries. +// */ +// for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) { +// (*cinfo.mem.free_pool) (cinfo, pool); +// } + + /* Reset overall state for possible reuse of object */ + if (cinfo.is_decompressor) { + cinfo.global_state = DSTATE_START; + /* Try to keep application from accessing now-deleted marker list. + * A bit kludgy to do it here, but this is the most central place. + */ +// ((j_decompress_ptr) cinfo).marker_list = null; + } else { + cinfo.global_state = CSTATE_START; + } } static bool isFileFormat(LEDataInputStream stream) { - try { - byte[] buffer = new byte[2]; - stream.read(buffer); - stream.unread(buffer); - return (buffer[0] & 0xFF) == 0xFF && (buffer[1] & 0xFF) == M_SOI; - } catch (TracedException e) { - return false; - } + try { + byte[] buffer = new byte[2]; + stream.read(buffer); + stream.unread(buffer); + return (buffer[0] & 0xFF) == 0xFF && (buffer[1] & 0xFF) == M_SOI; + } catch (TracedException e) { + return false; + } } static ImageData[] loadFromByteStream(InputStream inputStream, ImageLoader loader) { - jpeg_decompress_struct cinfo = new jpeg_decompress_struct(); - cinfo.inputStream = inputStream; - jpeg_create_decompress(cinfo); - jpeg_read_header(cinfo, true); - cinfo.buffered_image = cinfo.progressive_mode && loader.hasListeners(); - jpeg_start_decompress(cinfo); - PaletteData palette = null; - switch (cinfo.out_color_space) { - case JCS_RGB: - palette = new PaletteData(0xFF, 0xFF00, 0xFF0000); - break; - case JCS_GRAYSCALE: - RGB[] colors = new RGB[256]; - for (int i = 0; i < colors.length; i++) { - colors[i] = new RGB(i, i, i); - } - palette = new PaletteData(colors); - break; - default: - error(); - } - int scanlinePad = 4; - int row_stride = (((cinfo.output_width * cinfo.out_color_components * 8 + 7) / 8) + (scanlinePad - 1)) / scanlinePad * scanlinePad; - byte[][] buffer = new byte[][]( 1, row_stride ); - byte[] data = new byte[row_stride * cinfo.output_height]; - ImageData imageData = ImageData.internal_new( - cinfo.output_width, cinfo.output_height, palette.isDirect ? 24 : 8, palette, scanlinePad, data, - 0, null, null, -1, -1, SWT.IMAGE_JPEG, 0, 0, 0, 0); - if (cinfo.buffered_image) { - bool done; - do { - int incrementCount = cinfo.input_scan_number - 1; - jpeg_start_output(cinfo, cinfo.input_scan_number); - while (cinfo.output_scanline < cinfo.output_height) { - int offset = row_stride * cinfo.output_scanline; - jpeg_read_scanlines(cinfo, buffer, 1); + jpeg_decompress_struct cinfo = new jpeg_decompress_struct(); + cinfo.inputStream = inputStream; + jpeg_create_decompress(cinfo); + jpeg_read_header(cinfo, true); + cinfo.buffered_image = cinfo.progressive_mode && loader.hasListeners(); + jpeg_start_decompress(cinfo); + PaletteData palette = null; + switch (cinfo.out_color_space) { + case JCS_RGB: + palette = new PaletteData(0xFF, 0xFF00, 0xFF0000); + break; + case JCS_GRAYSCALE: + RGB[] colors = new RGB[256]; + for (int i = 0; i < colors.length; i++) { + colors[i] = new RGB(i, i, i); + } + palette = new PaletteData(colors); + break; + default: + error(); + } + int scanlinePad = 4; + int row_stride = (((cinfo.output_width * cinfo.out_color_components * 8 + 7) / 8) + (scanlinePad - 1)) / scanlinePad * scanlinePad; + byte[][] buffer = new byte[][]( 1, row_stride ); + byte[] data = new byte[row_stride * cinfo.output_height]; + ImageData imageData = ImageData.internal_new( + cinfo.output_width, cinfo.output_height, palette.isDirect ? 24 : 8, palette, scanlinePad, data, + 0, null, null, -1, -1, SWT.IMAGE_JPEG, 0, 0, 0, 0); + if (cinfo.buffered_image) { + bool done; + do { + int incrementCount = cinfo.input_scan_number - 1; + jpeg_start_output(cinfo, cinfo.input_scan_number); + while (cinfo.output_scanline < cinfo.output_height) { + int offset = row_stride * cinfo.output_scanline; + jpeg_read_scanlines(cinfo, buffer, 1); System.arraycopy(buffer[0], 0, data, offset, row_stride); - } - jpeg_finish_output(cinfo); - loader.notifyListeners(new ImageLoaderEvent(loader, cast(ImageData)imageData.clone(), incrementCount, done = jpeg_input_complete(cinfo))); - } while (!done); - } else { - while (cinfo.output_scanline < cinfo.output_height) { - int offset = row_stride * cinfo.output_scanline; - jpeg_read_scanlines(cinfo, buffer, 1); + } + jpeg_finish_output(cinfo); + loader.notifyListeners(new ImageLoaderEvent(loader, cast(ImageData)imageData.clone(), incrementCount, done = jpeg_input_complete(cinfo))); + } while (!done); + } else { + while (cinfo.output_scanline < cinfo.output_height) { + int offset = row_stride * cinfo.output_scanline; + jpeg_read_scanlines(cinfo, buffer, 1); System.arraycopy(buffer[0], 0, data, offset, row_stride); - } - } - jpeg_finish_decompress(cinfo); - jpeg_destroy_decompress(cinfo); - return [imageData]; + } + } + jpeg_finish_decompress(cinfo); + jpeg_destroy_decompress(cinfo); + return [imageData]; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGEndOfImage.d --- a/dwt/internal/image/JPEGEndOfImage.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGEndOfImage.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,19 +16,19 @@ final class JPEGEndOfImage : JPEGFixedSizeSegment { - public this() { - super(); - } + public this() { + super(); + } - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public int signature() { - return JPEGFileFormat.EOI; - } + public int signature() { + return JPEGFileFormat.EOI; + } - public int fixedSize() { - return 2; - } + public int fixedSize() { + return 2; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGFileFormat.d --- a/dwt/internal/image/JPEGFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This source file is made available under the terms contained in the README file * accompanying this program. The README file should be located in the about_files directory of the @@ -30,125 +30,125 @@ import tango.core.Exception; final class JPEGFileFormat : FileFormat { - int restartInterval; - JPEGFrameHeader frameHeader; - int imageWidth, imageHeight; - int interleavedMcuCols, interleavedMcuRows; - int maxV, maxH; - bool progressive; - int samplePrecision; - int nComponents; - int[][] frameComponents; - int[] componentIds; - byte[][] imageComponents; - int[] dataUnit; - int[][][] dataUnits; - int[] precedingDCs; - JPEGScanHeader scanHeader; - byte[] dataBuffer; - int currentBitCount; - int bufferCurrentPosition; - int restartsToGo; - int nextRestartNumber; - JPEGHuffmanTable[] acHuffmanTables; - JPEGHuffmanTable[] dcHuffmanTables; - int[][] quantizationTables; - int currentByte; - int encoderQFactor = 75; - int eobrun = 0; - /* JPEGConstants */ - public static const int DCTSIZE = 8; - public static const int DCTSIZESQR = 64; - /* JPEGFixedPointConstants */ - public static const int FIX_0_899976223 = 7373; - public static const int FIX_1_961570560 = 16069; - public static const int FIX_2_053119869 = 16819; - public static const int FIX_0_298631336 = 2446; - public static const int FIX_1_847759065 = 15137; - public static const int FIX_1_175875602 = 9633; - public static const int FIX_3_072711026 = 25172; - public static const int FIX_0_765366865 = 6270; - public static const int FIX_2_562915447 = 20995; - public static const int FIX_0_541196100 = 4433; - public static const int FIX_0_390180644 = 3196; - public static const int FIX_1_501321110 = 12299; - /* JPEGMarkerCodes */ - public static const int APP0 = 0xFFE0; - public static const int APP15 = 0xFFEF; - public static const int COM = 0xFFFE; - public static const int DAC = 0xFFCC; - public static const int DHP = 0xFFDE; - public static const int DHT = 0xFFC4; - public static const int DNL = 0xFFDC; - public static const int DRI = 0xFFDD; - public static const int DQT = 0xFFDB; - public static const int EOI = 0xFFD9; - public static const int EXP = 0xFFDF; - public static const int JPG = 0xFFC8; - public static const int JPG0 = 0xFFF0; - public static const int JPG13 = 0xFFFD; - public static const int RST0 = 0xFFD0; - public static const int RST1 = 0xFFD1; - public static const int RST2 = 0xFFD2; - public static const int RST3 = 0xFFD3; - public static const int RST4 = 0xFFD4; - public static const int RST5 = 0xFFD5; - public static const int RST6 = 0xFFD6; - public static const int RST7 = 0xFFD7; - public static const int SOF0 = 0xFFC0; - public static const int SOF1 = 0xFFC1; - public static const int SOF2 = 0xFFC2; - public static const int SOF3 = 0xFFC3; - public static const int SOF5 = 0xFFC5; - public static const int SOF6 = 0xFFC6; - public static const int SOF7 = 0xFFC7; - public static const int SOF9 = 0xFFC9; - public static const int SOF10 = 0xFFCA; - public static const int SOF11 = 0xFFCB; - public static const int SOF13 = 0xFFCD; - public static const int SOF14 = 0xFFCE; - public static const int SOF15 = 0xFFCF; - public static const int SOI = 0xFFD8; - public static const int SOS = 0xFFDA; - public static const int TEM = 0xFF01; - /* JPEGFrameComponentParameterConstants */ - public static const int TQI = 0; - public static const int HI = 1; - public static const int VI = 2; - public static const int CW = 3; - public static const int CH = 4; - /* JPEGScanComponentParameterConstants */ - public static const int DC = 0; - public static const int AC = 1; - /* JFIF Component Constants */ - public static const int ID_Y = 1 - 1; - public static const int ID_CB = 2 - 1; - public static const int ID_CR = 3 - 1; - public static /*const*/ RGB[] RGB16; - public static const int[] ExtendTest = [ - 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, - 4096, 8192, 16384, 32768, 65536, 131072, 262144 - ]; - public static const int[] ExtendOffset = [ - 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, - -4095, -8191, -16383, -32767, -65535, -131071, -262143 - ]; - public static const int[] ZigZag8x8 = [ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63 - ]; + int restartInterval; + JPEGFrameHeader frameHeader; + int imageWidth, imageHeight; + int interleavedMcuCols, interleavedMcuRows; + int maxV, maxH; + bool progressive; + int samplePrecision; + int nComponents; + int[][] frameComponents; + int[] componentIds; + byte[][] imageComponents; + int[] dataUnit; + int[][][] dataUnits; + int[] precedingDCs; + JPEGScanHeader scanHeader; + byte[] dataBuffer; + int currentBitCount; + int bufferCurrentPosition; + int restartsToGo; + int nextRestartNumber; + JPEGHuffmanTable[] acHuffmanTables; + JPEGHuffmanTable[] dcHuffmanTables; + int[][] quantizationTables; + int currentByte; + int encoderQFactor = 75; + int eobrun = 0; + /* JPEGConstants */ + public static const int DCTSIZE = 8; + public static const int DCTSIZESQR = 64; + /* JPEGFixedPointConstants */ + public static const int FIX_0_899976223 = 7373; + public static const int FIX_1_961570560 = 16069; + public static const int FIX_2_053119869 = 16819; + public static const int FIX_0_298631336 = 2446; + public static const int FIX_1_847759065 = 15137; + public static const int FIX_1_175875602 = 9633; + public static const int FIX_3_072711026 = 25172; + public static const int FIX_0_765366865 = 6270; + public static const int FIX_2_562915447 = 20995; + public static const int FIX_0_541196100 = 4433; + public static const int FIX_0_390180644 = 3196; + public static const int FIX_1_501321110 = 12299; + /* JPEGMarkerCodes */ + public static const int APP0 = 0xFFE0; + public static const int APP15 = 0xFFEF; + public static const int COM = 0xFFFE; + public static const int DAC = 0xFFCC; + public static const int DHP = 0xFFDE; + public static const int DHT = 0xFFC4; + public static const int DNL = 0xFFDC; + public static const int DRI = 0xFFDD; + public static const int DQT = 0xFFDB; + public static const int EOI = 0xFFD9; + public static const int EXP = 0xFFDF; + public static const int JPG = 0xFFC8; + public static const int JPG0 = 0xFFF0; + public static const int JPG13 = 0xFFFD; + public static const int RST0 = 0xFFD0; + public static const int RST1 = 0xFFD1; + public static const int RST2 = 0xFFD2; + public static const int RST3 = 0xFFD3; + public static const int RST4 = 0xFFD4; + public static const int RST5 = 0xFFD5; + public static const int RST6 = 0xFFD6; + public static const int RST7 = 0xFFD7; + public static const int SOF0 = 0xFFC0; + public static const int SOF1 = 0xFFC1; + public static const int SOF2 = 0xFFC2; + public static const int SOF3 = 0xFFC3; + public static const int SOF5 = 0xFFC5; + public static const int SOF6 = 0xFFC6; + public static const int SOF7 = 0xFFC7; + public static const int SOF9 = 0xFFC9; + public static const int SOF10 = 0xFFCA; + public static const int SOF11 = 0xFFCB; + public static const int SOF13 = 0xFFCD; + public static const int SOF14 = 0xFFCE; + public static const int SOF15 = 0xFFCF; + public static const int SOI = 0xFFD8; + public static const int SOS = 0xFFDA; + public static const int TEM = 0xFF01; + /* JPEGFrameComponentParameterConstants */ + public static const int TQI = 0; + public static const int HI = 1; + public static const int VI = 2; + public static const int CW = 3; + public static const int CH = 4; + /* JPEGScanComponentParameterConstants */ + public static const int DC = 0; + public static const int AC = 1; + /* JFIF Component Constants */ + public static const int ID_Y = 1 - 1; + public static const int ID_CB = 2 - 1; + public static const int ID_CR = 3 - 1; + public static /*const*/ RGB[] RGB16; + public static const int[] ExtendTest = [ + 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, + 4096, 8192, 16384, 32768, 65536, 131072, 262144 + ]; + public static const int[] ExtendOffset = [ + 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, + -4095, -8191, -16383, -32767, -65535, -131071, -262143 + ]; + public static const int[] ZigZag8x8 = [ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63 + ]; - public static int[] CrRTable, CbBTable, CrGTable, CbGTable; - public static int[] RYTable, GYTable, BYTable, - RCbTable, GCbTable, BCbTable, RCrTable, GCrTable, BCrTable, NBitsTable; + public static int[] CrRTable, CbBTable, CrGTable, CbGTable; + public static int[] RYTable, GYTable, BYTable, + RCbTable, GCbTable, BCbTable, RCrTable, GCrTable, BCrTable, NBitsTable; public static void static_this() { - initialize(); + initialize(); RGB16 = [ new RGB(0,0,0), new RGB(0x80,0,0), @@ -167,1727 +167,1727 @@ new RGB(0,0xFF,0xFF), new RGB(0xFF,0xFF,0xFF) ]; - } + } void compress(ImageData image, byte[] dataYComp, byte[] dataCbComp, byte[] dataCrComp) { - int srcWidth = image.width; - int srcHeight = image.height; - int vhFactor = maxV * maxH; - int[] frameComponent; - imageComponents = new byte[][](nComponents); - for (int i = 0; i < nComponents; i++) { - frameComponent = frameComponents[componentIds[i]]; - imageComponents[i] = new byte[frameComponent[CW] * frameComponent[CH]]; - } - frameComponent = frameComponents[componentIds[ID_Y]]; - for (int yPos = 0; yPos < srcHeight; yPos++) { - int srcOfs = yPos * srcWidth; - int dstOfs = yPos * frameComponent[CW]; + int srcWidth = image.width; + int srcHeight = image.height; + int vhFactor = maxV * maxH; + int[] frameComponent; + imageComponents = new byte[][](nComponents); + for (int i = 0; i < nComponents; i++) { + frameComponent = frameComponents[componentIds[i]]; + imageComponents[i] = new byte[frameComponent[CW] * frameComponent[CH]]; + } + frameComponent = frameComponents[componentIds[ID_Y]]; + for (int yPos = 0; yPos < srcHeight; yPos++) { + int srcOfs = yPos * srcWidth; + int dstOfs = yPos * frameComponent[CW]; System.arraycopy(dataYComp, srcOfs, imageComponents[ID_Y], dstOfs, srcWidth); - } - frameComponent = frameComponents[componentIds[ID_CB]]; - for (int yPos = 0; yPos < srcHeight / maxV; yPos++) { - int destRowIndex = yPos * frameComponent[CW]; - for (int xPos = 0; xPos < srcWidth / maxH; xPos++) { - int sum = 0; - for (int iv = 0; iv < maxV; iv++) { - int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH); - for (int ih = 0; ih < maxH; ih++) { - sum += dataCbComp[srcIndex + ih] & 0xFF; - } - } - imageComponents[ID_CB][destRowIndex + xPos] = cast(byte)(sum / vhFactor); - } - } - frameComponent = frameComponents[componentIds[ID_CR]]; - for (int yPos = 0; yPos < srcHeight / maxV; yPos++) { - int destRowIndex = yPos * frameComponent[CW]; - for (int xPos = 0; xPos < srcWidth / maxH; xPos++) { - int sum = 0; - for (int iv = 0; iv < maxV; iv++) { - int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH); - for (int ih = 0; ih < maxH; ih++) { - sum += dataCrComp[srcIndex + ih] & 0xFF; - } - } - imageComponents[ID_CR][destRowIndex + xPos] = cast(byte)(sum / vhFactor); - } - } - for (int iComp = 0; iComp < nComponents; iComp++) { - byte[] imageComponent = imageComponents[iComp]; - frameComponent = frameComponents[componentIds[iComp]]; - int hFactor = frameComponent[HI]; - int vFactor = frameComponent[VI]; - int componentWidth = frameComponent[CW]; - int componentHeight = frameComponent[CH]; - int compressedWidth = srcWidth / (maxH / hFactor); - int compressedHeight = srcHeight / (maxV / vFactor); - if (compressedWidth < componentWidth) { - int delta = componentWidth - compressedWidth; - for (int yPos = 0; yPos < compressedHeight; yPos++) { - int dstOfs = ((yPos + 1) * componentWidth - delta); - int dataValue = imageComponent[dstOfs - 1] & 0xFF; - for (int i = 0; i < delta; i++) { - imageComponent[dstOfs + i] = cast(byte)dataValue; - } - } - } - if (compressedHeight < componentHeight) { - int srcOfs = (compressedHeight - 1) * componentWidth; - for (int yPos = compressedHeight; yPos <= componentHeight; yPos++) { - int dstOfs = (yPos - 1) * componentWidth; + } + frameComponent = frameComponents[componentIds[ID_CB]]; + for (int yPos = 0; yPos < srcHeight / maxV; yPos++) { + int destRowIndex = yPos * frameComponent[CW]; + for (int xPos = 0; xPos < srcWidth / maxH; xPos++) { + int sum = 0; + for (int iv = 0; iv < maxV; iv++) { + int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH); + for (int ih = 0; ih < maxH; ih++) { + sum += dataCbComp[srcIndex + ih] & 0xFF; + } + } + imageComponents[ID_CB][destRowIndex + xPos] = cast(byte)(sum / vhFactor); + } + } + frameComponent = frameComponents[componentIds[ID_CR]]; + for (int yPos = 0; yPos < srcHeight / maxV; yPos++) { + int destRowIndex = yPos * frameComponent[CW]; + for (int xPos = 0; xPos < srcWidth / maxH; xPos++) { + int sum = 0; + for (int iv = 0; iv < maxV; iv++) { + int srcIndex = (yPos * maxV + iv) * srcWidth + (xPos * maxH); + for (int ih = 0; ih < maxH; ih++) { + sum += dataCrComp[srcIndex + ih] & 0xFF; + } + } + imageComponents[ID_CR][destRowIndex + xPos] = cast(byte)(sum / vhFactor); + } + } + for (int iComp = 0; iComp < nComponents; iComp++) { + byte[] imageComponent = imageComponents[iComp]; + frameComponent = frameComponents[componentIds[iComp]]; + int hFactor = frameComponent[HI]; + int vFactor = frameComponent[VI]; + int componentWidth = frameComponent[CW]; + int componentHeight = frameComponent[CH]; + int compressedWidth = srcWidth / (maxH / hFactor); + int compressedHeight = srcHeight / (maxV / vFactor); + if (compressedWidth < componentWidth) { + int delta = componentWidth - compressedWidth; + for (int yPos = 0; yPos < compressedHeight; yPos++) { + int dstOfs = ((yPos + 1) * componentWidth - delta); + int dataValue = imageComponent[dstOfs - 1] & 0xFF; + for (int i = 0; i < delta; i++) { + imageComponent[dstOfs + i] = cast(byte)dataValue; + } + } + } + if (compressedHeight < componentHeight) { + int srcOfs = (compressedHeight - 1) * componentWidth; + for (int yPos = compressedHeight; yPos <= componentHeight; yPos++) { + int dstOfs = (yPos - 1) * componentWidth; System.arraycopy(imageComponent, srcOfs, imageComponent, dstOfs, componentWidth); - } - } - } + } + } + } } void convert4BitRGBToYCbCr(ImageData image) { - RGB[] rgbs = image.getRGBs(); - int paletteSize = rgbs.length; - byte[] yComp = new byte[paletteSize]; - byte[] cbComp = new byte[paletteSize]; - byte[] crComp = new byte[paletteSize]; - int srcWidth = image.width; - int srcHeight = image.height; - for (int i = 0; i < paletteSize; i++) { - RGB color = rgbs[i]; - int r = color.red; - int g = color.green; - int b = color.blue; - int n = RYTable[r] + GYTable[g] + BYTable[b]; - yComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) yComp[i]--; - n = RCbTable[r] + GCbTable[g] + BCbTable[b]; - cbComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) cbComp[i]--; - n = RCrTable[r] + GCrTable[g] + BCrTable[b]; - crComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) crComp[i]--; - } - int bSize = srcWidth * srcHeight; - byte[] dataYComp = new byte[bSize]; - byte[] dataCbComp = new byte[bSize]; - byte[] dataCrComp = new byte[bSize]; - byte[] origData = image.data; - int bytesPerLine = image.bytesPerLine; - int maxScanlineByte = srcWidth >> 1; - for (int yPos = 0; yPos < srcHeight; yPos++) { - for (int xPos = 0; xPos < maxScanlineByte; xPos++) { - int srcIndex = yPos * bytesPerLine + xPos; - int dstIndex = yPos * srcWidth + (xPos * 2); - int value2 = origData[srcIndex] & 0xFF; - int value1 = value2 >> 4; - value2 &= 0x0F; - dataYComp[dstIndex] = yComp[value1]; - dataCbComp[dstIndex] = cbComp[value1]; - dataCrComp[dstIndex] = crComp[value1]; - dataYComp[dstIndex + 1] = yComp[value2]; - dataCbComp[dstIndex + 1] = cbComp[value2]; - dataCrComp[dstIndex + 1] = crComp[value2]; - } - } - compress(image, dataYComp, dataCbComp, dataCrComp); + RGB[] rgbs = image.getRGBs(); + int paletteSize = rgbs.length; + byte[] yComp = new byte[paletteSize]; + byte[] cbComp = new byte[paletteSize]; + byte[] crComp = new byte[paletteSize]; + int srcWidth = image.width; + int srcHeight = image.height; + for (int i = 0; i < paletteSize; i++) { + RGB color = rgbs[i]; + int r = color.red; + int g = color.green; + int b = color.blue; + int n = RYTable[r] + GYTable[g] + BYTable[b]; + yComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) yComp[i]--; + n = RCbTable[r] + GCbTable[g] + BCbTable[b]; + cbComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) cbComp[i]--; + n = RCrTable[r] + GCrTable[g] + BCrTable[b]; + crComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) crComp[i]--; + } + int bSize = srcWidth * srcHeight; + byte[] dataYComp = new byte[bSize]; + byte[] dataCbComp = new byte[bSize]; + byte[] dataCrComp = new byte[bSize]; + byte[] origData = image.data; + int bytesPerLine = image.bytesPerLine; + int maxScanlineByte = srcWidth >> 1; + for (int yPos = 0; yPos < srcHeight; yPos++) { + for (int xPos = 0; xPos < maxScanlineByte; xPos++) { + int srcIndex = yPos * bytesPerLine + xPos; + int dstIndex = yPos * srcWidth + (xPos * 2); + int value2 = origData[srcIndex] & 0xFF; + int value1 = value2 >> 4; + value2 &= 0x0F; + dataYComp[dstIndex] = yComp[value1]; + dataCbComp[dstIndex] = cbComp[value1]; + dataCrComp[dstIndex] = crComp[value1]; + dataYComp[dstIndex + 1] = yComp[value2]; + dataCbComp[dstIndex + 1] = cbComp[value2]; + dataCrComp[dstIndex + 1] = crComp[value2]; + } + } + compress(image, dataYComp, dataCbComp, dataCrComp); } void convert8BitRGBToYCbCr(ImageData image) { - RGB[] rgbs = image.getRGBs(); - int paletteSize = rgbs.length; - byte[] yComp = new byte[paletteSize]; - byte[] cbComp = new byte[paletteSize]; - byte[] crComp = new byte[paletteSize]; - int srcWidth = image.width; - int srcHeight = image.height; - for (int i = 0; i < paletteSize; i++) { - RGB color = rgbs[i]; - int r = color.red; - int g = color.green; - int b = color.blue; - int n = RYTable[r] + GYTable[g] + BYTable[b]; - yComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) yComp[i]--; - n = RCbTable[r] + GCbTable[g] + BCbTable[b]; - cbComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) cbComp[i]--; - n = RCrTable[r] + GCrTable[g] + BCrTable[b]; - crComp[i] = cast(byte)(n >> 16); - if ((n < 0) && ((n & 0xFFFF) != 0)) crComp[i]--; - } - int dstWidth = image.width; - int dstHeight = srcHeight; - int stride = ((srcWidth + 3) >> 2) << 2; - int bSize = dstWidth * dstHeight; - byte[] dataYComp = new byte[bSize]; - byte[] dataCbComp = new byte[bSize]; - byte[] dataCrComp = new byte[bSize]; - byte[] origData = image.data; - for (int yPos = 0; yPos < srcHeight; yPos++) { - int srcRowIndex = yPos * stride; - int dstRowIndex = yPos * dstWidth; - for (int xPos = 0; xPos < srcWidth; xPos++) { - int value = origData[srcRowIndex + xPos] & 0xFF; - int dstIndex = dstRowIndex + xPos; - dataYComp[dstIndex] = yComp[value]; - dataCbComp[dstIndex] = cbComp[value]; - dataCrComp[dstIndex] = crComp[value]; - } - } - compress(image, dataYComp, dataCbComp, dataCrComp); + RGB[] rgbs = image.getRGBs(); + int paletteSize = rgbs.length; + byte[] yComp = new byte[paletteSize]; + byte[] cbComp = new byte[paletteSize]; + byte[] crComp = new byte[paletteSize]; + int srcWidth = image.width; + int srcHeight = image.height; + for (int i = 0; i < paletteSize; i++) { + RGB color = rgbs[i]; + int r = color.red; + int g = color.green; + int b = color.blue; + int n = RYTable[r] + GYTable[g] + BYTable[b]; + yComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) yComp[i]--; + n = RCbTable[r] + GCbTable[g] + BCbTable[b]; + cbComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) cbComp[i]--; + n = RCrTable[r] + GCrTable[g] + BCrTable[b]; + crComp[i] = cast(byte)(n >> 16); + if ((n < 0) && ((n & 0xFFFF) != 0)) crComp[i]--; + } + int dstWidth = image.width; + int dstHeight = srcHeight; + int stride = ((srcWidth + 3) >> 2) << 2; + int bSize = dstWidth * dstHeight; + byte[] dataYComp = new byte[bSize]; + byte[] dataCbComp = new byte[bSize]; + byte[] dataCrComp = new byte[bSize]; + byte[] origData = image.data; + for (int yPos = 0; yPos < srcHeight; yPos++) { + int srcRowIndex = yPos * stride; + int dstRowIndex = yPos * dstWidth; + for (int xPos = 0; xPos < srcWidth; xPos++) { + int value = origData[srcRowIndex + xPos] & 0xFF; + int dstIndex = dstRowIndex + xPos; + dataYComp[dstIndex] = yComp[value]; + dataCbComp[dstIndex] = cbComp[value]; + dataCrComp[dstIndex] = crComp[value]; + } + } + compress(image, dataYComp, dataCbComp, dataCrComp); } byte[] convertCMYKToRGB() { - /* Unsupported CMYK format. Answer an empty byte array. */ - return new byte[0]; + /* Unsupported CMYK format. Answer an empty byte array. */ + return new byte[0]; } void convertImageToYCbCr(ImageData image) { - switch (image.depth) { - case 4: - convert4BitRGBToYCbCr(image); - return; - case 8: - convert8BitRGBToYCbCr(image); - return; - case 16: - case 24: - case 32: - convertMultiRGBToYCbCr(image); - return; - default: - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - } - return; + switch (image.depth) { + case 4: + convert4BitRGBToYCbCr(image); + return; + case 8: + convert8BitRGBToYCbCr(image); + return; + case 16: + case 24: + case 32: + convertMultiRGBToYCbCr(image); + return; + default: + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + } + return; } void convertMultiRGBToYCbCr(ImageData image) { - int srcWidth = image.width; - int srcHeight = image.height; - int bSize = srcWidth * srcHeight; - byte[] dataYComp = new byte[bSize]; - byte[] dataCbComp = new byte[bSize]; - byte[] dataCrComp = new byte[bSize]; - PaletteData palette = image.palette; - int[] buffer = new int[srcWidth]; - if (palette.isDirect) { - 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 yPos = 0; yPos < srcHeight; yPos++) { - image.getPixels(0, yPos, srcWidth, buffer, 0); - int dstRowIndex = yPos * srcWidth; - for (int xPos = 0; xPos < srcWidth; xPos++) { - int pixel = buffer[xPos]; - int dstDataIndex = dstRowIndex + xPos; - int r = pixel & redMask; - r = (redShift < 0) ? r >>> -redShift : r << redShift; - int g = pixel & greenMask; - g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; - int b = pixel & blueMask; - b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; - dataYComp[dstDataIndex] = cast(byte)((RYTable[r] + GYTable[g] + BYTable[b]) >> 16); - dataCbComp[dstDataIndex] = cast(byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) >> 16); - dataCrComp[dstDataIndex] = cast(byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) >> 16); - } - } - } else { - for (int yPos = 0; yPos < srcHeight; yPos++) { - image.getPixels(0, yPos, srcWidth, buffer, 0); - int dstRowIndex = yPos * srcWidth; - for (int xPos = 0; xPos < srcWidth; xPos++) { - int pixel = buffer[xPos]; - int dstDataIndex = dstRowIndex + xPos; - RGB rgb = palette.getRGB(pixel); - int r = rgb.red; - int g = rgb.green; - int b = rgb.blue; - dataYComp[dstDataIndex] = cast(byte)((RYTable[r] + GYTable[g] + BYTable[b]) >> 16); - dataCbComp[dstDataIndex] = cast(byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) >> 16); - dataCrComp[dstDataIndex] = cast(byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) >> 16); - } - } - } - compress(image, dataYComp, dataCbComp, dataCrComp); + int srcWidth = image.width; + int srcHeight = image.height; + int bSize = srcWidth * srcHeight; + byte[] dataYComp = new byte[bSize]; + byte[] dataCbComp = new byte[bSize]; + byte[] dataCrComp = new byte[bSize]; + PaletteData palette = image.palette; + int[] buffer = new int[srcWidth]; + if (palette.isDirect) { + 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 yPos = 0; yPos < srcHeight; yPos++) { + image.getPixels(0, yPos, srcWidth, buffer, 0); + int dstRowIndex = yPos * srcWidth; + for (int xPos = 0; xPos < srcWidth; xPos++) { + int pixel = buffer[xPos]; + int dstDataIndex = dstRowIndex + xPos; + int r = pixel & redMask; + r = (redShift < 0) ? r >>> -redShift : r << redShift; + int g = pixel & greenMask; + g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; + int b = pixel & blueMask; + b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; + dataYComp[dstDataIndex] = cast(byte)((RYTable[r] + GYTable[g] + BYTable[b]) >> 16); + dataCbComp[dstDataIndex] = cast(byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) >> 16); + dataCrComp[dstDataIndex] = cast(byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) >> 16); + } + } + } else { + for (int yPos = 0; yPos < srcHeight; yPos++) { + image.getPixels(0, yPos, srcWidth, buffer, 0); + int dstRowIndex = yPos * srcWidth; + for (int xPos = 0; xPos < srcWidth; xPos++) { + int pixel = buffer[xPos]; + int dstDataIndex = dstRowIndex + xPos; + RGB rgb = palette.getRGB(pixel); + int r = rgb.red; + int g = rgb.green; + int b = rgb.blue; + dataYComp[dstDataIndex] = cast(byte)((RYTable[r] + GYTable[g] + BYTable[b]) >> 16); + dataCbComp[dstDataIndex] = cast(byte)((RCbTable[r] + GCbTable[g] + BCbTable[b]) >> 16); + dataCrComp[dstDataIndex] = cast(byte)((RCrTable[r] + GCrTable[g] + BCrTable[b]) >> 16); + } + } + } + compress(image, dataYComp, dataCbComp, dataCrComp); } byte[] convertYToRGB() { - int compWidth = frameComponents[componentIds[ID_Y]][CW]; - int bytesPerLine = (((imageWidth * 8 + 7) / 8) + 3) / 4 * 4; - byte[] data = new byte[bytesPerLine * imageHeight]; - byte[] yComp = imageComponents[ID_Y]; - int destIndex = 0; - for (int i = 0; i < imageHeight; i++) { - int srcIndex = i * compWidth; - for (int j = 0; j < bytesPerLine; j++) { - int y = yComp[srcIndex] & 0xFF; - if (y < 0) { - y = 0; - } else { - if (y > 255) y = 255; - } - if (j >= imageWidth) { - y = 0; - } - data[destIndex] = cast(byte)y; - srcIndex++; - destIndex++; - } - } - return data; + int compWidth = frameComponents[componentIds[ID_Y]][CW]; + int bytesPerLine = (((imageWidth * 8 + 7) / 8) + 3) / 4 * 4; + byte[] data = new byte[bytesPerLine * imageHeight]; + byte[] yComp = imageComponents[ID_Y]; + int destIndex = 0; + for (int i = 0; i < imageHeight; i++) { + int srcIndex = i * compWidth; + for (int j = 0; j < bytesPerLine; j++) { + int y = yComp[srcIndex] & 0xFF; + if (y < 0) { + y = 0; + } else { + if (y > 255) y = 255; + } + if (j >= imageWidth) { + y = 0; + } + data[destIndex] = cast(byte)y; + srcIndex++; + destIndex++; + } + } + return data; } byte[] convertYCbCrToRGB() { - /** - * Convert existing image components into an RGB format. - * YCbCr is defined per CCIR 601-1, except that Cb and Cr are - * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. - * The conversion equations to be implemented are therefore - * R = Y + 1.40200 * Cr - * G = Y - 0.34414 * Cb - 0.71414 * Cr - * B = Y + 1.77200 * Cb - * where Cb and Cr represent the incoming values less MAXJSAMPLE/2. - * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) - * - * To avoid floating-point arithmetic, we represent the fractional constants - * as integers scaled up by 2^16 (about 4 digits precision); we have to divide - * the products by 2^16, with appropriate rounding, to get the correct answer. - * Notice that Y, being an integral input, does not contribute any fraction - * so it need not participate in the rounding. - * - * For even more speed, we avoid doing any multiplications in the inner loop - * by precalculating the constants times Cb and Cr for all possible values. - * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); - * for 12-bit samples it is still acceptable. It's not very reasonable for - * 16-bit samples, but if you want lossless storage you shouldn't be changing - * colorspace anyway. - * The Cr=>R and Cb=>B values can be rounded to integers in advance; the - * values for the G calculation are left scaled up, since we must add them - * together before rounding. - */ - int bSize = imageWidth * imageHeight * nComponents; - byte[] rgbData = new byte[bSize]; - int destIndex = 0; - expandImageComponents(); - byte[] yComp = imageComponents[ID_Y]; - byte[] cbComp = imageComponents[ID_CB]; - byte[] crComp = imageComponents[ID_CR]; - int compWidth = frameComponents[componentIds[ID_Y]][CW]; - for (int v = 0; v < imageHeight; v++) { - int srcIndex = v * compWidth; - for (int i = 0; i < imageWidth; i++) { - int y = yComp[srcIndex] & 0xFF; - int cb = cbComp[srcIndex] & 0xFF; - int cr = crComp[srcIndex] & 0xFF; - int r = y + CrRTable[cr]; - int g = y + ((CbGTable[cb] + CrGTable[cr]) >> 16); - int b = y + CbBTable[cb]; - if (r < 0) { - r = 0; - } else { - if (r > 255) r = 255; - } - if (g < 0) { - g = 0; - } else { - if (g > 255) g = 255; - } - if (b < 0) { - b = 0; - } else { - if (b > 255) b = 255; - } - rgbData[destIndex] = cast(byte)b; - rgbData[destIndex + 1] = cast(byte)g; - rgbData[destIndex + 2] = cast(byte)r; - destIndex += 3; - srcIndex++; - } - } - return rgbData; + /** + * Convert existing image components into an RGB format. + * YCbCr is defined per CCIR 601-1, except that Cb and Cr are + * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. + * The conversion equations to be implemented are therefore + * R = Y + 1.40200 * Cr + * G = Y - 0.34414 * Cb - 0.71414 * Cr + * B = Y + 1.77200 * Cb + * where Cb and Cr represent the incoming values less MAXJSAMPLE/2. + * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) + * + * To avoid floating-point arithmetic, we represent the fractional constants + * as integers scaled up by 2^16 (about 4 digits precision); we have to divide + * the products by 2^16, with appropriate rounding, to get the correct answer. + * Notice that Y, being an integral input, does not contribute any fraction + * so it need not participate in the rounding. + * + * For even more speed, we avoid doing any multiplications in the inner loop + * by precalculating the constants times Cb and Cr for all possible values. + * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); + * for 12-bit samples it is still acceptable. It's not very reasonable for + * 16-bit samples, but if you want lossless storage you shouldn't be changing + * colorspace anyway. + * The Cr=>R and Cb=>B values can be rounded to integers in advance; the + * values for the G calculation are left scaled up, since we must add them + * together before rounding. + */ + int bSize = imageWidth * imageHeight * nComponents; + byte[] rgbData = new byte[bSize]; + int destIndex = 0; + expandImageComponents(); + byte[] yComp = imageComponents[ID_Y]; + byte[] cbComp = imageComponents[ID_CB]; + byte[] crComp = imageComponents[ID_CR]; + int compWidth = frameComponents[componentIds[ID_Y]][CW]; + for (int v = 0; v < imageHeight; v++) { + int srcIndex = v * compWidth; + for (int i = 0; i < imageWidth; i++) { + int y = yComp[srcIndex] & 0xFF; + int cb = cbComp[srcIndex] & 0xFF; + int cr = crComp[srcIndex] & 0xFF; + int r = y + CrRTable[cr]; + int g = y + ((CbGTable[cb] + CrGTable[cr]) >> 16); + int b = y + CbBTable[cb]; + if (r < 0) { + r = 0; + } else { + if (r > 255) r = 255; + } + if (g < 0) { + g = 0; + } else { + if (g > 255) g = 255; + } + if (b < 0) { + b = 0; + } else { + if (b > 255) b = 255; + } + rgbData[destIndex] = cast(byte)b; + rgbData[destIndex + 1] = cast(byte)g; + rgbData[destIndex + 2] = cast(byte)r; + destIndex += 3; + srcIndex++; + } + } + return rgbData; } void decodeACCoefficients(int[] dataUnit, int iComp) { - int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; - JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; - int k = 1; - while (k < 64) { - int rs = decodeUsingTable(acTable); - int r = rs >> 4; - int s = rs & 0xF; - if (s == 0) { - if (r == 15) { - k += 16; - } else { - break; - } - } else { - k += r; - int bits = receive(s); - dataUnit[ZigZag8x8[k]] = extendBy(bits, s); - k++; - } - } + int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; + JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; + int k = 1; + while (k < 64) { + int rs = decodeUsingTable(acTable); + int r = rs >> 4; + int s = rs & 0xF; + if (s == 0) { + if (r == 15) { + k += 16; + } else { + break; + } + } else { + k += r; + int bits = receive(s); + dataUnit[ZigZag8x8[k]] = extendBy(bits, s); + k++; + } + } } void decodeACFirstCoefficients(int[] dataUnit, int iComp, int start, int end, int approxBit) { - if (eobrun > 0) { - eobrun--; - return; - } - int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; - JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; - int k = start; - while (k <= end) { - int rs = decodeUsingTable(acTable); - int r = rs >> 4; - int s = rs & 0xF; - if (s == 0) { - if (r == 15) { - k += 16; - } else { - eobrun = (1 << r) + receive(r) - 1; - break; - } - } else { - k += r; - int bits = receive(s); - dataUnit[ZigZag8x8[k]] = extendBy(bits, s) << approxBit; - k++; - } - } + if (eobrun > 0) { + eobrun--; + return; + } + int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; + JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; + int k = start; + while (k <= end) { + int rs = decodeUsingTable(acTable); + int r = rs >> 4; + int s = rs & 0xF; + if (s == 0) { + if (r == 15) { + k += 16; + } else { + eobrun = (1 << r) + receive(r) - 1; + break; + } + } else { + k += r; + int bits = receive(s); + dataUnit[ZigZag8x8[k]] = extendBy(bits, s) << approxBit; + k++; + } + } } void decodeACRefineCoefficients(int[] dataUnit, int iComp, int start, int end, int approxBit) { - int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; - JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; - int k = start; - while (k <= end) { - if (eobrun > 0) { - while (k <= end) { - int zzIndex = ZigZag8x8[k]; - if (dataUnit[zzIndex] != 0) { - dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); - } - k++; - } - eobrun--; - } else { - int rs = decodeUsingTable(acTable); - int r = rs >> 4; - int s = rs & 0xF; - if (s == 0) { - if (r == 15) { - int zeros = 0; - while (zeros < 16 && k <= end) { - int zzIndex = ZigZag8x8[k]; - if (dataUnit[zzIndex] != 0) { - dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); - } else { - zeros++; - } - k++; - } - } else { - eobrun = (1 << r) + receive(r); - } - } else { - int bit = receive(s); - int zeros = 0; - int zzIndex = ZigZag8x8[k]; - while ((zeros < r || dataUnit[zzIndex] != 0) && k <= end) { - if (dataUnit[zzIndex] != 0) { - dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); - } else { - zeros++; - } - k++; - zzIndex = ZigZag8x8[k]; - } - if (bit != 0) { - dataUnit[zzIndex] = 1 << approxBit; - } else { - dataUnit[zzIndex] = -1 << approxBit; - } - k++; - } - } - } + int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; + JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; + int k = start; + while (k <= end) { + if (eobrun > 0) { + while (k <= end) { + int zzIndex = ZigZag8x8[k]; + if (dataUnit[zzIndex] != 0) { + dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); + } + k++; + } + eobrun--; + } else { + int rs = decodeUsingTable(acTable); + int r = rs >> 4; + int s = rs & 0xF; + if (s == 0) { + if (r == 15) { + int zeros = 0; + while (zeros < 16 && k <= end) { + int zzIndex = ZigZag8x8[k]; + if (dataUnit[zzIndex] != 0) { + dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); + } else { + zeros++; + } + k++; + } + } else { + eobrun = (1 << r) + receive(r); + } + } else { + int bit = receive(s); + int zeros = 0; + int zzIndex = ZigZag8x8[k]; + while ((zeros < r || dataUnit[zzIndex] != 0) && k <= end) { + if (dataUnit[zzIndex] != 0) { + dataUnit[zzIndex] = refineAC(dataUnit[zzIndex], approxBit); + } else { + zeros++; + } + k++; + zzIndex = ZigZag8x8[k]; + } + if (bit != 0) { + dataUnit[zzIndex] = 1 << approxBit; + } else { + dataUnit[zzIndex] = -1 << approxBit; + } + k++; + } + } + } } int refineAC(int ac, int approxBit) { - if (ac > 0) { - int bit = nextBit(); - if (bit != 0) { - ac += 1 << approxBit; - } - } else if (ac < 0) { - int bit = nextBit(); - if (bit != 0) { - ac += -1 << approxBit; - } - } - return ac; + if (ac > 0) { + int bit = nextBit(); + if (bit != 0) { + ac += 1 << approxBit; + } + } else if (ac < 0) { + int bit = nextBit(); + if (bit != 0) { + ac += -1 << approxBit; + } + } + return ac; } void decodeDCCoefficient(int[] dataUnit, int iComp, bool first, int approxBit) { - int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; - JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]]; - int lastDC = 0; - if (progressive && !first) { - int bit = nextBit(); - lastDC = dataUnit[0] + (bit << approxBit); - } else { - lastDC = precedingDCs[iComp]; - int nBits = decodeUsingTable(dcTable); - if (nBits != 0) { - int bits = receive(nBits); - int diff = extendBy(bits, nBits); - lastDC += diff; - precedingDCs[iComp] = lastDC; - } - if (progressive) { - lastDC = lastDC << approxBit; - } - } - dataUnit[0] = lastDC; + int[] sParams = scanHeader.componentParameters[componentIds[iComp]]; + JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]]; + int lastDC = 0; + if (progressive && !first) { + int bit = nextBit(); + lastDC = dataUnit[0] + (bit << approxBit); + } else { + lastDC = precedingDCs[iComp]; + int nBits = decodeUsingTable(dcTable); + if (nBits != 0) { + int bits = receive(nBits); + int diff = extendBy(bits, nBits); + lastDC += diff; + precedingDCs[iComp] = lastDC; + } + if (progressive) { + lastDC = lastDC << approxBit; + } + } + dataUnit[0] = lastDC; } void dequantize(int[] dataUnit, int iComp) { - int[] qTable = quantizationTables[frameComponents[componentIds[iComp]][TQI]]; - for (int i = 0; i < dataUnit.length; i++) { - int zzIndex = ZigZag8x8[i]; - dataUnit[zzIndex] = dataUnit[zzIndex] * qTable[i]; - } + int[] qTable = quantizationTables[frameComponents[componentIds[iComp]][TQI]]; + for (int i = 0; i < dataUnit.length; i++) { + int zzIndex = ZigZag8x8[i]; + dataUnit[zzIndex] = dataUnit[zzIndex] * qTable[i]; + } } byte[] decodeImageComponents() { - if (nComponents == 3) { // compIds 1, 2, 3 - return convertYCbCrToRGB(); - } -// if (nComponents == 3) { // compIds 1, 4, 5 -// Unsupported CMYK format. -// return convertYIQToRGB(); -// } - if (nComponents == 4) { - return convertCMYKToRGB(); - } - return convertYToRGB(); + if (nComponents == 3) { // compIds 1, 2, 3 + return convertYCbCrToRGB(); + } +// if (nComponents == 3) { // compIds 1, 4, 5 +// Unsupported CMYK format. +// return convertYIQToRGB(); +// } + if (nComponents == 4) { + return convertCMYKToRGB(); + } + return convertYToRGB(); } void decodeMCUAtXAndY(int xmcu, int ymcu, int nComponentsInScan, bool first, int start, int end, int approxBit) { - for (int iComp = 0; iComp < nComponentsInScan; iComp++) { - int scanComponent = iComp; - while (scanHeader.componentParameters[componentIds[scanComponent]] == null) { - scanComponent++; - } - int[] frameComponent = frameComponents[componentIds[scanComponent]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - if (nComponentsInScan == 1) { - hi = 1; - vi = 1; - } - int compWidth = frameComponent[CW]; - for (int ivi = 0; ivi < vi; ivi++) { - for (int ihi = 0; ihi < hi; ihi++) { - if (progressive) { - // Progressive: First scan - create a new data unit. - // Subsequent scans - refine the existing data unit. - int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi; - dataUnit = dataUnits[scanComponent][index]; - if (dataUnit == null) { - dataUnit = new int[64]; - dataUnits[scanComponent][index] = dataUnit; - } - } else { - // Sequential: Clear and reuse the data unit buffer. - for (int i = 0; i < dataUnit.length; i++) { - dataUnit[i] = 0; - } - } - if (!progressive || scanHeader.isDCProgressiveScan()) { - decodeDCCoefficient(dataUnit, scanComponent, first, approxBit); - } - if (!progressive) { - decodeACCoefficients(dataUnit, scanComponent); - } else { - if (scanHeader.isACProgressiveScan()) { - if (first) { - decodeACFirstCoefficients(dataUnit, scanComponent, start, end, approxBit); - } else { - decodeACRefineCoefficients(dataUnit, scanComponent, start, end, approxBit); - } - } - if (loader.hasListeners()) { - // Dequantization, IDCT, up-sampling and color conversion - // are done on a copy of the coefficient data in order to - // display the image incrementally. + for (int iComp = 0; iComp < nComponentsInScan; iComp++) { + int scanComponent = iComp; + while (scanHeader.componentParameters[componentIds[scanComponent]] == null) { + scanComponent++; + } + int[] frameComponent = frameComponents[componentIds[scanComponent]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + if (nComponentsInScan == 1) { + hi = 1; + vi = 1; + } + int compWidth = frameComponent[CW]; + for (int ivi = 0; ivi < vi; ivi++) { + for (int ihi = 0; ihi < hi; ihi++) { + if (progressive) { + // Progressive: First scan - create a new data unit. + // Subsequent scans - refine the existing data unit. + int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi; + dataUnit = dataUnits[scanComponent][index]; + if (dataUnit == null) { + dataUnit = new int[64]; + dataUnits[scanComponent][index] = dataUnit; + } + } else { + // Sequential: Clear and reuse the data unit buffer. + for (int i = 0; i < dataUnit.length; i++) { + dataUnit[i] = 0; + } + } + if (!progressive || scanHeader.isDCProgressiveScan()) { + decodeDCCoefficient(dataUnit, scanComponent, first, approxBit); + } + if (!progressive) { + decodeACCoefficients(dataUnit, scanComponent); + } else { + if (scanHeader.isACProgressiveScan()) { + if (first) { + decodeACFirstCoefficients(dataUnit, scanComponent, start, end, approxBit); + } else { + decodeACRefineCoefficients(dataUnit, scanComponent, start, end, approxBit); + } + } + if (loader.hasListeners()) { + // Dequantization, IDCT, up-sampling and color conversion + // are done on a copy of the coefficient data in order to + // display the image incrementally. int[] temp = dataUnit; dataUnit = new int[64]; System.arraycopy(temp, 0, dataUnit, 0, 64); - } - } - if (!progressive || (progressive && loader.hasListeners())) { - dequantize(dataUnit, scanComponent); - inverseDCT(dataUnit); - storeData(dataUnit, scanComponent, xmcu, ymcu, hi, ihi, vi, ivi); - } - } - } - } + } + } + if (!progressive || (progressive && loader.hasListeners())) { + dequantize(dataUnit, scanComponent); + inverseDCT(dataUnit); + storeData(dataUnit, scanComponent, xmcu, ymcu, hi, ihi, vi, ivi); + } + } + } + } } void decodeScan() { - if (progressive && !scanHeader.verifyProgressiveScan()) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - int nComponentsInScan = scanHeader.getNumberOfImageComponents(); - int mcuRowsInScan = interleavedMcuRows; - int mcusPerRow = interleavedMcuCols; - if (nComponentsInScan == 1) { - // Non-interleaved. - int scanComponent = 0; - while (scanHeader.componentParameters[componentIds[scanComponent]] == null) { - scanComponent++; - } - int[] frameComponent = frameComponents[componentIds[scanComponent]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - int mcuWidth = DCTSIZE * maxH / hi; - int mcuHeight = DCTSIZE * maxV / vi; - mcusPerRow = (imageWidth + mcuWidth - 1) / mcuWidth; - mcuRowsInScan = (imageHeight + mcuHeight - 1) / mcuHeight; - } - bool first = scanHeader.isFirstScan(); - int start = scanHeader.getStartOfSpectralSelection(); - int end = scanHeader.getEndOfSpectralSelection(); - int approxBit = scanHeader.getApproxBitPositionLow(); - restartsToGo = restartInterval; - nextRestartNumber = 0; - for (int ymcu = 0; ymcu < mcuRowsInScan; ymcu++) { - for (int xmcu = 0; xmcu < mcusPerRow; xmcu++) { - if (restartInterval != 0) { - if (restartsToGo == 0) processRestartInterval(); - restartsToGo--; - } - decodeMCUAtXAndY(xmcu, ymcu, nComponentsInScan, first, start, end, approxBit); - } - } + if (progressive && !scanHeader.verifyProgressiveScan()) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + int nComponentsInScan = scanHeader.getNumberOfImageComponents(); + int mcuRowsInScan = interleavedMcuRows; + int mcusPerRow = interleavedMcuCols; + if (nComponentsInScan == 1) { + // Non-interleaved. + int scanComponent = 0; + while (scanHeader.componentParameters[componentIds[scanComponent]] == null) { + scanComponent++; + } + int[] frameComponent = frameComponents[componentIds[scanComponent]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + int mcuWidth = DCTSIZE * maxH / hi; + int mcuHeight = DCTSIZE * maxV / vi; + mcusPerRow = (imageWidth + mcuWidth - 1) / mcuWidth; + mcuRowsInScan = (imageHeight + mcuHeight - 1) / mcuHeight; + } + bool first = scanHeader.isFirstScan(); + int start = scanHeader.getStartOfSpectralSelection(); + int end = scanHeader.getEndOfSpectralSelection(); + int approxBit = scanHeader.getApproxBitPositionLow(); + restartsToGo = restartInterval; + nextRestartNumber = 0; + for (int ymcu = 0; ymcu < mcuRowsInScan; ymcu++) { + for (int xmcu = 0; xmcu < mcusPerRow; xmcu++) { + if (restartInterval != 0) { + if (restartsToGo == 0) processRestartInterval(); + restartsToGo--; + } + decodeMCUAtXAndY(xmcu, ymcu, nComponentsInScan, first, start, end, approxBit); + } + } } int decodeUsingTable(JPEGHuffmanTable huffmanTable) { - int i = 0; - int[] maxCodes = huffmanTable.getDhMaxCodes(); - int[] minCodes = huffmanTable.getDhMinCodes(); - int[] valPtrs = huffmanTable.getDhValPtrs(); - int[] huffVals = huffmanTable.getDhValues(); - int code = nextBit(); - while (code > maxCodes[i]) { - code = code * 2 + nextBit(); - i++; - } - int j = valPtrs[i] + code - minCodes[i]; - return huffVals[j]; + int i = 0; + int[] maxCodes = huffmanTable.getDhMaxCodes(); + int[] minCodes = huffmanTable.getDhMinCodes(); + int[] valPtrs = huffmanTable.getDhValPtrs(); + int[] huffVals = huffmanTable.getDhValues(); + int code = nextBit(); + while (code > maxCodes[i]) { + code = code * 2 + nextBit(); + i++; + } + int j = valPtrs[i] + code - minCodes[i]; + return huffVals[j]; } void emit(int huffCode, int nBits) { - if (nBits == 0) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - int[] power2m1 = [ - 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, - 16383, 32767, 65535, 131125 - ]; - int code = (huffCode & power2m1[nBits - 1]) << (24 - nBits - currentBitCount); - byte[] codeBuffer = new byte[4]; - codeBuffer[0] = cast(byte)(code & 0xFF); - codeBuffer[1] = cast(byte)((code >> 8) & 0xFF); - codeBuffer[2] = cast(byte)((code >> 16) & 0xFF); - codeBuffer[3] = cast(byte)((code >> 24) & 0xFF); - int abs = nBits - (8 - currentBitCount); - if (abs < 0) abs = -abs; - if ((abs >> 3) > 0) { - currentByte += codeBuffer[2]; - emitByte(cast(byte)currentByte); - emitByte(codeBuffer[1]); - currentByte = codeBuffer[0]; - currentBitCount += nBits - 16; - } else { - currentBitCount += nBits; - if (currentBitCount >= 8) { - currentByte += codeBuffer[2]; - emitByte(cast(byte)currentByte); - currentByte = codeBuffer[1]; - currentBitCount -= 8; - } else { - currentByte += codeBuffer[2]; - } - } + if (nBits == 0) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + int[] power2m1 = [ + 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, + 16383, 32767, 65535, 131125 + ]; + int code = (huffCode & power2m1[nBits - 1]) << (24 - nBits - currentBitCount); + byte[] codeBuffer = new byte[4]; + codeBuffer[0] = cast(byte)(code & 0xFF); + codeBuffer[1] = cast(byte)((code >> 8) & 0xFF); + codeBuffer[2] = cast(byte)((code >> 16) & 0xFF); + codeBuffer[3] = cast(byte)((code >> 24) & 0xFF); + int abs = nBits - (8 - currentBitCount); + if (abs < 0) abs = -abs; + if ((abs >> 3) > 0) { + currentByte += codeBuffer[2]; + emitByte(cast(byte)currentByte); + emitByte(codeBuffer[1]); + currentByte = codeBuffer[0]; + currentBitCount += nBits - 16; + } else { + currentBitCount += nBits; + if (currentBitCount >= 8) { + currentByte += codeBuffer[2]; + emitByte(cast(byte)currentByte); + currentByte = codeBuffer[1]; + currentBitCount -= 8; + } else { + currentByte += codeBuffer[2]; + } + } } void emitByte(byte byteValue) { - if (bufferCurrentPosition >= 512) { - resetOutputBuffer(); - } - dataBuffer[bufferCurrentPosition] = byteValue; - bufferCurrentPosition++; - if (byteValue == -1) { - emitByte(cast(byte)0); - } + if (bufferCurrentPosition >= 512) { + resetOutputBuffer(); + } + dataBuffer[bufferCurrentPosition] = byteValue; + bufferCurrentPosition++; + if (byteValue == -1) { + emitByte(cast(byte)0); + } } void encodeACCoefficients(int[] dataUnit, int iComp) { - int[] sParams = scanHeader.componentParameters[iComp]; - JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; - int[] ehCodes = acTable.ehCodes; - byte[] ehSizes = acTable.ehCodeLengths; - int r = 0; - int k = 1; - while (k < 64) { - k++; - int acValue = dataUnit[ZigZag8x8[k - 1]]; - if (acValue == 0) { - if (k == 64) { - emit(ehCodes[0], ehSizes[0] & 0xFF); - } else { - r++; - } - } else { - while (r > 15) { - emit(ehCodes[0xF0], ehSizes[0xF0] & 0xFF); - r -= 16; - } - if (acValue < 0) { - int absACValue = acValue; - if (absACValue < 0) absACValue = -absACValue; - int nBits = NBitsTable[absACValue]; - int rs = r * 16 + nBits; - emit(ehCodes[rs], ehSizes[rs] & 0xFF); - emit(0xFFFFFF - absACValue, nBits); - } else { - int nBits = NBitsTable[acValue]; - int rs = r * 16 + nBits; - emit(ehCodes[rs], ehSizes[rs] & 0xFF); - emit(acValue, nBits); - } - r = 0; - } - } + int[] sParams = scanHeader.componentParameters[iComp]; + JPEGHuffmanTable acTable = acHuffmanTables[sParams[AC]]; + int[] ehCodes = acTable.ehCodes; + byte[] ehSizes = acTable.ehCodeLengths; + int r = 0; + int k = 1; + while (k < 64) { + k++; + int acValue = dataUnit[ZigZag8x8[k - 1]]; + if (acValue == 0) { + if (k == 64) { + emit(ehCodes[0], ehSizes[0] & 0xFF); + } else { + r++; + } + } else { + while (r > 15) { + emit(ehCodes[0xF0], ehSizes[0xF0] & 0xFF); + r -= 16; + } + if (acValue < 0) { + int absACValue = acValue; + if (absACValue < 0) absACValue = -absACValue; + int nBits = NBitsTable[absACValue]; + int rs = r * 16 + nBits; + emit(ehCodes[rs], ehSizes[rs] & 0xFF); + emit(0xFFFFFF - absACValue, nBits); + } else { + int nBits = NBitsTable[acValue]; + int rs = r * 16 + nBits; + emit(ehCodes[rs], ehSizes[rs] & 0xFF); + emit(acValue, nBits); + } + r = 0; + } + } } void encodeDCCoefficients(int[] dataUnit, int iComp) { - int[] sParams = scanHeader.componentParameters[iComp]; - JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]]; - int lastDC = precedingDCs[iComp]; - int dcValue = dataUnit[0]; - int diff = dcValue - lastDC; - precedingDCs[iComp] = dcValue; - if (diff < 0) { - int absDiff = 0 - diff; - int nBits = NBitsTable[absDiff]; - emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]); - emit(0xFFFFFF - absDiff, nBits); - } else { - int nBits = NBitsTable[diff]; - emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]); - if (nBits != 0) { - emit(diff, nBits); - } - } + int[] sParams = scanHeader.componentParameters[iComp]; + JPEGHuffmanTable dcTable = dcHuffmanTables[sParams[DC]]; + int lastDC = precedingDCs[iComp]; + int dcValue = dataUnit[0]; + int diff = dcValue - lastDC; + precedingDCs[iComp] = dcValue; + if (diff < 0) { + int absDiff = 0 - diff; + int nBits = NBitsTable[absDiff]; + emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]); + emit(0xFFFFFF - absDiff, nBits); + } else { + int nBits = NBitsTable[diff]; + emit(dcTable.ehCodes[nBits], dcTable.ehCodeLengths[nBits]); + if (nBits != 0) { + emit(diff, nBits); + } + } } void encodeMCUAtXAndY(int xmcu, int ymcu) { - int nComponentsInScan = scanHeader.getNumberOfImageComponents(); - dataUnit = new int[64]; - for (int iComp = 0; iComp < nComponentsInScan; iComp++) { - int[] frameComponent = frameComponents[componentIds[iComp]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - for (int ivi = 0; ivi < vi; ivi++) { - for (int ihi = 0; ihi < hi; ihi++) { - extractData(dataUnit, iComp, xmcu, ymcu, ihi, ivi); - forwardDCT(dataUnit); - quantizeData(dataUnit, iComp); - encodeDCCoefficients(dataUnit, iComp); - encodeACCoefficients(dataUnit, iComp); - } - } - } + int nComponentsInScan = scanHeader.getNumberOfImageComponents(); + dataUnit = new int[64]; + for (int iComp = 0; iComp < nComponentsInScan; iComp++) { + int[] frameComponent = frameComponents[componentIds[iComp]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + for (int ivi = 0; ivi < vi; ivi++) { + for (int ihi = 0; ihi < hi; ihi++) { + extractData(dataUnit, iComp, xmcu, ymcu, ihi, ivi); + forwardDCT(dataUnit); + quantizeData(dataUnit, iComp); + encodeDCCoefficients(dataUnit, iComp); + encodeACCoefficients(dataUnit, iComp); + } + } + } } void encodeScan() { - for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) { - for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) { - encodeMCUAtXAndY(xmcu, ymcu); - } - } - if (currentBitCount != 0) { - emitByte(cast(byte)currentByte); - } - resetOutputBuffer(); + for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) { + for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) { + encodeMCUAtXAndY(xmcu, ymcu); + } + } + if (currentBitCount != 0) { + emitByte(cast(byte)currentByte); + } + resetOutputBuffer(); } void expandImageComponents() { - for (int iComp = 0; iComp < nComponents; iComp++) { - int[] frameComponent = frameComponents[componentIds[iComp]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - int upH = maxH / hi; - int upV = maxV / vi; - if ((upH * upV) > 1) { - byte[] component = imageComponents[iComp]; - int compWidth = frameComponent[CW]; - int compHeight = frameComponent[CH]; - int upCompWidth = compWidth * upH; - int upCompHeight = compHeight * upV; - ImageData src = new ImageData(compWidth, compHeight, 8, new PaletteData(RGB16), 4, component); - ImageData dest = src.scaledTo(upCompWidth, upCompHeight); - imageComponents[iComp] = dest.data; - } - } + for (int iComp = 0; iComp < nComponents; iComp++) { + int[] frameComponent = frameComponents[componentIds[iComp]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + int upH = maxH / hi; + int upV = maxV / vi; + if ((upH * upV) > 1) { + byte[] component = imageComponents[iComp]; + int compWidth = frameComponent[CW]; + int compHeight = frameComponent[CH]; + int upCompWidth = compWidth * upH; + int upCompHeight = compHeight * upV; + ImageData src = new ImageData(compWidth, compHeight, 8, new PaletteData(RGB16), 4, component); + ImageData dest = src.scaledTo(upCompWidth, upCompHeight); + imageComponents[iComp] = dest.data; + } + } } int extendBy(int diff, int t) { - if (diff < ExtendTest[t]) { - return diff + ExtendOffset[t]; - } else { - return diff; - } + if (diff < ExtendTest[t]) { + return diff + ExtendOffset[t]; + } else { + return diff; + } } void extractData(int[] dataUnit, int iComp, int xmcu, int ymcu, int ihi, int ivi) { - byte[] compImage = imageComponents[iComp]; - int[] frameComponent = frameComponents[componentIds[iComp]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - int compWidth = frameComponent[CW]; - int srcIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE); - int destIndex = 0; - for (int i = 0; i < DCTSIZE; i++) { - for (int col = 0; col < DCTSIZE; col++) { - dataUnit[destIndex] = (compImage[srcIndex + col] & 0xFF) - 128; - destIndex++; - } - srcIndex += compWidth; - } + byte[] compImage = imageComponents[iComp]; + int[] frameComponent = frameComponents[componentIds[iComp]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + int compWidth = frameComponent[CW]; + int srcIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE); + int destIndex = 0; + for (int i = 0; i < DCTSIZE; i++) { + for (int col = 0; col < DCTSIZE; col++) { + dataUnit[destIndex] = (compImage[srcIndex + col] & 0xFF) - 128; + destIndex++; + } + srcIndex += compWidth; + } } void forwardDCT(int[] dataUnit) { - for (int row = 0; row < 8; row++) { - int rIndex = row * DCTSIZE; - int tmp0 = dataUnit[rIndex] + dataUnit[rIndex + 7]; - int tmp7 = dataUnit[rIndex] - dataUnit[rIndex + 7]; - int tmp1 = dataUnit[rIndex + 1] + dataUnit[rIndex + 6]; - int tmp6 = dataUnit[rIndex + 1] - dataUnit[rIndex + 6]; - int tmp2 = dataUnit[rIndex + 2] + dataUnit[rIndex + 5]; - int tmp5 = dataUnit[rIndex + 2] - dataUnit[rIndex + 5]; - int tmp3 = dataUnit[rIndex + 3] + dataUnit[rIndex + 4]; - int tmp4 = dataUnit[rIndex + 3] - dataUnit[rIndex + 4]; + for (int row = 0; row < 8; row++) { + int rIndex = row * DCTSIZE; + int tmp0 = dataUnit[rIndex] + dataUnit[rIndex + 7]; + int tmp7 = dataUnit[rIndex] - dataUnit[rIndex + 7]; + int tmp1 = dataUnit[rIndex + 1] + dataUnit[rIndex + 6]; + int tmp6 = dataUnit[rIndex + 1] - dataUnit[rIndex + 6]; + int tmp2 = dataUnit[rIndex + 2] + dataUnit[rIndex + 5]; + int tmp5 = dataUnit[rIndex + 2] - dataUnit[rIndex + 5]; + int tmp3 = dataUnit[rIndex + 3] + dataUnit[rIndex + 4]; + int tmp4 = dataUnit[rIndex + 3] - dataUnit[rIndex + 4]; - /** - * Even part per LL&M figure 1 --- note that published figure - * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'. - */ - int tmp10 = tmp0 + tmp3; - int tmp13 = tmp0 - tmp3; - int tmp11 = tmp1 + tmp2; - int tmp12 = tmp1 - tmp2; + /** + * Even part per LL&M figure 1 --- note that published figure + * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'. + */ + int tmp10 = tmp0 + tmp3; + int tmp13 = tmp0 - tmp3; + int tmp11 = tmp1 + tmp2; + int tmp12 = tmp1 - tmp2; - dataUnit[rIndex] = (tmp10 + tmp11) * 4; - dataUnit[rIndex + 4] = (tmp10 - tmp11) * 4; + dataUnit[rIndex] = (tmp10 + tmp11) * 4; + dataUnit[rIndex + 4] = (tmp10 - tmp11) * 4; - int z1 = (tmp12 + tmp13) * FIX_0_541196100; - int n = z1 + (tmp13 * FIX_0_765366865) + 1024; - dataUnit[rIndex + 2] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 2]--; - n = z1 + (tmp12 * (0 - FIX_1_847759065)) + 1024; - dataUnit[rIndex + 6] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 6]--; + int z1 = (tmp12 + tmp13) * FIX_0_541196100; + int n = z1 + (tmp13 * FIX_0_765366865) + 1024; + dataUnit[rIndex + 2] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 2]--; + n = z1 + (tmp12 * (0 - FIX_1_847759065)) + 1024; + dataUnit[rIndex + 6] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 6]--; - /** - * Odd part per figure 8 --- note paper omits factor of sqrt(2). - * cK represents cos(K*pi/16). - * i0..i3 in the paper are tmp4..tmp7 here. - */ - z1 = tmp4 + tmp7; - int z2 = tmp5 + tmp6; - int z3 = tmp4 + tmp6; - int z4 = tmp5 + tmp7; - int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3 + /** + * Odd part per figure 8 --- note paper omits factor of sqrt(2). + * cK represents cos(K*pi/16). + * i0..i3 in the paper are tmp4..tmp7 here. + */ + z1 = tmp4 + tmp7; + int z2 = tmp5 + tmp6; + int z3 = tmp4 + tmp6; + int z4 = tmp5 + tmp7; + int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3 - tmp4 *= FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7) - tmp5 *= FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7) - tmp6 *= FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7) - tmp7 *= FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7) - z1 *= 0 - FIX_0_899976223; // sqrt(2) * (c7-c3) - z2 *= 0 - FIX_2_562915447; // sqrt(2) * (-c1-c3) - z3 *= 0 - FIX_1_961570560; // sqrt(2) * (-c3-c5) - z4 *= 0 - FIX_0_390180644; // sqrt(2) * (c5-c3) + tmp4 *= FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7) + tmp5 *= FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7) + tmp6 *= FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7) + tmp7 *= FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7) + z1 *= 0 - FIX_0_899976223; // sqrt(2) * (c7-c3) + z2 *= 0 - FIX_2_562915447; // sqrt(2) * (-c1-c3) + z3 *= 0 - FIX_1_961570560; // sqrt(2) * (-c3-c5) + z4 *= 0 - FIX_0_390180644; // sqrt(2) * (c5-c3) - z3 += z5; - z4 += z5; + z3 += z5; + z4 += z5; - n = tmp4 + z1 + z3 + 1024; - dataUnit[rIndex + 7] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 7]--; - n = tmp5 + z2 + z4 + 1024; - dataUnit[rIndex + 5] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 5]--; - n = tmp6 + z2 + z3 + 1024; - dataUnit[rIndex + 3] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 3]--; - n = tmp7 + z1 + z4 + 1024; - dataUnit[rIndex + 1] = n >> 11; - if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 1]--; - } + n = tmp4 + z1 + z3 + 1024; + dataUnit[rIndex + 7] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 7]--; + n = tmp5 + z2 + z4 + 1024; + dataUnit[rIndex + 5] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 5]--; + n = tmp6 + z2 + z3 + 1024; + dataUnit[rIndex + 3] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 3]--; + n = tmp7 + z1 + z4 + 1024; + dataUnit[rIndex + 1] = n >> 11; + if ((n < 0) && ((n & 0x07FF) != 0)) dataUnit[rIndex + 1]--; + } - /** - * Pass 2: process columns. - * Note that we must descale the results by a factor of 8 == 2**3, - * and also undo the PASS1_BITS scaling. - */ - for (int col = 0; col < 8; col++) { - int c0 = col; - int c1 = col + 8; - int c2 = col + 16; - int c3 = col + 24; - int c4 = col + 32; - int c5 = col + 40; - int c6 = col + 48; - int c7 = col + 56; - int tmp0 = dataUnit[c0] + dataUnit[c7]; - int tmp7 = dataUnit[c0] - dataUnit[c7]; - int tmp1 = dataUnit[c1] + dataUnit[c6]; - int tmp6 = dataUnit[c1] - dataUnit[c6]; - int tmp2 = dataUnit[c2] + dataUnit[c5]; - int tmp5 = dataUnit[c2] - dataUnit[c5]; - int tmp3 = dataUnit[c3] + dataUnit[c4]; - int tmp4 = dataUnit[c3] - dataUnit[c4]; + /** + * Pass 2: process columns. + * Note that we must descale the results by a factor of 8 == 2**3, + * and also undo the PASS1_BITS scaling. + */ + for (int col = 0; col < 8; col++) { + int c0 = col; + int c1 = col + 8; + int c2 = col + 16; + int c3 = col + 24; + int c4 = col + 32; + int c5 = col + 40; + int c6 = col + 48; + int c7 = col + 56; + int tmp0 = dataUnit[c0] + dataUnit[c7]; + int tmp7 = dataUnit[c0] - dataUnit[c7]; + int tmp1 = dataUnit[c1] + dataUnit[c6]; + int tmp6 = dataUnit[c1] - dataUnit[c6]; + int tmp2 = dataUnit[c2] + dataUnit[c5]; + int tmp5 = dataUnit[c2] - dataUnit[c5]; + int tmp3 = dataUnit[c3] + dataUnit[c4]; + int tmp4 = dataUnit[c3] - dataUnit[c4]; - /** - * Even part per LL&M figure 1 --- note that published figure - * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'. - */ - int tmp10 = tmp0 + tmp3; - int tmp13 = tmp0 - tmp3; - int tmp11 = tmp1 + tmp2; - int tmp12 = tmp1 - tmp2; + /** + * Even part per LL&M figure 1 --- note that published figure + * is faulty; rotator 'sqrt(2)*c1' should be 'sqrt(2)*c6'. + */ + int tmp10 = tmp0 + tmp3; + int tmp13 = tmp0 - tmp3; + int tmp11 = tmp1 + tmp2; + int tmp12 = tmp1 - tmp2; - int n = tmp10 + tmp11 + 16; - dataUnit[c0] = n >> 5; - if ((n < 0) && ((n & 0x1F) != 0)) dataUnit[c0]--; - n = tmp10 - tmp11 + 16; - dataUnit[c4] = n >> 5; - if ((n < 0) && ((n & 0x1F) != 0)) dataUnit[c4]--; + int n = tmp10 + tmp11 + 16; + dataUnit[c0] = n >> 5; + if ((n < 0) && ((n & 0x1F) != 0)) dataUnit[c0]--; + n = tmp10 - tmp11 + 16; + dataUnit[c4] = n >> 5; + if ((n < 0) && ((n & 0x1F) != 0)) dataUnit[c4]--; - int z1 = (tmp12 + tmp13) * FIX_0_541196100; - n = z1 + (tmp13 * FIX_0_765366865) + 131072; - dataUnit[c2] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c2]--; - n = z1 + (tmp12 * (0 - FIX_1_847759065)) + 131072; - dataUnit[c6] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c6]--; + int z1 = (tmp12 + tmp13) * FIX_0_541196100; + n = z1 + (tmp13 * FIX_0_765366865) + 131072; + dataUnit[c2] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c2]--; + n = z1 + (tmp12 * (0 - FIX_1_847759065)) + 131072; + dataUnit[c6] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c6]--; - /** - * Odd part per figure 8 --- note paper omits factor of sqrt(2). - * cK represents cos(K*pi/16). - * i0..i3 in the paper are tmp4..tmp7 here. - */ - z1 = tmp4 + tmp7; - int z2 = tmp5 + tmp6; - int z3 = tmp4 + tmp6; - int z4 = tmp5 + tmp7; - int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3 + /** + * Odd part per figure 8 --- note paper omits factor of sqrt(2). + * cK represents cos(K*pi/16). + * i0..i3 in the paper are tmp4..tmp7 here. + */ + z1 = tmp4 + tmp7; + int z2 = tmp5 + tmp6; + int z3 = tmp4 + tmp6; + int z4 = tmp5 + tmp7; + int z5 = (z3 + z4) * FIX_1_175875602; // sqrt(2) * c3 - tmp4 *= FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7) - tmp5 *= FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7) - tmp6 *= FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7) - tmp7 *= FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7) - z1 *= 0 - FIX_0_899976223; // sqrt(2) * (c7-c3) - z2 *= 0 - FIX_2_562915447; // sqrt(2) * (-c1-c3) - z3 *= 0 - FIX_1_961570560; // sqrt(2) * (-c3-c5) - z4 *= 0 - FIX_0_390180644; // sqrt(2) * (c5-c3) + tmp4 *= FIX_0_298631336; // sqrt(2) * (-c1+c3+c5-c7) + tmp5 *= FIX_2_053119869; // sqrt(2) * ( c1+c3-c5+c7) + tmp6 *= FIX_3_072711026; // sqrt(2) * ( c1+c3+c5-c7) + tmp7 *= FIX_1_501321110; // sqrt(2) * ( c1+c3-c5-c7) + z1 *= 0 - FIX_0_899976223; // sqrt(2) * (c7-c3) + z2 *= 0 - FIX_2_562915447; // sqrt(2) * (-c1-c3) + z3 *= 0 - FIX_1_961570560; // sqrt(2) * (-c3-c5) + z4 *= 0 - FIX_0_390180644; // sqrt(2) * (c5-c3) - z3 += z5; - z4 += z5; + z3 += z5; + z4 += z5; - n = tmp4 + z1 + z3 + 131072; - dataUnit[c7] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c7]--; - n = tmp5 + z2 + z4 + 131072; - dataUnit[c5] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c5]--; - n = tmp6 + z2 + z3 + 131072; - dataUnit[c3] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c3]--; - n = tmp7 + z1 + z4 + 131072; - dataUnit[c1] = n >> 18; - if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c1]--; - } + n = tmp4 + z1 + z3 + 131072; + dataUnit[c7] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c7]--; + n = tmp5 + z2 + z4 + 131072; + dataUnit[c5] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c5]--; + n = tmp6 + z2 + z3 + 131072; + dataUnit[c3] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c3]--; + n = tmp7 + z1 + z4 + 131072; + dataUnit[c1] = n >> 18; + if ((n < 0) && ((n & 0x3FFFF) != 0)) dataUnit[c1]--; + } } void getAPP0() { - JPEGAppn appn = new JPEGAppn(inputStream); - if (!appn.verify()) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + JPEGAppn appn = new JPEGAppn(inputStream); + if (!appn.verify()) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } } void getCOM() { - new JPEGComment(inputStream); + new JPEGComment(inputStream); } void getDAC() { - new JPEGArithmeticConditioningTable(inputStream); + new JPEGArithmeticConditioningTable(inputStream); } void getDHT() { - JPEGHuffmanTable dht = new JPEGHuffmanTable(inputStream); - if (!dht.verify()) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - if (acHuffmanTables == null) { - acHuffmanTables = new JPEGHuffmanTable[4]; - } - if (dcHuffmanTables == null) { - dcHuffmanTables = new JPEGHuffmanTable[4]; - } - JPEGHuffmanTable[] dhtTables = dht.getAllTables(); - for (int i = 0; i < dhtTables.length; i++) { - JPEGHuffmanTable dhtTable = dhtTables[i]; - if (dhtTable.getTableClass() == 0) { - dcHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable; - } else { - acHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable; - } - } + JPEGHuffmanTable dht = new JPEGHuffmanTable(inputStream); + if (!dht.verify()) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + if (acHuffmanTables == null) { + acHuffmanTables = new JPEGHuffmanTable[4]; + } + if (dcHuffmanTables == null) { + dcHuffmanTables = new JPEGHuffmanTable[4]; + } + JPEGHuffmanTable[] dhtTables = dht.getAllTables(); + for (int i = 0; i < dhtTables.length; i++) { + JPEGHuffmanTable dhtTable = dhtTables[i]; + if (dhtTable.getTableClass() == 0) { + dcHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable; + } else { + acHuffmanTables[dhtTable.getTableIdentifier()] = dhtTable; + } + } } void getDNL() { - new JPEGRestartInterval(inputStream); + new JPEGRestartInterval(inputStream); } void getDQT() { - JPEGQuantizationTable dqt = new JPEGQuantizationTable(inputStream); - int[][] currentTables = quantizationTables; - if (currentTables == null) { - currentTables = new int[][](4); - } - int[] dqtTablesKeys = dqt.getQuantizationTablesKeys(); - int[][] dqtTablesValues = dqt.getQuantizationTablesValues(); - for (int i = 0; i < dqtTablesKeys.length; i++) { - int index = dqtTablesKeys[i]; - currentTables[index] = dqtTablesValues[i]; - } - quantizationTables = currentTables; + JPEGQuantizationTable dqt = new JPEGQuantizationTable(inputStream); + int[][] currentTables = quantizationTables; + if (currentTables == null) { + currentTables = new int[][](4); + } + int[] dqtTablesKeys = dqt.getQuantizationTablesKeys(); + int[][] dqtTablesValues = dqt.getQuantizationTablesValues(); + for (int i = 0; i < dqtTablesKeys.length; i++) { + int index = dqtTablesKeys[i]; + currentTables[index] = dqtTablesValues[i]; + } + quantizationTables = currentTables; } void getDRI() { - JPEGRestartInterval dri = new JPEGRestartInterval(inputStream); - if (!dri.verify()) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - restartInterval = dri.getRestartInterval(); + JPEGRestartInterval dri = new JPEGRestartInterval(inputStream); + if (!dri.verify()) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + restartInterval = dri.getRestartInterval(); } static void initialize() { - initializeRGBYCbCrTables(); - initializeYCbCrRGBTables(); - initializeBitCountTable(); + initializeRGBYCbCrTables(); + initializeYCbCrRGBTables(); + initializeBitCountTable(); } static void initializeBitCountTable() { - int nBits = 1; - int power2 = 2; - NBitsTable = new int[2048]; - NBitsTable[0] = 0; - for (int i = 1; i < NBitsTable.length; i++) { - if (!(i < power2)) { - nBits++; - power2 *= 2; - } - NBitsTable[i] = nBits; - } + int nBits = 1; + int power2 = 2; + NBitsTable = new int[2048]; + NBitsTable[0] = 0; + for (int i = 1; i < NBitsTable.length; i++) { + if (!(i < power2)) { + nBits++; + power2 *= 2; + } + NBitsTable[i] = nBits; + } } static void initializeRGBYCbCrTables() { - RYTable = new int[256]; - GYTable = new int[256]; - BYTable = new int[256]; - RCbTable = new int[256]; - GCbTable = new int[256]; - BCbTable = new int[256]; - RCrTable = BCbTable; - GCrTable = new int[256]; - BCrTable = new int[256]; - for (int i = 0; i < 256; i++) { - RYTable[i] = i * 19595; - GYTable[i] = i * 38470; - BYTable[i] = i * 7471 + 32768; - RCbTable[i] = i * -11059; - GCbTable[i] = i * -21709; - BCbTable[i] = i * 32768 + 8388608; - GCrTable[i] = i * -27439; - BCrTable[i] = i * -5329; - } + RYTable = new int[256]; + GYTable = new int[256]; + BYTable = new int[256]; + RCbTable = new int[256]; + GCbTable = new int[256]; + BCbTable = new int[256]; + RCrTable = BCbTable; + GCrTable = new int[256]; + BCrTable = new int[256]; + for (int i = 0; i < 256; i++) { + RYTable[i] = i * 19595; + GYTable[i] = i * 38470; + BYTable[i] = i * 7471 + 32768; + RCbTable[i] = i * -11059; + GCbTable[i] = i * -21709; + BCbTable[i] = i * 32768 + 8388608; + GCrTable[i] = i * -27439; + BCrTable[i] = i * -5329; + } } static void initializeYCbCrRGBTables() { - CrRTable = new int[256]; - CbBTable = new int[256]; - CrGTable = new int[256]; - CbGTable = new int[256]; - for (int i = 0; i < 256; i++) { - int x2 = 2 * i - 255; - CrRTable[i] = (45941 * x2 + 32768) >> 16; - CbBTable[i] = (58065 * x2 + 32768) >> 16; - CrGTable[i] = -23401 * x2; - CbGTable[i] = -11277 * x2 + 32768; - } + CrRTable = new int[256]; + CbBTable = new int[256]; + CrGTable = new int[256]; + CbGTable = new int[256]; + for (int i = 0; i < 256; i++) { + int x2 = 2 * i - 255; + CrRTable[i] = (45941 * x2 + 32768) >> 16; + CbBTable[i] = (58065 * x2 + 32768) >> 16; + CrGTable[i] = -23401 * x2; + CbGTable[i] = -11277 * x2 + 32768; + } } void inverseDCT(int[] dataUnit) { - for (int row = 0; row < 8; row++) { - int rIndex = row * DCTSIZE; - /** - * Due to quantization, we will usually find that many of the input - * coefficients are zero, especially the AC terms. We can exploit this - * by short-circuiting the IDCT calculation for any row in which all - * the AC terms are zero. In that case each output is equal to the - * DC coefficient (with scale factor as needed). - * With typical images and quantization tables, half or more of the - * row DCT calculations can be simplified this way. - */ - if (isZeroInRow(dataUnit, rIndex)) { - int dcVal = dataUnit[rIndex] << 2; - for (int i = rIndex + 7; i >= rIndex; i--) { - dataUnit[i] = dcVal; - } - } else { - /** - * Even part: reverse the even part of the forward DCT. - * The rotator is sqrt(2)*c(-6). - */ - int z2 = dataUnit[rIndex + 2]; - int z3 = dataUnit[rIndex + 6]; - int z1 = (z2 + z3) * FIX_0_541196100; - int tmp2 = z1 + (z3 * (0 - FIX_1_847759065)); - int tmp3 = z1 + (z2 * FIX_0_765366865); - int tmp0 = (dataUnit[rIndex] + dataUnit[rIndex + 4]) << 13; - int tmp1 = (dataUnit[rIndex] - dataUnit[rIndex + 4]) << 13; - int tmp10 = tmp0 + tmp3; - int tmp13 = tmp0 - tmp3; - int tmp11 = tmp1 + tmp2; - int tmp12 = tmp1 - tmp2; - /** - * Odd part per figure 8; the matrix is unitary and hence its - * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. - */ - tmp0 = dataUnit[rIndex + 7]; - tmp1 = dataUnit[rIndex + 5]; - tmp2 = dataUnit[rIndex + 3]; - tmp3 = dataUnit[rIndex + 1]; - z1 = tmp0 + tmp3; - z2 = tmp1 + tmp2; - z3 = tmp0 + tmp2; - int z4 = tmp1 + tmp3; - int z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */ + for (int row = 0; row < 8; row++) { + int rIndex = row * DCTSIZE; + /** + * Due to quantization, we will usually find that many of the input + * coefficients are zero, especially the AC terms. We can exploit this + * by short-circuiting the IDCT calculation for any row in which all + * the AC terms are zero. In that case each output is equal to the + * DC coefficient (with scale factor as needed). + * With typical images and quantization tables, half or more of the + * row DCT calculations can be simplified this way. + */ + if (isZeroInRow(dataUnit, rIndex)) { + int dcVal = dataUnit[rIndex] << 2; + for (int i = rIndex + 7; i >= rIndex; i--) { + dataUnit[i] = dcVal; + } + } else { + /** + * Even part: reverse the even part of the forward DCT. + * The rotator is sqrt(2)*c(-6). + */ + int z2 = dataUnit[rIndex + 2]; + int z3 = dataUnit[rIndex + 6]; + int z1 = (z2 + z3) * FIX_0_541196100; + int tmp2 = z1 + (z3 * (0 - FIX_1_847759065)); + int tmp3 = z1 + (z2 * FIX_0_765366865); + int tmp0 = (dataUnit[rIndex] + dataUnit[rIndex + 4]) << 13; + int tmp1 = (dataUnit[rIndex] - dataUnit[rIndex + 4]) << 13; + int tmp10 = tmp0 + tmp3; + int tmp13 = tmp0 - tmp3; + int tmp11 = tmp1 + tmp2; + int tmp12 = tmp1 - tmp2; + /** + * Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + tmp0 = dataUnit[rIndex + 7]; + tmp1 = dataUnit[rIndex + 5]; + tmp2 = dataUnit[rIndex + 3]; + tmp3 = dataUnit[rIndex + 1]; + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + int z4 = tmp1 + tmp3; + int z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */ - tmp0 *= FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ - tmp1 *= FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ - tmp2 *= FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ - tmp3 *= FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ - z1 *= 0 - FIX_0_899976223; /* sqrt(2) * (c7-c3) */ - z2 *= 0 - FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ - z3 *= 0 - FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ - z4 *= 0 - FIX_0_390180644; /* sqrt(2) * (c5-c3) */ + tmp0 *= FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 *= FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 *= FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 *= FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 *= 0 - FIX_0_899976223; /* sqrt(2) * (c7-c3) */ + z2 *= 0 - FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ + z3 *= 0 - FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ + z4 *= 0 - FIX_0_390180644; /* sqrt(2) * (c5-c3) */ - z3 += z5; - z4 += z5; - tmp0 += z1 + z3; - tmp1 += z2 + z4; - tmp2 += z2 + z3; - tmp3 += z1 + z4; + z3 += z5; + z4 += z5; + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; - dataUnit[rIndex] = (tmp10 + tmp3 + 1024) >> 11; - dataUnit[rIndex + 7] = (tmp10 - tmp3 + 1024) >> 11; - dataUnit[rIndex + 1] = (tmp11 + tmp2 + 1024) >> 11; - dataUnit[rIndex + 6] = (tmp11 - tmp2 + 1024) >> 11; - dataUnit[rIndex + 2] = (tmp12 + tmp1 + 1024) >> 11; - dataUnit[rIndex + 5] = (tmp12 - tmp1 + 1024) >> 11; - dataUnit[rIndex + 3] = (tmp13 + tmp0 + 1024) >> 11; - dataUnit[rIndex + 4] = (tmp13 - tmp0 + 1024) >> 11; - } - } - /** - * Pass 2: process columns. - * Note that we must descale the results by a factor of 8 == 2**3, - * and also undo the PASS1_BITS scaling. - */ - for (int col = 0; col < 8; col++) { - int c0 = col; - int c1 = col + 8; - int c2 = col + 16; - int c3 = col + 24; - int c4 = col + 32; - int c5 = col + 40; - int c6 = col + 48; - int c7 = col + 56; - if (isZeroInColumn(dataUnit, col)) { - int dcVal = (dataUnit[c0] + 16) >> 5; - dataUnit[c0] = dcVal; - dataUnit[c1] = dcVal; - dataUnit[c2] = dcVal; - dataUnit[c3] = dcVal; - dataUnit[c4] = dcVal; - dataUnit[c5] = dcVal; - dataUnit[c6] = dcVal; - dataUnit[c7] = dcVal; - } else { - /** - * Even part: reverse the even part of the forward DCT. - * The rotator is sqrt(2)*c(-6). - */ - int z0 = dataUnit[c0]; - int z2 = dataUnit[c2]; - int z3 = dataUnit[c6]; - int z4 = dataUnit[c4]; - int z1 = (z2 + z3) * FIX_0_541196100; - int tmp2 = z1 + (z3 * (0 - FIX_1_847759065)); - int tmp3 = z1 + (z2 * FIX_0_765366865); - int tmp0 = (z0 + z4) << 13; - int tmp1 = (z0 - z4) << 13; - int tmp10 = tmp0 + tmp3; - int tmp13 = tmp0 - tmp3; - int tmp11 = tmp1 + tmp2; - int tmp12 = tmp1 - tmp2; - /** - * Odd part per figure 8; the matrix is unitary and hence its - * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. - */ - tmp0 = dataUnit[c7]; - tmp1 = dataUnit[c5]; - tmp2 = dataUnit[c3]; - tmp3 = dataUnit[c1]; - z1 = tmp0 + tmp3; - z2 = tmp1 + tmp2; - z3 = tmp0 + tmp2; - z4 = tmp1 + tmp3; - z0 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */ + dataUnit[rIndex] = (tmp10 + tmp3 + 1024) >> 11; + dataUnit[rIndex + 7] = (tmp10 - tmp3 + 1024) >> 11; + dataUnit[rIndex + 1] = (tmp11 + tmp2 + 1024) >> 11; + dataUnit[rIndex + 6] = (tmp11 - tmp2 + 1024) >> 11; + dataUnit[rIndex + 2] = (tmp12 + tmp1 + 1024) >> 11; + dataUnit[rIndex + 5] = (tmp12 - tmp1 + 1024) >> 11; + dataUnit[rIndex + 3] = (tmp13 + tmp0 + 1024) >> 11; + dataUnit[rIndex + 4] = (tmp13 - tmp0 + 1024) >> 11; + } + } + /** + * Pass 2: process columns. + * Note that we must descale the results by a factor of 8 == 2**3, + * and also undo the PASS1_BITS scaling. + */ + for (int col = 0; col < 8; col++) { + int c0 = col; + int c1 = col + 8; + int c2 = col + 16; + int c3 = col + 24; + int c4 = col + 32; + int c5 = col + 40; + int c6 = col + 48; + int c7 = col + 56; + if (isZeroInColumn(dataUnit, col)) { + int dcVal = (dataUnit[c0] + 16) >> 5; + dataUnit[c0] = dcVal; + dataUnit[c1] = dcVal; + dataUnit[c2] = dcVal; + dataUnit[c3] = dcVal; + dataUnit[c4] = dcVal; + dataUnit[c5] = dcVal; + dataUnit[c6] = dcVal; + dataUnit[c7] = dcVal; + } else { + /** + * Even part: reverse the even part of the forward DCT. + * The rotator is sqrt(2)*c(-6). + */ + int z0 = dataUnit[c0]; + int z2 = dataUnit[c2]; + int z3 = dataUnit[c6]; + int z4 = dataUnit[c4]; + int z1 = (z2 + z3) * FIX_0_541196100; + int tmp2 = z1 + (z3 * (0 - FIX_1_847759065)); + int tmp3 = z1 + (z2 * FIX_0_765366865); + int tmp0 = (z0 + z4) << 13; + int tmp1 = (z0 - z4) << 13; + int tmp10 = tmp0 + tmp3; + int tmp13 = tmp0 - tmp3; + int tmp11 = tmp1 + tmp2; + int tmp12 = tmp1 - tmp2; + /** + * Odd part per figure 8; the matrix is unitary and hence its + * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively. + */ + tmp0 = dataUnit[c7]; + tmp1 = dataUnit[c5]; + tmp2 = dataUnit[c3]; + tmp3 = dataUnit[c1]; + z1 = tmp0 + tmp3; + z2 = tmp1 + tmp2; + z3 = tmp0 + tmp2; + z4 = tmp1 + tmp3; + z0 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */ - tmp0 *= FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ - tmp1 *= FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ - tmp2 *= FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ - tmp3 *= FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ - z1 *= 0 - FIX_0_899976223; /* sqrt(2) * (c7-c3) */ - z2 *= 0 - FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ - z3 *= 0 - FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ - z4 *= 0 - FIX_0_390180644; /* sqrt(2) * (c5-c3) */ + tmp0 *= FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ + tmp1 *= FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ + tmp2 *= FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ + tmp3 *= FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ + z1 *= 0 - FIX_0_899976223; /* sqrt(2) * (c7-c3) */ + z2 *= 0 - FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ + z3 *= 0 - FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ + z4 *= 0 - FIX_0_390180644; /* sqrt(2) * (c5-c3) */ - z3 += z0; - z4 += z0; + z3 += z0; + z4 += z0; - tmp0 += z1 + z3; - tmp1 += z2 + z4; - tmp2 += z2 + z3; - tmp3 += z1 + z4; + tmp0 += z1 + z3; + tmp1 += z2 + z4; + tmp2 += z2 + z3; + tmp3 += z1 + z4; - /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ - dataUnit[c0] = (tmp10 + tmp3 + 131072) >> 18; - dataUnit[c7] = (tmp10 - tmp3 + 131072) >> 18; - dataUnit[c1] = (tmp11 + tmp2 + 131072) >> 18; - dataUnit[c6] = (tmp11 - tmp2 + 131072) >> 18; - dataUnit[c2] = (tmp12 + tmp1 + 131072) >> 18; - dataUnit[c5] = (tmp12 - tmp1 + 131072) >> 18; - dataUnit[c3] = (tmp13 + tmp0 + 131072) >> 18; - dataUnit[c4] = (tmp13 - tmp0 + 131072) >> 18; - } - } + /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */ + dataUnit[c0] = (tmp10 + tmp3 + 131072) >> 18; + dataUnit[c7] = (tmp10 - tmp3 + 131072) >> 18; + dataUnit[c1] = (tmp11 + tmp2 + 131072) >> 18; + dataUnit[c6] = (tmp11 - tmp2 + 131072) >> 18; + dataUnit[c2] = (tmp12 + tmp1 + 131072) >> 18; + dataUnit[c5] = (tmp12 - tmp1 + 131072) >> 18; + dataUnit[c3] = (tmp13 + tmp0 + 131072) >> 18; + dataUnit[c4] = (tmp13 - tmp0 + 131072) >> 18; + } + } } bool isFileFormat(LEDataInputStream stream) { - try { - JPEGStartOfImage soi = new JPEGStartOfImage(stream); - stream.unread(soi.reference); - return soi.verify(); // we no longer check for appN - } catch (TracedException e) { - return false; - } + try { + JPEGStartOfImage soi = new JPEGStartOfImage(stream); + stream.unread(soi.reference); + return soi.verify(); // we no longer check for appN + } catch (TracedException e) { + return false; + } } bool isZeroInColumn(int[] dataUnit, int col) { - return dataUnit[col + 8] == 0 && dataUnit[col + 16] == 0 - && dataUnit[col + 24] == 0 && dataUnit[col + 32] == 0 - && dataUnit[col + 40] == 0 && dataUnit[col + 48] == 0 - && dataUnit[col + 56] == 0; + return dataUnit[col + 8] == 0 && dataUnit[col + 16] == 0 + && dataUnit[col + 24] == 0 && dataUnit[col + 32] == 0 + && dataUnit[col + 40] == 0 && dataUnit[col + 48] == 0 + && dataUnit[col + 56] == 0; } bool isZeroInRow(int[] dataUnit, int rIndex) { - return dataUnit[rIndex + 1] == 0 && dataUnit[rIndex + 2] == 0 - && dataUnit[rIndex + 3] == 0 && dataUnit[rIndex + 4] == 0 - && dataUnit[rIndex + 5] == 0 && dataUnit[rIndex + 6] == 0 - && dataUnit[rIndex + 7] == 0; + return dataUnit[rIndex + 1] == 0 && dataUnit[rIndex + 2] == 0 + && dataUnit[rIndex + 3] == 0 && dataUnit[rIndex + 4] == 0 + && dataUnit[rIndex + 5] == 0 && dataUnit[rIndex + 6] == 0 + && dataUnit[rIndex + 7] == 0; } ImageData[] loadFromByteStream() { - //TEMPORARY CODE + //TEMPORARY CODE //PORTING_FIXME - if (/+System.getProperty("dwt.internal.image.JPEGFileFormat_3.2") == null+/ true ) { - return JPEGDecoder.loadFromByteStream(inputStream, loader); - } - JPEGStartOfImage soi = new JPEGStartOfImage(inputStream); - if (!soi.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); - restartInterval = 0; + if (/+System.getProperty("dwt.internal.image.JPEGFileFormat_3.2") == null+/ true ) { + return JPEGDecoder.loadFromByteStream(inputStream, loader); + } + JPEGStartOfImage soi = new JPEGStartOfImage(inputStream); + if (!soi.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); + restartInterval = 0; - /* Process the tables preceding the frame header. */ - processTables(); + /* Process the tables preceding the frame header. */ + processTables(); - /* Start of Frame. */ - frameHeader = new JPEGFrameHeader(inputStream); - if (!frameHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); - imageWidth = frameHeader.getSamplesPerLine(); - imageHeight = frameHeader.getNumberOfLines(); - maxH = frameHeader.getMaxHFactor(); - maxV = frameHeader.getMaxVFactor(); - int mcuWidth = maxH * DCTSIZE; - int mcuHeight = maxV * DCTSIZE; - interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth; - interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight; - progressive = frameHeader.isProgressive(); - samplePrecision = frameHeader.getSamplePrecision(); - nComponents = frameHeader.getNumberOfImageComponents(); - frameComponents = frameHeader.componentParameters; - componentIds = frameHeader.componentIdentifiers; - imageComponents = new byte[][](nComponents); - if (progressive) { - // Progressive jpeg: need to keep all of the data units. - dataUnits = new int[][][](nComponents); - } else { - // Sequential jpeg: only need one data unit. - dataUnit = new int[8 * 8]; - } - for (int i = 0; i < nComponents; i++) { - int[] frameComponent = frameComponents[componentIds[i]]; - int bufferSize = frameComponent[CW] * frameComponent[CH]; - imageComponents[i] = new byte[bufferSize]; - if (progressive) { - dataUnits[i] = new int[][](bufferSize); - } - } + /* Start of Frame. */ + frameHeader = new JPEGFrameHeader(inputStream); + if (!frameHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); + imageWidth = frameHeader.getSamplesPerLine(); + imageHeight = frameHeader.getNumberOfLines(); + maxH = frameHeader.getMaxHFactor(); + maxV = frameHeader.getMaxVFactor(); + int mcuWidth = maxH * DCTSIZE; + int mcuHeight = maxV * DCTSIZE; + interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth; + interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight; + progressive = frameHeader.isProgressive(); + samplePrecision = frameHeader.getSamplePrecision(); + nComponents = frameHeader.getNumberOfImageComponents(); + frameComponents = frameHeader.componentParameters; + componentIds = frameHeader.componentIdentifiers; + imageComponents = new byte[][](nComponents); + if (progressive) { + // Progressive jpeg: need to keep all of the data units. + dataUnits = new int[][][](nComponents); + } else { + // Sequential jpeg: only need one data unit. + dataUnit = new int[8 * 8]; + } + for (int i = 0; i < nComponents; i++) { + int[] frameComponent = frameComponents[componentIds[i]]; + int bufferSize = frameComponent[CW] * frameComponent[CH]; + imageComponents[i] = new byte[bufferSize]; + if (progressive) { + dataUnits[i] = new int[][](bufferSize); + } + } - /* Process the tables preceding the scan header. */ - processTables(); + /* Process the tables preceding the scan header. */ + processTables(); - /* Start of Scan. */ - scanHeader = new JPEGScanHeader(inputStream); - if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); + /* Start of Scan. */ + scanHeader = new JPEGScanHeader(inputStream); + if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); - /* Process scan(s) and further tables until EOI. */ - int progressiveScanCount = 0; - bool done = false; - while(!done) { - resetInputBuffer(); - precedingDCs = new int[4]; - decodeScan(); - if (progressive && loader.hasListeners()) { - ImageData imageData = createImageData(); - loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, false)); - progressiveScanCount++; - } + /* Process scan(s) and further tables until EOI. */ + int progressiveScanCount = 0; + bool done = false; + while(!done) { + resetInputBuffer(); + precedingDCs = new int[4]; + decodeScan(); + if (progressive && loader.hasListeners()) { + ImageData imageData = createImageData(); + loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, false)); + progressiveScanCount++; + } - /* Unread any buffered data before looking for tables again. */ - int delta = 512 - bufferCurrentPosition - 1; - if (delta > 0) { - byte[] unreadBuffer = new byte[delta]; + /* Unread any buffered data before looking for tables again. */ + int delta = 512 - bufferCurrentPosition - 1; + if (delta > 0) { + byte[] unreadBuffer = new byte[delta]; System.arraycopy(dataBuffer, bufferCurrentPosition + 1, unreadBuffer, 0, delta); - try { - inputStream.unread(unreadBuffer); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + try { + inputStream.unread(unreadBuffer); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - /* Process the tables preceding the next scan header. */ - JPEGSegment jpegSegment = processTables(); - if (jpegSegment == null || jpegSegment.getSegmentMarker() == EOI) { - done = true; - } else { - scanHeader = new JPEGScanHeader(inputStream); - if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); - } - } + /* Process the tables preceding the next scan header. */ + JPEGSegment jpegSegment = processTables(); + if (jpegSegment == null || jpegSegment.getSegmentMarker() == EOI) { + done = true; + } else { + scanHeader = new JPEGScanHeader(inputStream); + if (!scanHeader.verify()) SWT.error(SWT.ERROR_INVALID_IMAGE); + } + } - if (progressive) { - for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) { - for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) { - for (int iComp = 0; iComp < nComponents; iComp++) { - int[] frameComponent = frameComponents[componentIds[iComp]]; - int hi = frameComponent[HI]; - int vi = frameComponent[VI]; - int compWidth = frameComponent[CW]; - for (int ivi = 0; ivi < vi; ivi++) { - for (int ihi = 0; ihi < hi; ihi++) { - int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi; - dataUnit = dataUnits[iComp][index]; - dequantize(dataUnit, iComp); - inverseDCT(dataUnit); - storeData(dataUnit, iComp, xmcu, ymcu, hi, ihi, vi, ivi); - } - } - } - } - } - dataUnits = null; // release memory - } - ImageData imageData = createImageData(); - if (progressive && loader.hasListeners()) { - loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, true)); - } - return [imageData]; + if (progressive) { + for (int ymcu = 0; ymcu < interleavedMcuRows; ymcu++) { + for (int xmcu = 0; xmcu < interleavedMcuCols; xmcu++) { + for (int iComp = 0; iComp < nComponents; iComp++) { + int[] frameComponent = frameComponents[componentIds[iComp]]; + int hi = frameComponent[HI]; + int vi = frameComponent[VI]; + int compWidth = frameComponent[CW]; + for (int ivi = 0; ivi < vi; ivi++) { + for (int ihi = 0; ihi < hi; ihi++) { + int index = (ymcu * vi + ivi) * compWidth + xmcu * hi + ihi; + dataUnit = dataUnits[iComp][index]; + dequantize(dataUnit, iComp); + inverseDCT(dataUnit); + storeData(dataUnit, iComp, xmcu, ymcu, hi, ihi, vi, ivi); + } + } + } + } + } + dataUnits = null; // release memory + } + ImageData imageData = createImageData(); + if (progressive && loader.hasListeners()) { + loader.notifyListeners(new ImageLoaderEvent(loader, imageData, progressiveScanCount, true)); + } + return [imageData]; } ImageData createImageData() { - return ImageData.internal_new( - imageWidth, - imageHeight, - nComponents * samplePrecision, - setUpPalette(), - nComponents == 1 ? 4 : 1, - decodeImageComponents(), - 0, - null, - null, - -1, - -1, - SWT.IMAGE_JPEG, - 0, - 0, - 0, - 0); + return ImageData.internal_new( + imageWidth, + imageHeight, + nComponents * samplePrecision, + setUpPalette(), + nComponents == 1 ? 4 : 1, + decodeImageComponents(), + 0, + null, + null, + -1, + -1, + SWT.IMAGE_JPEG, + 0, + 0, + 0, + 0); } int nextBit() { - if (currentBitCount != 0) { - currentBitCount--; - currentByte *= 2; - if (currentByte > 255) { - currentByte -= 256; - return 1; - } else { - return 0; - } - } - bufferCurrentPosition++; - if (bufferCurrentPosition >= 512) { - resetInputBuffer(); - bufferCurrentPosition = 0; - } - currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; - currentBitCount = 8; - byte nextByte; - if (bufferCurrentPosition == 511) { - resetInputBuffer(); - currentBitCount = 8; - nextByte = dataBuffer[0]; - } else { - nextByte = dataBuffer[bufferCurrentPosition + 1]; - } - if (currentByte == 0xFF) { - if (nextByte == 0) { - bufferCurrentPosition ++; - currentBitCount--; - currentByte *= 2; - if (currentByte > 255) { - currentByte -= 256; - return 1; - } else { - return 0; - } - } else { - if ((nextByte & 0xFF) + 0xFF00 == DNL) { - getDNL(); - return 0; - } else { - SWT.error(SWT.ERROR_INVALID_IMAGE); - return 0; - } - } - } else { - currentBitCount--; - currentByte *= 2; - if (currentByte > 255) { - currentByte -= 256; - return 1; - } else { - return 0; - } - } + if (currentBitCount != 0) { + currentBitCount--; + currentByte *= 2; + if (currentByte > 255) { + currentByte -= 256; + return 1; + } else { + return 0; + } + } + bufferCurrentPosition++; + if (bufferCurrentPosition >= 512) { + resetInputBuffer(); + bufferCurrentPosition = 0; + } + currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; + currentBitCount = 8; + byte nextByte; + if (bufferCurrentPosition == 511) { + resetInputBuffer(); + currentBitCount = 8; + nextByte = dataBuffer[0]; + } else { + nextByte = dataBuffer[bufferCurrentPosition + 1]; + } + if (currentByte == 0xFF) { + if (nextByte == 0) { + bufferCurrentPosition ++; + currentBitCount--; + currentByte *= 2; + if (currentByte > 255) { + currentByte -= 256; + return 1; + } else { + return 0; + } + } else { + if ((nextByte & 0xFF) + 0xFF00 == DNL) { + getDNL(); + return 0; + } else { + SWT.error(SWT.ERROR_INVALID_IMAGE); + return 0; + } + } + } else { + currentBitCount--; + currentByte *= 2; + if (currentByte > 255) { + currentByte -= 256; + return 1; + } else { + return 0; + } + } } void processRestartInterval() { - do { - bufferCurrentPosition++; - if (bufferCurrentPosition > 511) { - resetInputBuffer(); - bufferCurrentPosition = 0; - } - currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; - } while (currentByte != 0xFF); - while (currentByte == 0xFF) { - bufferCurrentPosition++; - if (bufferCurrentPosition > 511) { - resetInputBuffer(); - bufferCurrentPosition = 0; - } - currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; - } - if (currentByte != ((RST0 + nextRestartNumber) & 0xFF)) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - bufferCurrentPosition++; - if (bufferCurrentPosition > 511) { - resetInputBuffer(); - bufferCurrentPosition = 0; - } - currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; - currentBitCount = 8; - restartsToGo = restartInterval; - nextRestartNumber = (nextRestartNumber + 1) & 0x7; - precedingDCs = new int[4]; - eobrun = 0; + do { + bufferCurrentPosition++; + if (bufferCurrentPosition > 511) { + resetInputBuffer(); + bufferCurrentPosition = 0; + } + currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; + } while (currentByte != 0xFF); + while (currentByte == 0xFF) { + bufferCurrentPosition++; + if (bufferCurrentPosition > 511) { + resetInputBuffer(); + bufferCurrentPosition = 0; + } + currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; + } + if (currentByte != ((RST0 + nextRestartNumber) & 0xFF)) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + bufferCurrentPosition++; + if (bufferCurrentPosition > 511) { + resetInputBuffer(); + bufferCurrentPosition = 0; + } + currentByte = dataBuffer[bufferCurrentPosition] & 0xFF; + currentBitCount = 8; + restartsToGo = restartInterval; + nextRestartNumber = (nextRestartNumber + 1) & 0x7; + precedingDCs = new int[4]; + eobrun = 0; } /* Process all markers until a frame header, scan header, or EOI is found. */ JPEGSegment processTables() { - while (true) { - JPEGSegment jpegSegment = seekUnspecifiedMarker(inputStream); - if (jpegSegment == null) return null; - JPEGFrameHeader sof = new JPEGFrameHeader(jpegSegment.reference); - if (sof.verify()) { - return jpegSegment; - } - int marker = jpegSegment.getSegmentMarker(); - switch (marker) { - case SOI: // there should only be one SOI per file - SWT.error(SWT.ERROR_INVALID_IMAGE); - case EOI: - case SOS: - return jpegSegment; - case DQT: - getDQT(); - break; - case DHT: - getDHT(); - break; - case DAC: - getDAC(); - break; - case DRI: - getDRI(); - break; - case APP0: - getAPP0(); - break; - case COM: - getCOM(); - break; - default: - skipSegmentFrom(inputStream); + while (true) { + JPEGSegment jpegSegment = seekUnspecifiedMarker(inputStream); + if (jpegSegment == null) return null; + JPEGFrameHeader sof = new JPEGFrameHeader(jpegSegment.reference); + if (sof.verify()) { + return jpegSegment; + } + int marker = jpegSegment.getSegmentMarker(); + switch (marker) { + case SOI: // there should only be one SOI per file + SWT.error(SWT.ERROR_INVALID_IMAGE); + case EOI: + case SOS: + return jpegSegment; + case DQT: + getDQT(); + break; + case DHT: + getDHT(); + break; + case DAC: + getDAC(); + break; + case DRI: + getDRI(); + break; + case APP0: + getAPP0(); + break; + case COM: + getCOM(); + break; + default: + skipSegmentFrom(inputStream); - } - } + } + } } void quantizeData(int[] dataUnit, int iComp) { - int[] qTable = quantizationTables[frameComponents[componentIds[iComp]][TQI]]; - for (int i = 0; i < dataUnit.length; i++) { - int zzIndex = ZigZag8x8[i]; - int data = dataUnit[zzIndex]; - int absData = data < 0 ? 0 - data : data; - int qValue = qTable[i]; - int q2 = qValue >> 1; - absData += q2; - if (absData < qValue) { - dataUnit[zzIndex] = 0; - } else { - absData /= qValue; - if (data >= 0) { - dataUnit[zzIndex] = absData; - } else { - dataUnit[zzIndex] = 0 - absData; - } - } - } + int[] qTable = quantizationTables[frameComponents[componentIds[iComp]][TQI]]; + for (int i = 0; i < dataUnit.length; i++) { + int zzIndex = ZigZag8x8[i]; + int data = dataUnit[zzIndex]; + int absData = data < 0 ? 0 - data : data; + int qValue = qTable[i]; + int q2 = qValue >> 1; + absData += q2; + if (absData < qValue) { + dataUnit[zzIndex] = 0; + } else { + absData /= qValue; + if (data >= 0) { + dataUnit[zzIndex] = absData; + } else { + dataUnit[zzIndex] = 0 - absData; + } + } + } } int receive(int nBits) { - int v = 0; - for (int i = 0; i < nBits; i++) { - v = v * 2 + nextBit(); - } - return v; + int v = 0; + for (int i = 0; i < nBits; i++) { + v = v * 2 + nextBit(); + } + return v; } void resetInputBuffer() { - if (dataBuffer == null) { - dataBuffer = new byte[512]; - } - try { - inputStream.read(dataBuffer); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - currentBitCount = 0; - bufferCurrentPosition = -1; + if (dataBuffer == null) { + dataBuffer = new byte[512]; + } + try { + inputStream.read(dataBuffer); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + currentBitCount = 0; + bufferCurrentPosition = -1; } void resetOutputBuffer() { - if (dataBuffer == null) { - dataBuffer = new byte[512]; - } else { - try { - outputStream.write(dataBuffer, 0, bufferCurrentPosition); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - bufferCurrentPosition = 0; + if (dataBuffer == null) { + dataBuffer = new byte[512]; + } else { + try { + outputStream.write(dataBuffer, 0, bufferCurrentPosition); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + bufferCurrentPosition = 0; } static JPEGSegment seekUnspecifiedMarker(LEDataInputStream byteStream) { - byte[] byteArray = new byte[2]; - try { - while (true) { - if (byteStream.read(byteArray, 0, 1) != 1) return null; - if (byteArray[0] == cast(byte) 0xFF) { - if (byteStream.read(byteArray, 1, 1) != 1) return null; - if (byteArray[1] != cast(byte) 0xFF && byteArray[1] != 0) { - byteStream.unread(byteArray); - return new JPEGSegment(byteArray); - } - } - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return null; + byte[] byteArray = new byte[2]; + try { + while (true) { + if (byteStream.read(byteArray, 0, 1) != 1) return null; + if (byteArray[0] == cast(byte) 0xFF) { + if (byteStream.read(byteArray, 1, 1) != 1) return null; + if (byteArray[1] != cast(byte) 0xFF && byteArray[1] != 0) { + byteStream.unread(byteArray); + return new JPEGSegment(byteArray); + } + } + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return null; } PaletteData setUpPalette() { - if (nComponents == 1) { - RGB[] entries = new RGB[256]; - for (int i = 0; i < 256; i++) { - entries[i] = new RGB(i, i, i); - } - return new PaletteData(entries); - } - return new PaletteData(0xFF, 0xFF00, 0xFF0000); + if (nComponents == 1) { + RGB[] entries = new RGB[256]; + for (int i = 0; i < 256; i++) { + entries[i] = new RGB(i, i, i); + } + return new PaletteData(entries); + } + return new PaletteData(0xFF, 0xFF00, 0xFF0000); } static void skipSegmentFrom(LEDataInputStream byteStream) { - try { - byte[] byteArray = new byte[4]; - JPEGSegment jpegSegment = new JPEGSegment(byteArray); + try { + byte[] byteArray = new byte[4]; + JPEGSegment jpegSegment = new JPEGSegment(byteArray); - if (byteStream.read(byteArray) != byteArray.length) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - if (!(byteArray[0] == -1 && byteArray[1] != 0 && byteArray[1] != -1)) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - int delta = jpegSegment.getSegmentLength() - 2; - byteStream.skip(delta); - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } + if (byteStream.read(byteArray) != byteArray.length) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + if (!(byteArray[0] == -1 && byteArray[1] != 0 && byteArray[1] != -1)) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + int delta = jpegSegment.getSegmentLength() - 2; + byteStream.skip(delta); + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } } void storeData(int[] dataUnit, int iComp, int xmcu, int ymcu, int hi, int ihi, int vi, int ivi) { - byte[] compImage = imageComponents[iComp]; - int[] frameComponent = frameComponents[componentIds[iComp]]; - int compWidth = frameComponent[CW]; - int destIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE); - int srcIndex = 0; - for (int i = 0; i < DCTSIZE; i++) { - for (int col = 0; col < DCTSIZE; col++) { - int x = dataUnit[srcIndex] + 128; - if (x < 0) { - x = 0; - } else { - if (x > 255) x = 255; - } - compImage[destIndex + col] = cast(byte)x; - srcIndex++; - } - destIndex += compWidth; - } + byte[] compImage = imageComponents[iComp]; + int[] frameComponent = frameComponents[componentIds[iComp]]; + int compWidth = frameComponent[CW]; + int destIndex = ((ymcu * vi + ivi) * compWidth * DCTSIZE) + ((xmcu * hi + ihi) * DCTSIZE); + int srcIndex = 0; + for (int i = 0; i < DCTSIZE; i++) { + for (int col = 0; col < DCTSIZE; col++) { + int x = dataUnit[srcIndex] + 128; + if (x < 0) { + x = 0; + } else { + if (x > 255) x = 255; + } + compImage[destIndex + col] = cast(byte)x; + srcIndex++; + } + destIndex += compWidth; + } } void unloadIntoByteStream(ImageLoader loader) { - ImageData image = loader.data[0]; - if (!(new JPEGStartOfImage()).writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - JPEGAppn appn = new JPEGAppn([cast(byte)0xFF, cast(byte)0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]); - if (!appn.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - quantizationTables = new int[][](4); - JPEGQuantizationTable chromDQT = JPEGQuantizationTable.defaultChrominanceTable(); - chromDQT.scaleBy(encoderQFactor); - int[] jpegDQTKeys = chromDQT.getQuantizationTablesKeys(); - int[][] jpegDQTValues = chromDQT.getQuantizationTablesValues(); - for (int i = 0; i < jpegDQTKeys.length; i++) { - quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i]; - } - JPEGQuantizationTable lumDQT = JPEGQuantizationTable.defaultLuminanceTable(); - lumDQT.scaleBy(encoderQFactor); - jpegDQTKeys = lumDQT.getQuantizationTablesKeys(); - jpegDQTValues = lumDQT.getQuantizationTablesValues(); - for (int i = 0; i < jpegDQTKeys.length; i++) { - quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i]; - } - if (!lumDQT.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - if (!chromDQT.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - int frameLength, scanLength, precision; - int[][] frameParams, scanParams; - if (image.depth == 1) { - frameLength = 11; - frameParams = new int[][](1); - frameParams[0] = [1, 1, 1, 0, 0]; - scanParams = new int[][](1); - scanParams[0] = [0, 0]; - scanLength = 8; - nComponents = 1; - precision = 1; - } else { - frameLength = 17; - frameParams = new int[][](3); - frameParams[0] = [0, 2, 2, 0, 0]; - frameParams[1] = [1, 1, 1, 0, 0]; - frameParams[2] = [1, 1, 1, 0, 0]; - scanParams = new int[][](3); - scanParams[0] = [0, 0]; - scanParams[1] = [1, 1]; - scanParams[2] = [1, 1]; - scanLength = 12; - nComponents = 3; - precision = 8; - } - imageWidth = image.width; - imageHeight = image.height; - frameHeader = new JPEGFrameHeader(new byte[19]); - frameHeader.setSegmentMarker(SOF0); - frameHeader.setSegmentLength(frameLength); - frameHeader.setSamplePrecision(precision); - frameHeader.setSamplesPerLine(imageWidth); - frameHeader.setNumberOfLines(imageHeight); - frameHeader.setNumberOfImageComponents(nComponents); - frameHeader.componentParameters = frameParams; - frameHeader.componentIdentifiers = [0, 1, 2]; - frameHeader.initializeContents(); - if (!frameHeader.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - frameComponents = frameParams; - componentIds = frameHeader.componentIdentifiers; - maxH = frameHeader.getMaxHFactor(); - maxV = frameHeader.getMaxVFactor(); - int mcuWidth = maxH * DCTSIZE; - int mcuHeight = maxV * DCTSIZE; - interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth; - interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight; - acHuffmanTables = new JPEGHuffmanTable[4]; - dcHuffmanTables = new JPEGHuffmanTable[4]; - JPEGHuffmanTable[] dhtTables = [ - JPEGHuffmanTable.getDefaultDCLuminanceTable(), - JPEGHuffmanTable.getDefaultDCChrominanceTable(), - JPEGHuffmanTable.getDefaultACLuminanceTable(), - JPEGHuffmanTable.getDefaultACChrominanceTable() - ]; - for (int i = 0; i < dhtTables.length; i++) { - JPEGHuffmanTable dhtTable = dhtTables[i]; - if (!dhtTable.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - JPEGHuffmanTable[] allTables = dhtTable.getAllTables(); - for (int j = 0; j < allTables.length; j++) { - JPEGHuffmanTable huffmanTable = allTables[j]; - if (huffmanTable.getTableClass() == 0) { - dcHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable; - } else { - acHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable; - } - } - } - precedingDCs = new int[4]; - scanHeader = new JPEGScanHeader(new byte[14]); - scanHeader.setSegmentMarker(SOS); - scanHeader.setSegmentLength(scanLength); - scanHeader.setNumberOfImageComponents(nComponents); - scanHeader.setStartOfSpectralSelection(0); - scanHeader.setEndOfSpectralSelection(63); - scanHeader.componentParameters = scanParams; - scanHeader.initializeContents(); - if (!scanHeader.writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } - convertImageToYCbCr(image); - resetOutputBuffer(); - currentByte = 0; - currentBitCount = 0; - encodeScan(); - if (!(new JPEGEndOfImage()).writeToStream(outputStream)) { - SWT.error(SWT.ERROR_IO); - } + ImageData image = loader.data[0]; + if (!(new JPEGStartOfImage()).writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + JPEGAppn appn = new JPEGAppn([cast(byte)0xFF, cast(byte)0xE0, 0, 0x10, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]); + if (!appn.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + quantizationTables = new int[][](4); + JPEGQuantizationTable chromDQT = JPEGQuantizationTable.defaultChrominanceTable(); + chromDQT.scaleBy(encoderQFactor); + int[] jpegDQTKeys = chromDQT.getQuantizationTablesKeys(); + int[][] jpegDQTValues = chromDQT.getQuantizationTablesValues(); + for (int i = 0; i < jpegDQTKeys.length; i++) { + quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i]; + } + JPEGQuantizationTable lumDQT = JPEGQuantizationTable.defaultLuminanceTable(); + lumDQT.scaleBy(encoderQFactor); + jpegDQTKeys = lumDQT.getQuantizationTablesKeys(); + jpegDQTValues = lumDQT.getQuantizationTablesValues(); + for (int i = 0; i < jpegDQTKeys.length; i++) { + quantizationTables[jpegDQTKeys[i]] = jpegDQTValues[i]; + } + if (!lumDQT.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + if (!chromDQT.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + int frameLength, scanLength, precision; + int[][] frameParams, scanParams; + if (image.depth == 1) { + frameLength = 11; + frameParams = new int[][](1); + frameParams[0] = [1, 1, 1, 0, 0]; + scanParams = new int[][](1); + scanParams[0] = [0, 0]; + scanLength = 8; + nComponents = 1; + precision = 1; + } else { + frameLength = 17; + frameParams = new int[][](3); + frameParams[0] = [0, 2, 2, 0, 0]; + frameParams[1] = [1, 1, 1, 0, 0]; + frameParams[2] = [1, 1, 1, 0, 0]; + scanParams = new int[][](3); + scanParams[0] = [0, 0]; + scanParams[1] = [1, 1]; + scanParams[2] = [1, 1]; + scanLength = 12; + nComponents = 3; + precision = 8; + } + imageWidth = image.width; + imageHeight = image.height; + frameHeader = new JPEGFrameHeader(new byte[19]); + frameHeader.setSegmentMarker(SOF0); + frameHeader.setSegmentLength(frameLength); + frameHeader.setSamplePrecision(precision); + frameHeader.setSamplesPerLine(imageWidth); + frameHeader.setNumberOfLines(imageHeight); + frameHeader.setNumberOfImageComponents(nComponents); + frameHeader.componentParameters = frameParams; + frameHeader.componentIdentifiers = [0, 1, 2]; + frameHeader.initializeContents(); + if (!frameHeader.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + frameComponents = frameParams; + componentIds = frameHeader.componentIdentifiers; + maxH = frameHeader.getMaxHFactor(); + maxV = frameHeader.getMaxVFactor(); + int mcuWidth = maxH * DCTSIZE; + int mcuHeight = maxV * DCTSIZE; + interleavedMcuCols = (imageWidth + mcuWidth - 1) / mcuWidth; + interleavedMcuRows = (imageHeight + mcuHeight - 1) / mcuHeight; + acHuffmanTables = new JPEGHuffmanTable[4]; + dcHuffmanTables = new JPEGHuffmanTable[4]; + JPEGHuffmanTable[] dhtTables = [ + JPEGHuffmanTable.getDefaultDCLuminanceTable(), + JPEGHuffmanTable.getDefaultDCChrominanceTable(), + JPEGHuffmanTable.getDefaultACLuminanceTable(), + JPEGHuffmanTable.getDefaultACChrominanceTable() + ]; + for (int i = 0; i < dhtTables.length; i++) { + JPEGHuffmanTable dhtTable = dhtTables[i]; + if (!dhtTable.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + JPEGHuffmanTable[] allTables = dhtTable.getAllTables(); + for (int j = 0; j < allTables.length; j++) { + JPEGHuffmanTable huffmanTable = allTables[j]; + if (huffmanTable.getTableClass() == 0) { + dcHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable; + } else { + acHuffmanTables[huffmanTable.getTableIdentifier()] = huffmanTable; + } + } + } + precedingDCs = new int[4]; + scanHeader = new JPEGScanHeader(new byte[14]); + scanHeader.setSegmentMarker(SOS); + scanHeader.setSegmentLength(scanLength); + scanHeader.setNumberOfImageComponents(nComponents); + scanHeader.setStartOfSpectralSelection(0); + scanHeader.setEndOfSpectralSelection(63); + scanHeader.componentParameters = scanParams; + scanHeader.initializeContents(); + if (!scanHeader.writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } + convertImageToYCbCr(image); + resetOutputBuffer(); + currentByte = 0; + currentBitCount = 0; + encodeScan(); + if (!(new JPEGEndOfImage()).writeToStream(outputStream)) { + SWT.error(SWT.ERROR_IO); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGFixedSizeSegment.d --- a/dwt/internal/image/JPEGFixedSizeSegment.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGFixedSizeSegment.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -20,30 +20,30 @@ abstract class JPEGFixedSizeSegment : JPEGSegment { - public this() { - reference = new byte[fixedSize()]; - setSegmentMarker(signature()); - } + public this() { + reference = new byte[fixedSize()]; + setSegmentMarker(signature()); + } - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - reference = new byte[fixedSize()]; - try { - byteStream.read(reference); - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + public this(LEDataInputStream byteStream) { + reference = new byte[fixedSize()]; + try { + byteStream.read(reference); + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - abstract public int fixedSize(); + abstract public int fixedSize(); - public int getSegmentLength() { - return fixedSize() - 2; - } + public int getSegmentLength() { + return fixedSize() - 2; + } - public void setSegmentLength(int length) { - } + public void setSegmentLength(int length) { + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGFrameHeader.d --- a/dwt/internal/image/JPEGFrameHeader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGFrameHeader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -17,201 +17,201 @@ import dwt.internal.image.LEDataInputStream; final class JPEGFrameHeader : JPEGVariableSizeSegment { - int maxVFactor; - int maxHFactor; - public int[] componentIdentifiers; - public int[][] componentParameters; + int maxVFactor; + int maxHFactor; + public int[] componentIdentifiers; + public int[][] componentParameters; - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - super(byteStream); - initializeComponentParameters(); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + initializeComponentParameters(); + } - public int getSamplePrecision() { - return reference[4] & 0xFF; - } + public int getSamplePrecision() { + return reference[4] & 0xFF; + } - public int getNumberOfLines() { - return (reference[5] & 0xFF) << 8 | (reference[6] & 0xFF); - } + public int getNumberOfLines() { + return (reference[5] & 0xFF) << 8 | (reference[6] & 0xFF); + } - public int getSamplesPerLine() { - return (reference[7] & 0xFF) << 8 | (reference[8] & 0xFF); - } + public int getSamplesPerLine() { + return (reference[7] & 0xFF) << 8 | (reference[8] & 0xFF); + } - public int getNumberOfImageComponents() { - return reference[9] & 0xFF; - } + public int getNumberOfImageComponents() { + return reference[9] & 0xFF; + } - public void setSamplePrecision(int precision) { - reference[4] = cast(byte)(precision & 0xFF); - } + public void setSamplePrecision(int precision) { + reference[4] = cast(byte)(precision & 0xFF); + } - public void setNumberOfLines(int anInteger) { - reference[5] = cast(byte)((anInteger & 0xFF00) >> 8); - reference[6] = cast(byte)(anInteger & 0xFF); - } + public void setNumberOfLines(int anInteger) { + reference[5] = cast(byte)((anInteger & 0xFF00) >> 8); + reference[6] = cast(byte)(anInteger & 0xFF); + } - public void setSamplesPerLine(int samples) { - reference[7] = cast(byte)((samples & 0xFF00) >> 8); - reference[8] = cast(byte)(samples & 0xFF); - } + public void setSamplesPerLine(int samples) { + reference[7] = cast(byte)((samples & 0xFF00) >> 8); + reference[8] = cast(byte)(samples & 0xFF); + } - public void setNumberOfImageComponents(int anInteger) { - reference[9] = cast(byte)(anInteger & 0xFF); - } + public void setNumberOfImageComponents(int anInteger) { + reference[9] = cast(byte)(anInteger & 0xFF); + } - public int getMaxHFactor() { - return maxHFactor; - } + public int getMaxHFactor() { + return maxHFactor; + } - public int getMaxVFactor() { - return maxVFactor; - } + public int getMaxVFactor() { + return maxVFactor; + } - public void setMaxHFactor(int anInteger) { - maxHFactor = anInteger; - } + public void setMaxHFactor(int anInteger) { + maxHFactor = anInteger; + } - public void setMaxVFactor(int anInteger) { - maxVFactor = anInteger; - } + public void setMaxVFactor(int anInteger) { + maxVFactor = anInteger; + } - /* Used when decoding. */ - void initializeComponentParameters() { - int nf = getNumberOfImageComponents(); - componentIdentifiers = new int[nf]; - int[][] compSpecParams; - int hmax = 1; - int vmax = 1; - for (int i = 0; i < nf; i++) { - int ofs = i * 3 + 10; - int ci = reference[ofs] & 0xFF; - componentIdentifiers[i] = ci; - int hi = (reference[ofs + 1] & 0xFF) >> 4; - int vi = reference[ofs + 1] & 0xF; - int tqi = reference[ofs + 2] & 0xFF; - if (hi > hmax) { - hmax = hi; - } - if (vi > vmax) { - vmax = vi; - } - int[] compParam = new int[5]; - compParam[0] = tqi; - compParam[1] = hi; - compParam[2] = vi; - if (compSpecParams.length <= ci) { + /* Used when decoding. */ + void initializeComponentParameters() { + int nf = getNumberOfImageComponents(); + componentIdentifiers = new int[nf]; + int[][] compSpecParams; + int hmax = 1; + int vmax = 1; + for (int i = 0; i < nf; i++) { + int ofs = i * 3 + 10; + int ci = reference[ofs] & 0xFF; + componentIdentifiers[i] = ci; + int hi = (reference[ofs + 1] & 0xFF) >> 4; + int vi = reference[ofs + 1] & 0xF; + int tqi = reference[ofs + 2] & 0xFF; + if (hi > hmax) { + hmax = hi; + } + if (vi > vmax) { + vmax = vi; + } + int[] compParam = new int[5]; + compParam[0] = tqi; + compParam[1] = hi; + compParam[2] = vi; + if (compSpecParams.length <= ci) { int[][] newParams = new int[][](ci + 1); System.arraycopy(compSpecParams, 0, newParams, 0, compSpecParams.length); compSpecParams = newParams; - } - compSpecParams[ci] = compParam; - } - int x = getSamplesPerLine(); - int y = getNumberOfLines(); - int[] multiples = [ 8, 16, 24, 32 ]; - for (int i = 0; i < nf; i++) { - int[] compParam = compSpecParams[componentIdentifiers[i]]; - int hi = compParam[1]; - int vi = compParam[2]; - int compWidth = (x * hi + hmax - 1) / hmax; - int compHeight = (y * vi + vmax - 1) / vmax; - int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]); - int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]); - compParam[3] = dsWidth; - compParam[4] = dsHeight; - } - setMaxHFactor(hmax); - setMaxVFactor(vmax); - componentParameters = compSpecParams; - } + } + compSpecParams[ci] = compParam; + } + int x = getSamplesPerLine(); + int y = getNumberOfLines(); + int[] multiples = [ 8, 16, 24, 32 ]; + for (int i = 0; i < nf; i++) { + int[] compParam = compSpecParams[componentIdentifiers[i]]; + int hi = compParam[1]; + int vi = compParam[2]; + int compWidth = (x * hi + hmax - 1) / hmax; + int compHeight = (y * vi + vmax - 1) / vmax; + int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]); + int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]); + compParam[3] = dsWidth; + compParam[4] = dsHeight; + } + setMaxHFactor(hmax); + setMaxVFactor(vmax); + componentParameters = compSpecParams; + } - /* Used when encoding. */ - public void initializeContents() { - int nf = getNumberOfImageComponents(); - if (nf == 0 || nf != componentParameters.length) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - int hmax = 0; - int vmax = 0; - int[][] compSpecParams = componentParameters; - for (int i = 0; i < nf; i++) { - int ofs = i * 3 + 10; - int[] compParam = compSpecParams[componentIdentifiers[i]]; - int hi = compParam[1]; - int vi = compParam[2]; - if (hi * vi > 4) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - reference[ofs] = cast(byte)(i + 1); - reference[ofs + 1] = cast(byte)(hi * 16 + vi); - reference[ofs + 2] = cast(byte)(compParam[0]); - if (hi > hmax) hmax = hi; - if (vi > vmax) vmax = vi; - } - int x = getSamplesPerLine(); - int y = getNumberOfLines(); - int[] multiples = [8, 16, 24, 32]; - for (int i = 0; i < nf; i++) { - int[] compParam = compSpecParams[componentIdentifiers[i]]; - int hi = compParam[1]; - int vi = compParam[2]; - int compWidth = (x * hi + hmax - 1) / hmax; - int compHeight = (y * vi + vmax - 1) / vmax; - int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]); - int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]); - compParam[3] = dsWidth; - compParam[4] = dsHeight; - } - setMaxHFactor(hmax); - setMaxVFactor(vmax); - } + /* Used when encoding. */ + public void initializeContents() { + int nf = getNumberOfImageComponents(); + if (nf == 0 || nf != componentParameters.length) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + int hmax = 0; + int vmax = 0; + int[][] compSpecParams = componentParameters; + for (int i = 0; i < nf; i++) { + int ofs = i * 3 + 10; + int[] compParam = compSpecParams[componentIdentifiers[i]]; + int hi = compParam[1]; + int vi = compParam[2]; + if (hi * vi > 4) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + reference[ofs] = cast(byte)(i + 1); + reference[ofs + 1] = cast(byte)(hi * 16 + vi); + reference[ofs + 2] = cast(byte)(compParam[0]); + if (hi > hmax) hmax = hi; + if (vi > vmax) vmax = vi; + } + int x = getSamplesPerLine(); + int y = getNumberOfLines(); + int[] multiples = [8, 16, 24, 32]; + for (int i = 0; i < nf; i++) { + int[] compParam = compSpecParams[componentIdentifiers[i]]; + int hi = compParam[1]; + int vi = compParam[2]; + int compWidth = (x * hi + hmax - 1) / hmax; + int compHeight = (y * vi + vmax - 1) / vmax; + int dsWidth = roundUpToMultiple(compWidth, multiples[hi - 1]); + int dsHeight = roundUpToMultiple(compHeight, multiples[vi - 1]); + compParam[3] = dsWidth; + compParam[4] = dsHeight; + } + setMaxHFactor(hmax); + setMaxVFactor(vmax); + } - int roundUpToMultiple(int anInteger, int mInteger) { - int a = anInteger + mInteger - 1; - return a - (a % mInteger); - } + int roundUpToMultiple(int anInteger, int mInteger) { + int a = anInteger + mInteger - 1; + return a - (a % mInteger); + } - /* - * Verify the information contained in the receiver is correct. - * Answer true if the header contains a valid marker. Otherwise, - * answer false. Valid Start Of Frame markers are: - * SOF_0 - Baseline DCT, Huffman coding - * SOF_1 - Extended sequential DCT, Huffman coding - * SOF_2 - Progressive DCT, Huffman coding - * SOF_3 - Lossless (sequential), Huffman coding - * SOF_5 - Differential sequential, Huffman coding - * SOF_6 - Differential progressive, Huffman coding - * SOF_7 - Differential lossless, Huffman coding - * SOF_9 - Extended sequential DCT, arithmetic coding - * SOF_10 - Progressive DCT, arithmetic coding - * SOF_11 - Lossless (sequential), arithmetic coding - * SOF_13 - Differential sequential, arithmetic coding - * SOF_14 - Differential progressive, arithmetic coding - * SOF_15 - Differential lossless, arithmetic coding - */ - public bool verify() { - int marker = getSegmentMarker(); - return (marker >= JPEGFileFormat.SOF0 && marker <= JPEGFileFormat.SOF3) || - (marker >= JPEGFileFormat.SOF5 && marker <= JPEGFileFormat.SOF7) || - (marker >= JPEGFileFormat.SOF9 && marker <= JPEGFileFormat.SOF11) || - (marker >= JPEGFileFormat.SOF13 && marker <= JPEGFileFormat.SOF15); - } + /* + * Verify the information contained in the receiver is correct. + * Answer true if the header contains a valid marker. Otherwise, + * answer false. Valid Start Of Frame markers are: + * SOF_0 - Baseline DCT, Huffman coding + * SOF_1 - Extended sequential DCT, Huffman coding + * SOF_2 - Progressive DCT, Huffman coding + * SOF_3 - Lossless (sequential), Huffman coding + * SOF_5 - Differential sequential, Huffman coding + * SOF_6 - Differential progressive, Huffman coding + * SOF_7 - Differential lossless, Huffman coding + * SOF_9 - Extended sequential DCT, arithmetic coding + * SOF_10 - Progressive DCT, arithmetic coding + * SOF_11 - Lossless (sequential), arithmetic coding + * SOF_13 - Differential sequential, arithmetic coding + * SOF_14 - Differential progressive, arithmetic coding + * SOF_15 - Differential lossless, arithmetic coding + */ + public bool verify() { + int marker = getSegmentMarker(); + return (marker >= JPEGFileFormat.SOF0 && marker <= JPEGFileFormat.SOF3) || + (marker >= JPEGFileFormat.SOF5 && marker <= JPEGFileFormat.SOF7) || + (marker >= JPEGFileFormat.SOF9 && marker <= JPEGFileFormat.SOF11) || + (marker >= JPEGFileFormat.SOF13 && marker <= JPEGFileFormat.SOF15); + } - public bool isProgressive() { - int marker = getSegmentMarker(); - return marker == JPEGFileFormat.SOF2 - || marker == JPEGFileFormat.SOF6 - || marker == JPEGFileFormat.SOF10 - || marker == JPEGFileFormat.SOF14; - } + public bool isProgressive() { + int marker = getSegmentMarker(); + return marker == JPEGFileFormat.SOF2 + || marker == JPEGFileFormat.SOF6 + || marker == JPEGFileFormat.SOF10 + || marker == JPEGFileFormat.SOF14; + } - public bool isArithmeticCoding() { - return getSegmentMarker() >= JPEGFileFormat.SOF9; - } + public bool isArithmeticCoding() { + return getSegmentMarker() >= JPEGFileFormat.SOF9; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGHuffmanTable.d --- a/dwt/internal/image/JPEGHuffmanTable.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGHuffmanTable.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -18,251 +18,251 @@ /** * JPEGHuffmanTable class actually represents two types of object: * 1) A DHT (Define Huffman Tables) segment, which may represent - * as many as 4 Huffman tables. In this case, the tables are - * stored in the allTables array. + * as many as 4 Huffman tables. In this case, the tables are + * stored in the allTables array. * 2) A single Huffman table. In this case, the allTables array - * will be null. + * will be null. * The 'reference' field is stored in both types of object, but * 'initialize' is only called if the object represents a DHT. */ final class JPEGHuffmanTable : JPEGVariableSizeSegment { - JPEGHuffmanTable[] allTables; - int tableClass; - int tableIdentifier; - int[] dhMaxCodes; - int[] dhMinCodes; - int[] dhValPtrs; - int[] dhValues; - int[] ehCodes; - byte[] ehCodeLengths; - static byte[] DCLuminanceTable = [ - cast(byte)255, cast(byte)196, 0, 31, 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 - ]; - static byte[] DCChrominanceTable = [ - cast(byte)255, cast(byte)196, 0, 31, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 - ]; - static byte[] ACLuminanceTable = [ - cast(byte)255, cast(byte)196, 0, cast(byte)181, 16, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125, - 1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20, - 50, cast(byte)129, cast(byte)145, cast(byte)161, 8, 35, 66, cast(byte)177, cast(byte)193, 21, 82, cast(byte)209, cast(byte)240, 36, 51, 98, - 114, cast(byte)130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53, - 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, - 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, - 119, 120, 121, 122, cast(byte)131, cast(byte)132, cast(byte)133, cast(byte)134, cast(byte)135, cast(byte)136, cast(byte)137, cast(byte)138, cast(byte)146, cast(byte)147, cast(byte)148, - cast(byte)149, cast(byte)150, cast(byte)151, cast(byte)152, cast(byte)153, cast(byte)154, cast(byte)162, cast(byte)163, cast(byte)164, cast(byte)165, cast(byte)166, cast(byte)167, cast(byte)168, cast(byte)169, cast(byte)170, - cast(byte)178, cast(byte)179, cast(byte)180, cast(byte)181, cast(byte)182, cast(byte)183, cast(byte)184, cast(byte)185, cast(byte)186, cast(byte)194, cast(byte)195, cast(byte)196, cast(byte)197, cast(byte)198, cast(byte)199, - cast(byte)200, cast(byte)201, cast(byte)202, cast(byte)210, cast(byte)211, cast(byte)212, cast(byte)213, cast(byte)214, cast(byte)215, cast(byte)216, cast(byte)217, cast(byte)218, cast(byte)225, cast(byte)226, cast(byte)227, - cast(byte)228, cast(byte)229, cast(byte)230, cast(byte)231, cast(byte)232, cast(byte)233, cast(byte)234, cast(byte)241, cast(byte)242, cast(byte)243, cast(byte)244, cast(byte)245, cast(byte)246, cast(byte)247, cast(byte)248, - cast(byte)249, cast(byte)250 - ]; - static byte[] ACChrominanceTable = [ - cast(byte)255, cast(byte)196, 0, cast(byte)181, 17, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, - 1, 2, 119, 0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34, - 50, cast(byte)129, 8, 20, 66, cast(byte)145, cast(byte)161, cast(byte)177, cast(byte)193, 9, 35, - 51, 82, cast(byte)240, 21, 98, 114, cast(byte)209, 10, 22, 36, 52, cast(byte)225, 37, - cast(byte)241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67, - 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, - 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, cast(byte)130, - cast(byte)131, cast(byte)132, cast(byte)133, cast(byte)134, cast(byte)135, cast(byte)136, cast(byte)137, - cast(byte)138, cast(byte)146, cast(byte)147, cast(byte)148, cast(byte)149, cast(byte)150, cast(byte)151, - cast(byte)152, cast(byte)153, cast(byte)154, cast(byte)162, cast(byte)163, cast(byte)164, cast(byte)165, - cast(byte)166, cast(byte)167, cast(byte)168, cast(byte)169, cast(byte)170, cast(byte)178, cast(byte)179, - cast(byte)180, cast(byte)181, cast(byte)182, cast(byte)183, cast(byte)184, cast(byte)185, cast(byte)186, - cast(byte)194, cast(byte)195, cast(byte)196, cast(byte)197, cast(byte)198, cast(byte)199, cast(byte)200, - cast(byte)201, cast(byte)202, cast(byte)210, cast(byte)211, cast(byte)212, cast(byte)213, cast(byte)214, - cast(byte)215, cast(byte)216, cast(byte)217, cast(byte)218, cast(byte)226, cast(byte)227, cast(byte)228, - cast(byte)229, cast(byte)230, cast(byte)231, cast(byte)232, cast(byte)233, cast(byte)234, cast(byte)242, - cast(byte)243, cast(byte)244, cast(byte)245, cast(byte)246, cast(byte)247, cast(byte)248, cast(byte)249, - cast(byte)250 - ]; + JPEGHuffmanTable[] allTables; + int tableClass; + int tableIdentifier; + int[] dhMaxCodes; + int[] dhMinCodes; + int[] dhValPtrs; + int[] dhValues; + int[] ehCodes; + byte[] ehCodeLengths; + static byte[] DCLuminanceTable = [ + cast(byte)255, cast(byte)196, 0, 31, 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 + ]; + static byte[] DCChrominanceTable = [ + cast(byte)255, cast(byte)196, 0, 31, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 + ]; + static byte[] ACLuminanceTable = [ + cast(byte)255, cast(byte)196, 0, cast(byte)181, 16, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125, + 1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20, + 50, cast(byte)129, cast(byte)145, cast(byte)161, 8, 35, 66, cast(byte)177, cast(byte)193, 21, 82, cast(byte)209, cast(byte)240, 36, 51, 98, + 114, cast(byte)130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53, + 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, + 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, + 119, 120, 121, 122, cast(byte)131, cast(byte)132, cast(byte)133, cast(byte)134, cast(byte)135, cast(byte)136, cast(byte)137, cast(byte)138, cast(byte)146, cast(byte)147, cast(byte)148, + cast(byte)149, cast(byte)150, cast(byte)151, cast(byte)152, cast(byte)153, cast(byte)154, cast(byte)162, cast(byte)163, cast(byte)164, cast(byte)165, cast(byte)166, cast(byte)167, cast(byte)168, cast(byte)169, cast(byte)170, + cast(byte)178, cast(byte)179, cast(byte)180, cast(byte)181, cast(byte)182, cast(byte)183, cast(byte)184, cast(byte)185, cast(byte)186, cast(byte)194, cast(byte)195, cast(byte)196, cast(byte)197, cast(byte)198, cast(byte)199, + cast(byte)200, cast(byte)201, cast(byte)202, cast(byte)210, cast(byte)211, cast(byte)212, cast(byte)213, cast(byte)214, cast(byte)215, cast(byte)216, cast(byte)217, cast(byte)218, cast(byte)225, cast(byte)226, cast(byte)227, + cast(byte)228, cast(byte)229, cast(byte)230, cast(byte)231, cast(byte)232, cast(byte)233, cast(byte)234, cast(byte)241, cast(byte)242, cast(byte)243, cast(byte)244, cast(byte)245, cast(byte)246, cast(byte)247, cast(byte)248, + cast(byte)249, cast(byte)250 + ]; + static byte[] ACChrominanceTable = [ + cast(byte)255, cast(byte)196, 0, cast(byte)181, 17, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, + 1, 2, 119, 0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34, + 50, cast(byte)129, 8, 20, 66, cast(byte)145, cast(byte)161, cast(byte)177, cast(byte)193, 9, 35, + 51, 82, cast(byte)240, 21, 98, 114, cast(byte)209, 10, 22, 36, 52, cast(byte)225, 37, + cast(byte)241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67, + 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, + 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, cast(byte)130, + cast(byte)131, cast(byte)132, cast(byte)133, cast(byte)134, cast(byte)135, cast(byte)136, cast(byte)137, + cast(byte)138, cast(byte)146, cast(byte)147, cast(byte)148, cast(byte)149, cast(byte)150, cast(byte)151, + cast(byte)152, cast(byte)153, cast(byte)154, cast(byte)162, cast(byte)163, cast(byte)164, cast(byte)165, + cast(byte)166, cast(byte)167, cast(byte)168, cast(byte)169, cast(byte)170, cast(byte)178, cast(byte)179, + cast(byte)180, cast(byte)181, cast(byte)182, cast(byte)183, cast(byte)184, cast(byte)185, cast(byte)186, + cast(byte)194, cast(byte)195, cast(byte)196, cast(byte)197, cast(byte)198, cast(byte)199, cast(byte)200, + cast(byte)201, cast(byte)202, cast(byte)210, cast(byte)211, cast(byte)212, cast(byte)213, cast(byte)214, + cast(byte)215, cast(byte)216, cast(byte)217, cast(byte)218, cast(byte)226, cast(byte)227, cast(byte)228, + cast(byte)229, cast(byte)230, cast(byte)231, cast(byte)232, cast(byte)233, cast(byte)234, cast(byte)242, + cast(byte)243, cast(byte)244, cast(byte)245, cast(byte)246, cast(byte)247, cast(byte)248, cast(byte)249, + cast(byte)250 + ]; public this(byte[] reference) { - super(reference); + super(reference); } public this(LEDataInputStream byteStream) { - super(byteStream); - initialize(); + super(byteStream); + initialize(); } public JPEGHuffmanTable[] getAllTables() { - return allTables; + return allTables; } public static JPEGHuffmanTable getDefaultACChrominanceTable() { - JPEGHuffmanTable result = new JPEGHuffmanTable(ACChrominanceTable); - result.initialize(); - return result; + JPEGHuffmanTable result = new JPEGHuffmanTable(ACChrominanceTable); + result.initialize(); + return result; } public static JPEGHuffmanTable getDefaultACLuminanceTable() { - JPEGHuffmanTable result = new JPEGHuffmanTable(ACLuminanceTable); - result.initialize(); - return result; + JPEGHuffmanTable result = new JPEGHuffmanTable(ACLuminanceTable); + result.initialize(); + return result; } public static JPEGHuffmanTable getDefaultDCChrominanceTable() { - JPEGHuffmanTable result = new JPEGHuffmanTable(DCChrominanceTable); - result.initialize(); - return result; + JPEGHuffmanTable result = new JPEGHuffmanTable(DCChrominanceTable); + result.initialize(); + return result; } public static JPEGHuffmanTable getDefaultDCLuminanceTable() { - JPEGHuffmanTable result = new JPEGHuffmanTable(DCLuminanceTable); - result.initialize(); - return result; + JPEGHuffmanTable result = new JPEGHuffmanTable(DCLuminanceTable); + result.initialize(); + return result; } public int[] getDhMaxCodes() { - return dhMaxCodes; + return dhMaxCodes; } public int[] getDhMinCodes() { - return dhMinCodes; + return dhMinCodes; } public int[] getDhValPtrs() { - return dhValPtrs; + return dhValPtrs; } public int[] getDhValues() { - return dhValues; + return dhValues; } public int getTableClass() { - return tableClass; + return tableClass; } public int getTableIdentifier() { - return tableIdentifier; + return tableIdentifier; } void initialize() { - int totalLength = getSegmentLength() - 2; - int ofs = 4; - int[] bits = new int[16]; - JPEGHuffmanTable[] huffTables = new JPEGHuffmanTable[8]; // maximum is 4 AC + 4 DC - int huffTableCount = 0; - while (totalLength > 0) { - int tc = (reference[ofs] & 0xFF) >> 4; // table class: AC (1) or DC (0) - int tid = reference[ofs] & 0xF; // table id: 0-1 baseline, 0-3 prog/ext - ofs++; + int totalLength = getSegmentLength() - 2; + int ofs = 4; + int[] bits = new int[16]; + JPEGHuffmanTable[] huffTables = new JPEGHuffmanTable[8]; // maximum is 4 AC + 4 DC + int huffTableCount = 0; + while (totalLength > 0) { + int tc = (reference[ofs] & 0xFF) >> 4; // table class: AC (1) or DC (0) + int tid = reference[ofs] & 0xF; // table id: 0-1 baseline, 0-3 prog/ext + ofs++; - /* Read the 16 count bytes and add them together to get the table size. */ - int count = 0; - for (int i = 0; i < bits.length; i++) { - int bCount = reference[ofs + i] & 0xFF; - bits[i] = bCount; - count += bCount; - } - ofs += 16; - totalLength -= 17; + /* Read the 16 count bytes and add them together to get the table size. */ + int count = 0; + for (int i = 0; i < bits.length; i++) { + int bCount = reference[ofs + i] & 0xFF; + bits[i] = bCount; + count += bCount; + } + ofs += 16; + totalLength -= 17; - /* Read the table. */ - int[] huffVals = new int[count]; - for (int i = 0; i < count; i++) { - huffVals[i] = reference[ofs + i] & 0xFF; - } - ofs += count; - totalLength -= count; + /* Read the table. */ + int[] huffVals = new int[count]; + for (int i = 0; i < count; i++) { + huffVals[i] = reference[ofs + i] & 0xFF; + } + ofs += count; + totalLength -= count; - /* Calculate the lengths. */ - int[] huffCodeLengths = new int[50]; // start with 50 and increment as needed - int huffCodeLengthsIndex = 0; - for (int i = 0; i < 16; i++) { - for (int j = 0; j < bits[i]; j++) { - if (huffCodeLengthsIndex >= huffCodeLengths.length) { - int[] newHuffCodeLengths = new int[huffCodeLengths.length + 50]; + /* Calculate the lengths. */ + int[] huffCodeLengths = new int[50]; // start with 50 and increment as needed + int huffCodeLengthsIndex = 0; + for (int i = 0; i < 16; i++) { + for (int j = 0; j < bits[i]; j++) { + if (huffCodeLengthsIndex >= huffCodeLengths.length) { + int[] newHuffCodeLengths = new int[huffCodeLengths.length + 50]; System.arraycopy(huffCodeLengths, 0, newHuffCodeLengths, 0, huffCodeLengths.length); - huffCodeLengths = newHuffCodeLengths; - } - huffCodeLengths[huffCodeLengthsIndex] = i + 1; - huffCodeLengthsIndex++; - } - } + huffCodeLengths = newHuffCodeLengths; + } + huffCodeLengths[huffCodeLengthsIndex] = i + 1; + huffCodeLengthsIndex++; + } + } - /* Truncate huffCodeLengths to the correct size. */ - if (huffCodeLengthsIndex < huffCodeLengths.length) { - int[] newHuffCodeLengths = new int[huffCodeLengthsIndex]; + /* Truncate huffCodeLengths to the correct size. */ + if (huffCodeLengthsIndex < huffCodeLengths.length) { + int[] newHuffCodeLengths = new int[huffCodeLengthsIndex]; System.arraycopy(huffCodeLengths, 0, newHuffCodeLengths, 0, huffCodeLengthsIndex); - huffCodeLengths = newHuffCodeLengths; - } + huffCodeLengths = newHuffCodeLengths; + } - /* Calculate the Huffman codes. */ - int[] huffCodes = new int[50]; // start with 50 and increment as needed - int huffCodesIndex = 0; - int k = 1; - int code = 0; - int si = huffCodeLengths[0]; - int p = 0; - while (p < huffCodeLengthsIndex) { - while ((p < huffCodeLengthsIndex) && (huffCodeLengths[p] == si)) { - if (huffCodesIndex >= huffCodes.length) { - int[] newHuffCodes = new int[huffCodes.length + 50]; + /* Calculate the Huffman codes. */ + int[] huffCodes = new int[50]; // start with 50 and increment as needed + int huffCodesIndex = 0; + int k = 1; + int code = 0; + int si = huffCodeLengths[0]; + int p = 0; + while (p < huffCodeLengthsIndex) { + while ((p < huffCodeLengthsIndex) && (huffCodeLengths[p] == si)) { + if (huffCodesIndex >= huffCodes.length) { + int[] newHuffCodes = new int[huffCodes.length + 50]; System.arraycopy(huffCodes, 0, newHuffCodes, 0, huffCodes.length); - huffCodes = newHuffCodes; - } - huffCodes[huffCodesIndex] = code; - huffCodesIndex++; - code++; - p++; - } - code *= 2; - si++; - } + huffCodes = newHuffCodes; + } + huffCodes[huffCodesIndex] = code; + huffCodesIndex++; + code++; + p++; + } + code *= 2; + si++; + } - /* Truncate huffCodes to the correct size. */ - if (huffCodesIndex < huffCodes.length) { - int[] newHuffCodes = new int[huffCodesIndex]; + /* Truncate huffCodes to the correct size. */ + if (huffCodesIndex < huffCodes.length) { + int[] newHuffCodes = new int[huffCodesIndex]; System.arraycopy(huffCodes, 0, newHuffCodes, 0, huffCodesIndex); - huffCodes = newHuffCodes; - } + huffCodes = newHuffCodes; + } - /* Calculate the maximum and minimum codes */ - k = 0; - int[] maxCodes = new int[16]; - int[] minCodes = new int[16]; - int[] valPtrs = new int[16]; - for (int i = 0; i < 16; i++) { - int bSize = bits[i]; - if (bSize == 0) { - maxCodes[i] = -1; - } else { - valPtrs[i] = k; - minCodes[i] = huffCodes[k]; - k += bSize; - maxCodes[i] = huffCodes[k - 1]; - } - } + /* Calculate the maximum and minimum codes */ + k = 0; + int[] maxCodes = new int[16]; + int[] minCodes = new int[16]; + int[] valPtrs = new int[16]; + for (int i = 0; i < 16; i++) { + int bSize = bits[i]; + if (bSize == 0) { + maxCodes[i] = -1; + } else { + valPtrs[i] = k; + minCodes[i] = huffCodes[k]; + k += bSize; + maxCodes[i] = huffCodes[k - 1]; + } + } - /* Calculate the eHuffman codes and lengths. */ - int[] eHuffCodes = new int[256]; - byte[] eHuffSize = new byte[256]; - for (int i = 0; i < huffCodesIndex; i++) { - eHuffCodes[huffVals[i]] = huffCodes[i]; - eHuffSize[huffVals[i]] = cast(byte)huffCodeLengths[i]; - } + /* Calculate the eHuffman codes and lengths. */ + int[] eHuffCodes = new int[256]; + byte[] eHuffSize = new byte[256]; + for (int i = 0; i < huffCodesIndex; i++) { + eHuffCodes[huffVals[i]] = huffCodes[i]; + eHuffSize[huffVals[i]] = cast(byte)huffCodeLengths[i]; + } - /* Create the new JPEGHuffmanTable and add it to the allTables array. */ - JPEGHuffmanTable dhtTable = new JPEGHuffmanTable(reference); - dhtTable.tableClass = tc; - dhtTable.tableIdentifier = tid; - dhtTable.dhValues = huffVals; - dhtTable.dhMinCodes = minCodes; - dhtTable.dhMaxCodes = maxCodes; - dhtTable.dhValPtrs = valPtrs; - dhtTable.ehCodes = eHuffCodes; - dhtTable.ehCodeLengths = eHuffSize; - huffTables[huffTableCount] = dhtTable; - huffTableCount++; - } - allTables = new JPEGHuffmanTable[huffTableCount]; + /* Create the new JPEGHuffmanTable and add it to the allTables array. */ + JPEGHuffmanTable dhtTable = new JPEGHuffmanTable(reference); + dhtTable.tableClass = tc; + dhtTable.tableIdentifier = tid; + dhtTable.dhValues = huffVals; + dhtTable.dhMinCodes = minCodes; + dhtTable.dhMaxCodes = maxCodes; + dhtTable.dhValPtrs = valPtrs; + dhtTable.ehCodes = eHuffCodes; + dhtTable.ehCodeLengths = eHuffSize; + huffTables[huffTableCount] = dhtTable; + huffTableCount++; + } + allTables = new JPEGHuffmanTable[huffTableCount]; System.arraycopy(huffTables, 0, allTables, 0, huffTableCount); } public int signature() { - return JPEGFileFormat.DHT; + return JPEGFileFormat.DHT; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGQuantizationTable.d --- a/dwt/internal/image/JPEGQuantizationTable.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGQuantizationTable.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -17,35 +17,35 @@ import dwt.dwthelper.System; final class JPEGQuantizationTable : JPEGVariableSizeSegment { - public static byte[] DefaultLuminanceQTable = [ - cast(byte)255, cast(byte)219, 0, 67, 0, - 16, 11, 10, 16, 24, 40, 51, 61, - 12, 12, 14, 19, 26, 58, 60, 55, - 14, 13, 16, 24, 40, 57, 69, 56, - 14, 17, 22, 29, 51, 87, 80, 62, - 18, 22, 37, 56, 68, 109, 103, 77, - 24, 35, 55, 64, 81, 104, 113, 92, - 49, 64, 78, 87, 103, 121, 120, 101, - 72, 92, 95, 98, 112, 100, 103, 99 - ]; - public static byte[] DefaultChrominanceQTable = [ - cast(byte)255, cast(byte)219, 0, 67, 1, - 17, 18, 24, 47, 99, 99, 99, 99, - 18, 21, 26, 66, 99, 99, 99, 99, - 24, 26, 56, 99, 99, 99, 99, 99, - 47, 66, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99 - ]; + public static byte[] DefaultLuminanceQTable = [ + cast(byte)255, cast(byte)219, 0, 67, 0, + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, + 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, + 72, 92, 95, 98, 112, 100, 103, 99 + ]; + public static byte[] DefaultChrominanceQTable = [ + cast(byte)255, cast(byte)219, 0, 67, 1, + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + ]; public this(byte[] reference) { - super(reference); + super(reference); } public this(LEDataInputStream byteStream) { - super(byteStream); + super(byteStream); } public static JPEGQuantizationTable defaultChrominanceTable() { @@ -61,110 +61,110 @@ } public int[] getQuantizationTablesKeys() { - int[] keys = new int[4]; - int keysIndex = 0; - int totalLength = getSegmentLength() - 2; - int ofs = 4; - while (totalLength > 64) { - int tq = reference[ofs] & 0xF; - int pq = (reference[ofs] & 0xFF) >> 4; - if (pq == 0) { - ofs += 65; - totalLength -= 65; - } else { - ofs += 129; - totalLength -= 129; - } - if (keysIndex >= keys.length) { + int[] keys = new int[4]; + int keysIndex = 0; + int totalLength = getSegmentLength() - 2; + int ofs = 4; + while (totalLength > 64) { + int tq = reference[ofs] & 0xF; + int pq = (reference[ofs] & 0xFF) >> 4; + if (pq == 0) { + ofs += 65; + totalLength -= 65; + } else { + ofs += 129; + totalLength -= 129; + } + if (keysIndex >= keys.length) { int[] newKeys = new int[keys.length + 4]; System.arraycopy(keys, 0, newKeys, 0, keys.length); keys = newKeys; - } - keys[keysIndex] = tq; - keysIndex++; - } + } + keys[keysIndex] = tq; + keysIndex++; + } int[] newKeys = new int[keysIndex]; System.arraycopy(keys, 0, newKeys, 0, keysIndex); return newKeys; } public int[][] getQuantizationTablesValues() { - int[][] values = new int[][](4); - int valuesIndex = 0; - int totalLength = getSegmentLength() - 2; - int ofs = 4; - while (totalLength > 64) { - int[] qk = new int[64]; - int pq = (reference[ofs] & 0xFF) >> 4; - if (pq == 0) { - for (int i = 0; i < qk.length; i++) { - qk[i] = reference[ofs + i + 1] & 0xFF; - } - ofs += 65; - totalLength -= 65; - } else { - for (int i = 0; i < qk.length; i++) { - int idx = (i - 1) * 2 ; - qk[i] = (reference[ofs + idx + 1] & 0xFF) * 256 + (reference[ofs + idx + 2] & 0xFF); - } - ofs += 129; - totalLength -= 129; - } - if (valuesIndex >= values.length) { + int[][] values = new int[][](4); + int valuesIndex = 0; + int totalLength = getSegmentLength() - 2; + int ofs = 4; + while (totalLength > 64) { + int[] qk = new int[64]; + int pq = (reference[ofs] & 0xFF) >> 4; + if (pq == 0) { + for (int i = 0; i < qk.length; i++) { + qk[i] = reference[ofs + i + 1] & 0xFF; + } + ofs += 65; + totalLength -= 65; + } else { + for (int i = 0; i < qk.length; i++) { + int idx = (i - 1) * 2 ; + qk[i] = (reference[ofs + idx + 1] & 0xFF) * 256 + (reference[ofs + idx + 2] & 0xFF); + } + ofs += 129; + totalLength -= 129; + } + if (valuesIndex >= values.length) { int[][] newValues = new int[][](values.length + 4); System.arraycopy(values, 0, newValues, 0, values.length); values = newValues; - } - values[valuesIndex] = qk; - valuesIndex++; - } + } + values[valuesIndex] = qk; + valuesIndex++; + } int[][] newValues = new int[][](valuesIndex); System.arraycopy(values, 0, newValues, 0, valuesIndex); return newValues; } public void scaleBy(int qualityFactor) { - int qFactor = qualityFactor; - if (qFactor <= 0) { - qFactor = 1; - } - if (qFactor > 100) { - qFactor = 100; - } - if (qFactor < 50) { - qFactor = 5000 / qFactor; - } else { - qFactor = 200 - (qFactor * 2); - } - int totalLength = getSegmentLength() - 2; - int ofs = 4; - while (totalLength > 64) { -// int tq = reference[ofs] & 0xFF; - int pq = (reference[ofs] & 0xFF) >> 4; - if (pq == 0) { - for (int i = ofs + 1; i <= ofs + 64; i++) { - int temp = ((reference[i] & 0xFF) * qFactor + 50) / 100; - if (temp <= 0) temp = 1; - if (temp > 255) temp = 255; - reference[i] = cast(byte)temp; - } - ofs += 65; - totalLength -= 65; - } else { - for (int i = ofs + 1; i <= ofs + 128; i += 2) { - int temp = (((reference[i] & 0xFF) * 256 + (reference[i + 1] & 0xFF)) * qFactor + 50) / 100; - if (temp <= 0) temp = 1; - if (temp > 32767) temp = 32767; - reference[i] = cast(byte)(temp >> 8); - reference[i + 1] = cast(byte)(temp & 0xFF); - } - ofs += 129; - totalLength -= 129; - } - } + int qFactor = qualityFactor; + if (qFactor <= 0) { + qFactor = 1; + } + if (qFactor > 100) { + qFactor = 100; + } + if (qFactor < 50) { + qFactor = 5000 / qFactor; + } else { + qFactor = 200 - (qFactor * 2); + } + int totalLength = getSegmentLength() - 2; + int ofs = 4; + while (totalLength > 64) { +// int tq = reference[ofs] & 0xFF; + int pq = (reference[ofs] & 0xFF) >> 4; + if (pq == 0) { + for (int i = ofs + 1; i <= ofs + 64; i++) { + int temp = ((reference[i] & 0xFF) * qFactor + 50) / 100; + if (temp <= 0) temp = 1; + if (temp > 255) temp = 255; + reference[i] = cast(byte)temp; + } + ofs += 65; + totalLength -= 65; + } else { + for (int i = ofs + 1; i <= ofs + 128; i += 2) { + int temp = (((reference[i] & 0xFF) * 256 + (reference[i + 1] & 0xFF)) * qFactor + 50) / 100; + if (temp <= 0) temp = 1; + if (temp > 32767) temp = 32767; + reference[i] = cast(byte)(temp >> 8); + reference[i + 1] = cast(byte)(temp & 0xFF); + } + ofs += 129; + totalLength -= 129; + } + } } public int signature() { - return JPEGFileFormat.DQT; + return JPEGFileFormat.DQT; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGRestartInterval.d --- a/dwt/internal/image/JPEGRestartInterval.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGRestartInterval.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,19 +16,19 @@ final class JPEGRestartInterval : JPEGFixedSizeSegment { - public this(LEDataInputStream byteStream) { - super(byteStream); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + } - public int signature() { - return JPEGFileFormat.DRI; - } + public int signature() { + return JPEGFileFormat.DRI; + } - public int getRestartInterval() { - return ((reference[4] & 0xFF) << 8 | (reference[5] & 0xFF)); - } + public int getRestartInterval() { + return ((reference[4] & 0xFF) << 8 | (reference[5] & 0xFF)); + } - public int fixedSize() { - return 6; - } + public int fixedSize() { + return 6; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGScanHeader.d --- a/dwt/internal/image/JPEGScanHeader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGScanHeader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -16,110 +16,110 @@ import dwt.internal.image.JPEGFileFormat; final class JPEGScanHeader : JPEGVariableSizeSegment { - public int[][] componentParameters; + public int[][] componentParameters; public this(byte[] reference) { - super(reference); + super(reference); } public this(LEDataInputStream byteStream) { - super(byteStream); - initializeComponentParameters(); + super(byteStream); + initializeComponentParameters(); } public int getApproxBitPositionHigh() { - return reference[(2 * getNumberOfImageComponents()) + 7] >> 4; + return reference[(2 * getNumberOfImageComponents()) + 7] >> 4; } public int getApproxBitPositionLow() { - return reference[(2 * getNumberOfImageComponents()) + 7] & 0xF; + return reference[(2 * getNumberOfImageComponents()) + 7] & 0xF; } public int getEndOfSpectralSelection() { - return reference[(2 * getNumberOfImageComponents()) + 6]; + return reference[(2 * getNumberOfImageComponents()) + 6]; } public int getNumberOfImageComponents() { - return reference[4]; + return reference[4]; } public int getStartOfSpectralSelection() { - return reference[(2 * getNumberOfImageComponents()) + 5]; + return reference[(2 * getNumberOfImageComponents()) + 5]; } /* Used when decoding. */ void initializeComponentParameters() { - int compCount = getNumberOfImageComponents(); - componentParameters = null; - for (int i = 0; i < compCount; i++) { - int ofs = 5 + i * 2; - int cid = reference[ofs] & 0xFF; - int dc = (reference[ofs + 1] & 0xFF) >> 4; - int ac = reference[ofs + 1] & 0xF; - if (componentParameters.length <= cid) { - int[][] newParams = new int[][](cid + 1); + int compCount = getNumberOfImageComponents(); + componentParameters = null; + for (int i = 0; i < compCount; i++) { + int ofs = 5 + i * 2; + int cid = reference[ofs] & 0xFF; + int dc = (reference[ofs + 1] & 0xFF) >> 4; + int ac = reference[ofs + 1] & 0xF; + if (componentParameters.length <= cid) { + int[][] newParams = new int[][](cid + 1); System.arraycopy(componentParameters, 0, newParams, 0, componentParameters.length); - componentParameters = newParams; - } - componentParameters[cid] = [ dc, ac ]; - } + componentParameters = newParams; + } + componentParameters[cid] = [ dc, ac ]; + } } /* Used when encoding. */ public void initializeContents() { - int compCount = getNumberOfImageComponents(); - int[][] compSpecParams = componentParameters; - if (compCount == 0 || compCount != compSpecParams.length) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - for (int i = 0; i < compCount; i++) { - int ofs = i * 2 + 5; - int[] compParams = compSpecParams[i]; - reference[ofs] = cast(byte)(i + 1); - reference[ofs + 1] = cast(byte)(compParams[0] * 16 + compParams[1]); - } + int compCount = getNumberOfImageComponents(); + int[][] compSpecParams = componentParameters; + if (compCount == 0 || compCount != compSpecParams.length) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + for (int i = 0; i < compCount; i++) { + int ofs = i * 2 + 5; + int[] compParams = compSpecParams[i]; + reference[ofs] = cast(byte)(i + 1); + reference[ofs + 1] = cast(byte)(compParams[0] * 16 + compParams[1]); + } } public void setEndOfSpectralSelection(int anInteger) { - reference[(2 * getNumberOfImageComponents()) + 6] = cast(byte)anInteger; + reference[(2 * getNumberOfImageComponents()) + 6] = cast(byte)anInteger; } public void setNumberOfImageComponents(int anInteger) { - reference[4] = cast(byte)(anInteger & 0xFF); + reference[4] = cast(byte)(anInteger & 0xFF); } public void setStartOfSpectralSelection(int anInteger) { - reference[(2 * getNumberOfImageComponents()) + 5] = cast(byte)anInteger; + reference[(2 * getNumberOfImageComponents()) + 5] = cast(byte)anInteger; } public int signature() { - return JPEGFileFormat.SOS; + return JPEGFileFormat.SOS; } public bool verifyProgressiveScan() { - int start = getStartOfSpectralSelection(); - int end = getEndOfSpectralSelection(); - int low = getApproxBitPositionLow(); - int high = getApproxBitPositionHigh(); - int count = getNumberOfImageComponents(); - if ((start == 0 && end == 00) || (start <= end && end <= 63)) { - if (low <= 13 && high <= 13 && (high == 0 || high == low + 1)) { - return start == 0 || (start > 0 && count == 1); - } - } - return false; + int start = getStartOfSpectralSelection(); + int end = getEndOfSpectralSelection(); + int low = getApproxBitPositionLow(); + int high = getApproxBitPositionHigh(); + int count = getNumberOfImageComponents(); + if ((start == 0 && end == 00) || (start <= end && end <= 63)) { + if (low <= 13 && high <= 13 && (high == 0 || high == low + 1)) { + return start == 0 || (start > 0 && count == 1); + } + } + return false; } public bool isACProgressiveScan() { - return getStartOfSpectralSelection() != 0 && getEndOfSpectralSelection() != 0; + return getStartOfSpectralSelection() != 0 && getEndOfSpectralSelection() != 0; } public bool isDCProgressiveScan() { - return getStartOfSpectralSelection() == 0 && getEndOfSpectralSelection() == 0; + return getStartOfSpectralSelection() == 0 && getEndOfSpectralSelection() == 0; } public bool isFirstScan() { - return getApproxBitPositionHigh() == 0; + return getApproxBitPositionHigh() == 0; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGSegment.d --- a/dwt/internal/image/JPEGSegment.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGSegment.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -15,47 +15,47 @@ import tango.core.Exception; class JPEGSegment { - public byte[] reference; + public byte[] reference; - this() { - } + this() { + } - public this(byte[] reference) { - this.reference = reference; - } + public this(byte[] reference) { + this.reference = reference; + } - public int signature() { - return 0; - } + public int signature() { + return 0; + } - public bool verify() { - return getSegmentMarker() == signature(); - } + public bool verify() { + return getSegmentMarker() == signature(); + } - public int getSegmentMarker() { - return ((reference[0] & 0xFF) << 8 | (reference[1] & 0xFF)); - } + public int getSegmentMarker() { + return ((reference[0] & 0xFF) << 8 | (reference[1] & 0xFF)); + } - public void setSegmentMarker(int marker) { - reference[0] = cast(byte)((marker & 0xFF00) >> 8); - reference[1] = cast(byte)(marker & 0xFF); - } + public void setSegmentMarker(int marker) { + reference[0] = cast(byte)((marker & 0xFF00) >> 8); + reference[1] = cast(byte)(marker & 0xFF); + } - public int getSegmentLength() { - return ((reference[2] & 0xFF) << 8 | (reference[3] & 0xFF)); - } + public int getSegmentLength() { + return ((reference[2] & 0xFF) << 8 | (reference[3] & 0xFF)); + } - public void setSegmentLength(int length) { - reference[2] = cast(byte)((length & 0xFF00) >> 8); - reference[3] = cast(byte)(length & 0xFF); - } + public void setSegmentLength(int length) { + reference[2] = cast(byte)((length & 0xFF00) >> 8); + reference[3] = cast(byte)(length & 0xFF); + } - public bool writeToStream(LEDataOutputStream byteStream) { - try { - byteStream.write(reference); - return true; - } catch (TracedException e) { - return false; - } - } + public bool writeToStream(LEDataOutputStream byteStream) { + try { + byteStream.write(reference); + return true; + } catch (TracedException e) { + return false; + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGStartOfImage.d --- a/dwt/internal/image/JPEGStartOfImage.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGStartOfImage.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -16,23 +16,23 @@ final class JPEGStartOfImage : JPEGFixedSizeSegment { - public this() { - super(); - } + public this() { + super(); + } - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - super(byteStream); - } + public this(LEDataInputStream byteStream) { + super(byteStream); + } - public int signature() { - return JPEGFileFormat.SOI; - } + public int signature() { + return JPEGFileFormat.SOI; + } - public int fixedSize() { - return 2; - } + public int fixedSize() { + return 2; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/JPEGVariableSizeSegment.d --- a/dwt/internal/image/JPEGVariableSizeSegment.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/JPEGVariableSizeSegment.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -18,24 +18,24 @@ abstract class JPEGVariableSizeSegment : JPEGSegment { - public this(byte[] reference) { - super(reference); - } + public this(byte[] reference) { + super(reference); + } - public this(LEDataInputStream byteStream) { - try { - byte[] header = new byte[4]; - byteStream.read(header); - reference = header; // to use getSegmentLength() - byte[] contents = new byte[getSegmentLength() + 2]; - contents[0] = header[0]; - contents[1] = header[1]; - contents[2] = header[2]; - contents[3] = header[3]; - byteStream.read(contents, 4, contents.length - 4); - reference = contents; - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + public this(LEDataInputStream byteStream) { + try { + byte[] header = new byte[4]; + byteStream.read(header); + reference = header; // to use getSegmentLength() + byte[] contents = new byte[getSegmentLength() + 2]; + contents[0] = header[0]; + contents[1] = header[1]; + contents[2] = header[2]; + contents[3] = header[3]; + byteStream.read(contents, 4, contents.length - 4); + reference = contents; + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/LEDataInputStream.d --- a/dwt/internal/image/LEDataInputStream.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/LEDataInputStream.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -21,172 +21,172 @@ InputStream host; - int position; + int position; - /** - * The byte array containing the bytes to read. - */ - protected byte[] buf; + /** + * The byte array containing the bytes to read. + */ + protected byte[] buf; - /** - * The current position within the byte array buf. A value - * equal to buf.length indicates no bytes available. A value of - * 0 indicates the buffer is full. - */ - protected int pos; + /** + * The current position within the byte array buf. A value + * equal to buf.length indicates no bytes available. A value of + * 0 indicates the buffer is full. + */ + protected int pos; - public this(InputStream input) { - this(input, 512); - } + public this(InputStream input) { + this(input, 512); + } - public this(InputStream input, int bufferSize) { + public this(InputStream input, int bufferSize) { host = input; - if (bufferSize > 0) { - buf = new byte[bufferSize]; - pos = bufferSize; - } - else throw new IllegalArgumentException("bufferSize must be greater zero" ); - } + if (bufferSize > 0) { + buf = new byte[bufferSize]; + pos = bufferSize; + } + else throw new IllegalArgumentException("bufferSize must be greater zero" ); + } - public void close() { + public void close() { buf = null; - if (host !is null) { - host.close(); + if (host !is null) { + host.close(); host = null; - } - } + } + } - /** - * Answer how many bytes were read. - */ - public int getPosition() { - return position; - } + /** + * Answer how many bytes were read. + */ + public int getPosition() { + return position; + } - /** - * Answers how many bytes are available for reading without blocking - */ - public int available() { - if (buf is null) throw new IOException("buf is null"); - return (buf.length - pos) + host.available(); - } + /** + * Answers how many bytes are available for reading without blocking + */ + public int available() { + if (buf is null) throw new IOException("buf is null"); + return (buf.length - pos) + host.available(); + } - /** - * Answer the next byte of the input stream. - */ - public int read() { - if (buf is null) throw new IOException("buf is null"); - if (pos < buf.length) { - position++; - return (buf[pos++] & 0xFF); - } + /** + * Answer the next byte of the input stream. + */ + public int read() { + if (buf is null) throw new IOException("buf is null"); + if (pos < buf.length) { + position++; + return (buf[pos++] & 0xFF); + } int c = host.read(); - if (c != -1 ) position++; - return c; - } + if (c != -1 ) position++; + return c; + } - /** - * Don't imitate the JDK behaviour of reading a random number - * of bytes when you can actually read them all. - */ - public int read(byte b[], int off, int len) { - int read = 0, count; - while (read != len && (count = readData(b, off, len - read)) != -1) { - off += count; - read += count; - } - position += read; - if (read == 0 && read != len) return -1; - return read; - } + /** + * Don't imitate the JDK behaviour of reading a random number + * of bytes when you can actually read them all. + */ + public int read(byte b[], int off, int len) { + int read = 0, count; + while (read != len && (count = readData(b, off, len - read)) != -1) { + off += count; + read += count; + } + position += read; + if (read == 0 && read != len) return -1; + return read; + } - /** - * Reads at most length bytes from this LEDataInputStream and - * stores them in byte array buffer starting at offset. - *

    - * Answer the number of bytes actually read or -1 if no bytes were read and - * end of stream was encountered. This implementation reads bytes from - * the pushback buffer first, then the target stream if more bytes are required - * to satisfy count. - *

    - * @param buffer the byte array in which to store the read bytes. - * @param offset the offset in buffer to store the read bytes. - * @param length the maximum number of bytes to store in buffer. - * - * @return int the number of bytes actually read or -1 if end of stream. - * - * @exception java.io.IOException if an IOException occurs. - */ - private int readData(byte[] buffer, int offset, int len) { - if (buf is null) throw new IOException("buf is null"); - if (offset < 0 || offset > buffer.length || - len < 0 || (len > buffer.length - offset)) { - throw new ArrayBoundsException(__FILE__,__LINE__); - } + /** + * Reads at most length bytes from this LEDataInputStream and + * stores them in byte array buffer starting at offset. + *

    + * Answer the number of bytes actually read or -1 if no bytes were read and + * end of stream was encountered. This implementation reads bytes from + * the pushback buffer first, then the target stream if more bytes are required + * to satisfy count. + *

    + * @param buffer the byte array in which to store the read bytes. + * @param offset the offset in buffer to store the read bytes. + * @param length the maximum number of bytes to store in buffer. + * + * @return int the number of bytes actually read or -1 if end of stream. + * + * @exception java.io.IOException if an IOException occurs. + */ + private int readData(byte[] buffer, int offset, int len) { + if (buf is null) throw new IOException("buf is null"); + if (offset < 0 || offset > buffer.length || + len < 0 || (len > buffer.length - offset)) { + throw new ArrayBoundsException(__FILE__,__LINE__); + } - int cacheCopied = 0; - int newOffset = offset; + int cacheCopied = 0; + int newOffset = offset; - // Are there pushback bytes available? - int available = buf.length - pos; - if (available > 0) { - cacheCopied = (available >= len) ? len : available; + // Are there pushback bytes available? + int available = buf.length - pos; + if (available > 0) { + cacheCopied = (available >= len) ? len : available; System.arraycopy(buf, pos, buffer, newOffset, cacheCopied); - newOffset += cacheCopied; - pos += cacheCopied; - } + newOffset += cacheCopied; + pos += cacheCopied; + } - // Have we copied enough? - if (cacheCopied == len) return len; + // Have we copied enough? + if (cacheCopied == len) return len; - int inCopied = host.read( buffer, newOffset, len - cacheCopied ); + int inCopied = host.read( buffer, newOffset, len - cacheCopied ); if( inCopied == -1 ) inCopied = -1; - if (inCopied > 0 ) return inCopied + cacheCopied; - if (cacheCopied == 0) return inCopied; - return cacheCopied; - } + if (inCopied > 0 ) return inCopied + cacheCopied; + if (cacheCopied == 0) return inCopied; + return cacheCopied; + } - /** - * Answer an integer comprised of the next - * four bytes of the input stream. - */ - public int readInt() { - byte[4] buf = void; - host.read(buf); - return ((((((buf[3] & 0xFF) << 24) | - (buf[2] & 0xFF)) << 16) | - (buf[1] & 0xFF)) << 8) | - (buf[0] & 0xFF); - } + /** + * Answer an integer comprised of the next + * four bytes of the input stream. + */ + public int readInt() { + byte[4] buf = void; + host.read(buf); + return ((((((buf[3] & 0xFF) << 24) | + (buf[2] & 0xFF)) << 16) | + (buf[1] & 0xFF)) << 8) | + (buf[0] & 0xFF); + } - /** - * Answer a short comprised of the next - * two bytes of the input stream. - */ - public short readShort() { - byte[2] buf = void; - host.read(buf); - return cast(short)(((buf[1] & 0xFF) << 8) | (buf[0] & 0xFF)); - } + /** + * Answer a short comprised of the next + * two bytes of the input stream. + */ + public short readShort() { + byte[2] buf = void; + host.read(buf); + return cast(short)(((buf[1] & 0xFF) << 8) | (buf[0] & 0xFF)); + } - /** - * Push back the entire content of the given buffer b. - *

    - * The bytes are pushed so that they would be read back b[0], b[1], etc. - * If the push back buffer cannot handle the bytes copied from b, - * an IOException will be thrown and no byte will be pushed back. - *

    - * - * @param b the byte array containing bytes to push back into the stream - * - * @exception java.io.IOException if the pushback buffer is too small - */ - public void unread(byte[] b) { - int l = b.length; - if (l > pos) throw new IOException("cannot unread"); - position -= l; - pos -= l; + /** + * Push back the entire content of the given buffer b. + *

    + * The bytes are pushed so that they would be read back b[0], b[1], etc. + * If the push back buffer cannot handle the bytes copied from b, + * an IOException will be thrown and no byte will be pushed back. + *

    + * + * @param b the byte array containing bytes to push back into the stream + * + * @exception java.io.IOException if the pushback buffer is too small + */ + public void unread(byte[] b) { + int l = b.length; + if (l > pos) throw new IOException("cannot unread"); + position -= l; + pos -= l; System.arraycopy(b, 0, buf, pos, l); - } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/LEDataOutputStream.d --- a/dwt/internal/image/LEDataOutputStream.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/LEDataOutputStream.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -15,45 +15,45 @@ final class LEDataOutputStream : OutputStream { alias OutputStream.write write; - OutputStream ostr; + OutputStream ostr; public this(OutputStream output) { - this.ostr = output; + this.ostr = output; } /** * Write the specified number of bytes of the given byte array, * starting at the specified offset, to the output stream. */ public void write(byte b[], int off, int len) { - ostr.write(b, off, len); + ostr.write(b, off, len); } /** * Write the given byte to the output stream. */ public void write(int b) { - ostr.write(b); + ostr.write(b); } /** * Write the given byte to the output stream. */ public void writeByte(byte b) { - ostr.write(b); + ostr.write(b); } /** * Write the four bytes of the given integer * to the output stream. */ public void writeInt(int theInt) { - ostr.write(theInt & 0xFF); - ostr.write((theInt >> 8) & 0xFF); - ostr.write((theInt >> 16) & 0xFF); - ostr.write((theInt >> 24) & 0xFF); + ostr.write(theInt & 0xFF); + ostr.write((theInt >> 8) & 0xFF); + ostr.write((theInt >> 16) & 0xFF); + ostr.write((theInt >> 24) & 0xFF); } /** * Write the two bytes of the given short * to the output stream. */ public void writeShort(int theShort) { - ostr.write(theShort & 0xFF); - ostr.write((theShort >> 8) & 0xFF); + ostr.write(theShort & 0xFF); + ostr.write((theShort >> 8) & 0xFF); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/LZWCodec.d --- a/dwt/internal/image/LZWCodec.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/LZWCodec.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -22,431 +22,431 @@ import tango.core.Exception; final class LZWCodec { - int bitsPerPixel, blockSize, blockIndex, currentByte, bitsLeft, - codeSize, clearCode, endCode, newCodes, topSlot, currentSlot, - imageWidth, imageHeight, imageX, imageY, pass, line, codeMask; - byte[] block, lineArray; - int[] stack, suffix, prefix; - LZWNode[] nodeStack; - LEDataInputStream inputStream; - LEDataOutputStream outputStream; - ImageData image; - ImageLoader loader; - bool interlaced; - static final int[] MASK_TABLE = [ - 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, - 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF - ]; + int bitsPerPixel, blockSize, blockIndex, currentByte, bitsLeft, + codeSize, clearCode, endCode, newCodes, topSlot, currentSlot, + imageWidth, imageHeight, imageX, imageY, pass, line, codeMask; + byte[] block, lineArray; + int[] stack, suffix, prefix; + LZWNode[] nodeStack; + LEDataInputStream inputStream; + LEDataOutputStream outputStream; + ImageData image; + ImageLoader loader; + bool interlaced; + static final int[] MASK_TABLE = [ + 0x1, 0x3, 0x7, 0xF, 0x1F, 0x3F, 0x7F, + 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF + ]; /** * Decode the input. */ void decode() { - int code; - int oc = 0; - int fc = 0; - byte[] buf = new byte[imageWidth]; - int stackIndex = 0; - int bufIndex = 0; - int c; - while ((c = nextCode()) != endCode) { - if (c == clearCode) { - codeSize = bitsPerPixel + 1; - codeMask = MASK_TABLE[bitsPerPixel]; - currentSlot = newCodes; - topSlot = 1 << codeSize; - while ((c = nextCode()) == clearCode) {} - if (c != endCode) { - oc = fc = c; - buf[bufIndex] = cast(byte)c; - bufIndex++; - if (bufIndex == imageWidth) { - nextPutPixels(buf); - bufIndex = 0; - } - } - } else { - code = c; - if (code >= currentSlot) { - code = oc; - stack[stackIndex] = fc; - stackIndex++; - } - while (code >= newCodes) { - stack[stackIndex] = suffix[code]; - stackIndex++; - code = prefix[code]; - } - stack[stackIndex] = code; - stackIndex++; - if (currentSlot < topSlot) { - fc = code; - suffix[currentSlot] = fc; - prefix[currentSlot] = oc; - currentSlot++; - oc = c; - } - if (currentSlot >= topSlot) { - if (codeSize < 12) { - codeMask = MASK_TABLE[codeSize]; - codeSize++; - topSlot = topSlot + topSlot; - } - } - while (stackIndex > 0) { - stackIndex--; - buf[bufIndex] = cast(byte)stack[stackIndex]; - bufIndex++; - if (bufIndex == imageWidth) { - nextPutPixels(buf); - bufIndex = 0; - } - } - } - } - if (bufIndex != 0 && line < imageHeight) { - nextPutPixels(buf); - } + int code; + int oc = 0; + int fc = 0; + byte[] buf = new byte[imageWidth]; + int stackIndex = 0; + int bufIndex = 0; + int c; + while ((c = nextCode()) != endCode) { + if (c == clearCode) { + codeSize = bitsPerPixel + 1; + codeMask = MASK_TABLE[bitsPerPixel]; + currentSlot = newCodes; + topSlot = 1 << codeSize; + while ((c = nextCode()) == clearCode) {} + if (c != endCode) { + oc = fc = c; + buf[bufIndex] = cast(byte)c; + bufIndex++; + if (bufIndex == imageWidth) { + nextPutPixels(buf); + bufIndex = 0; + } + } + } else { + code = c; + if (code >= currentSlot) { + code = oc; + stack[stackIndex] = fc; + stackIndex++; + } + while (code >= newCodes) { + stack[stackIndex] = suffix[code]; + stackIndex++; + code = prefix[code]; + } + stack[stackIndex] = code; + stackIndex++; + if (currentSlot < topSlot) { + fc = code; + suffix[currentSlot] = fc; + prefix[currentSlot] = oc; + currentSlot++; + oc = c; + } + if (currentSlot >= topSlot) { + if (codeSize < 12) { + codeMask = MASK_TABLE[codeSize]; + codeSize++; + topSlot = topSlot + topSlot; + } + } + while (stackIndex > 0) { + stackIndex--; + buf[bufIndex] = cast(byte)stack[stackIndex]; + bufIndex++; + if (bufIndex == imageWidth) { + nextPutPixels(buf); + bufIndex = 0; + } + } + } + } + if (bufIndex != 0 && line < imageHeight) { + nextPutPixels(buf); + } } /** * Decode the LZW-encoded bytes in the given byte stream * into the given DeviceIndependentImage. */ public void decode(LEDataInputStream inputStream, ImageLoader loader, ImageData image, bool interlaced, int depth) { - this.inputStream = inputStream; - this.loader = loader; - this.image = image; - this.interlaced = interlaced; - this.bitsPerPixel = depth; - initializeForDecoding(); - decode(); + this.inputStream = inputStream; + this.loader = loader; + this.image = image; + this.interlaced = interlaced; + this.bitsPerPixel = depth; + initializeForDecoding(); + decode(); } /** * Encode the image. */ void encode() { - nextPutCode(clearCode); - int lastPrefix = encodeLoop(); - nextPutCode(lastPrefix); - nextPutCode(endCode); + nextPutCode(clearCode); + int lastPrefix = encodeLoop(); + nextPutCode(lastPrefix); + nextPutCode(endCode); - // Write out last partial block - if (bitsLeft == 8) { - block[0] = cast(byte)(blockIndex - 1); // Nothing in last byte - } else { - block[0] = cast(byte)(blockIndex); // Last byte has data - } - writeBlock(); + // Write out last partial block + if (bitsLeft == 8) { + block[0] = cast(byte)(blockIndex - 1); // Nothing in last byte + } else { + block[0] = cast(byte)(blockIndex); // Last byte has data + } + writeBlock(); - // Write out empty block to indicate the end (if needed) - if (block[0] != 0) { - block[0] = 0; - writeBlock(); - } + // Write out empty block to indicate the end (if needed) + if (block[0] != 0) { + block[0] = 0; + writeBlock(); + } } /** * Encode the bytes into the given byte stream * from the given DeviceIndependentImage. */ public void encode(LEDataOutputStream byteStream, ImageData image) { - this.outputStream = byteStream; - this.image = image; - initializeForEncoding(); - encode(); + this.outputStream = byteStream; + this.image = image; + initializeForEncoding(); + encode(); } /** * Encoding loop broken out to allow early return. */ int encodeLoop() { - int pixel = nextPixel(); - bool found; - LZWNode node; - while (true) { - int currentPrefix = pixel; - node = nodeStack[currentPrefix]; - found = true; - pixel = nextPixel(); - if (pixel < 0) - return currentPrefix; - while (found && (node.children != null)) { - node = node.children; - while (found && (node.suffix != pixel)) { - if (pixel < node.suffix) { - if (node.left == null) { - node.left = new LZWNode(); - found = false; - } - node = node.left; - } else { - if (node.right == null) { - node.right = new LZWNode(); - found = false; - } - node = node.right; - } - } - if (found) { - currentPrefix = node.code; - pixel = nextPixel(); - if (pixel < 0) - return currentPrefix; - } - } - if (found) { - node.children = new LZWNode(); - node = node.children; - } - node.children = null; - node.left = null; - node.right = null; - node.code = currentSlot; - node.prefix = currentPrefix; - node.suffix = pixel; - nextPutCode(currentPrefix); - currentSlot++; - // Off by one? - if (currentSlot < 4096) { - if (currentSlot > topSlot) { - codeSize++; - codeMask = MASK_TABLE[codeSize - 1]; - topSlot *= 2; - } - } else { - nextPutCode(clearCode); - for (int i = 0; i < nodeStack.length; i++) - nodeStack[i].children = null; - codeSize = bitsPerPixel + 1; - codeMask = MASK_TABLE[codeSize - 1]; - currentSlot = newCodes; - topSlot = 1 << codeSize; - } - } + int pixel = nextPixel(); + bool found; + LZWNode node; + while (true) { + int currentPrefix = pixel; + node = nodeStack[currentPrefix]; + found = true; + pixel = nextPixel(); + if (pixel < 0) + return currentPrefix; + while (found && (node.children != null)) { + node = node.children; + while (found && (node.suffix != pixel)) { + if (pixel < node.suffix) { + if (node.left == null) { + node.left = new LZWNode(); + found = false; + } + node = node.left; + } else { + if (node.right == null) { + node.right = new LZWNode(); + found = false; + } + node = node.right; + } + } + if (found) { + currentPrefix = node.code; + pixel = nextPixel(); + if (pixel < 0) + return currentPrefix; + } + } + if (found) { + node.children = new LZWNode(); + node = node.children; + } + node.children = null; + node.left = null; + node.right = null; + node.code = currentSlot; + node.prefix = currentPrefix; + node.suffix = pixel; + nextPutCode(currentPrefix); + currentSlot++; + // Off by one? + if (currentSlot < 4096) { + if (currentSlot > topSlot) { + codeSize++; + codeMask = MASK_TABLE[codeSize - 1]; + topSlot *= 2; + } + } else { + nextPutCode(clearCode); + for (int i = 0; i < nodeStack.length; i++) + nodeStack[i].children = null; + codeSize = bitsPerPixel + 1; + codeMask = MASK_TABLE[codeSize - 1]; + currentSlot = newCodes; + topSlot = 1 << codeSize; + } + } } /** * Initialize the receiver for decoding the given * byte array. */ void initializeForDecoding() { - pass = 1; - line = 0; - codeSize = bitsPerPixel + 1; - topSlot = 1 << codeSize; - clearCode = 1 << bitsPerPixel; - endCode = clearCode + 1; - newCodes = currentSlot = endCode + 1; - currentByte = -1; - blockSize = bitsLeft = 0; - blockIndex = 0; - codeMask = MASK_TABLE[codeSize - 1]; - stack = new int[4096]; - suffix = new int[4096]; - prefix = new int[4096]; - block = new byte[256]; - imageWidth = image.width; - imageHeight = image.height; + pass = 1; + line = 0; + codeSize = bitsPerPixel + 1; + topSlot = 1 << codeSize; + clearCode = 1 << bitsPerPixel; + endCode = clearCode + 1; + newCodes = currentSlot = endCode + 1; + currentByte = -1; + blockSize = bitsLeft = 0; + blockIndex = 0; + codeMask = MASK_TABLE[codeSize - 1]; + stack = new int[4096]; + suffix = new int[4096]; + prefix = new int[4096]; + block = new byte[256]; + imageWidth = image.width; + imageHeight = image.height; } /** * Initialize the receiver for encoding the given * byte array. */ void initializeForEncoding() { - interlaced = false; - bitsPerPixel = image.depth; - codeSize = bitsPerPixel + 1; - topSlot = 1 << codeSize; - clearCode = 1 << bitsPerPixel; - endCode = clearCode + 1; - newCodes = currentSlot = endCode + 1; - bitsLeft = 8; - currentByte = 0; - blockIndex = 1; - blockSize = 255; - block = new byte[blockSize]; - block[0] = cast(byte)(blockSize - 1); - nodeStack = new LZWNode[1 << bitsPerPixel]; - for (int i = 0; i < nodeStack.length; i++) { - LZWNode node = new LZWNode(); - node.code = i + 1; - node.prefix = -1; - node.suffix = i + 1; - nodeStack[i] = node; - } - imageWidth = image.width; - imageHeight = image.height; - imageY = -1; - lineArray = new byte[imageWidth]; - imageX = imageWidth + 1; // Force a read + interlaced = false; + bitsPerPixel = image.depth; + codeSize = bitsPerPixel + 1; + topSlot = 1 << codeSize; + clearCode = 1 << bitsPerPixel; + endCode = clearCode + 1; + newCodes = currentSlot = endCode + 1; + bitsLeft = 8; + currentByte = 0; + blockIndex = 1; + blockSize = 255; + block = new byte[blockSize]; + block[0] = cast(byte)(blockSize - 1); + nodeStack = new LZWNode[1 << bitsPerPixel]; + for (int i = 0; i < nodeStack.length; i++) { + LZWNode node = new LZWNode(); + node.code = i + 1; + node.prefix = -1; + node.suffix = i + 1; + nodeStack[i] = node; + } + imageWidth = image.width; + imageHeight = image.height; + imageY = -1; + lineArray = new byte[imageWidth]; + imageX = imageWidth + 1; // Force a read } /** * Answer the next code from the input byte array. */ int nextCode() { - int code; - if (bitsLeft == 0) { - if (blockIndex >= blockSize) { - blockSize = readBlock(); - blockIndex = 0; - if (blockSize == 0) return endCode; - } - blockIndex++; - currentByte = block[blockIndex] & 0xFF; - bitsLeft = 8; - code = currentByte; - } else { - int shift = bitsLeft - 8; - if (shift < 0) - code = currentByte >> (0 - shift); - else - code = currentByte << shift; - } - while (codeSize > bitsLeft) { - if (blockIndex >= blockSize) { - blockSize = readBlock(); - blockIndex = 0; - if (blockSize == 0) return endCode; - } - blockIndex++; - currentByte = block[blockIndex] & 0xFF; - code += currentByte << bitsLeft; - bitsLeft += 8; - } - bitsLeft -= codeSize; - return code & codeMask; + int code; + if (bitsLeft == 0) { + if (blockIndex >= blockSize) { + blockSize = readBlock(); + blockIndex = 0; + if (blockSize == 0) return endCode; + } + blockIndex++; + currentByte = block[blockIndex] & 0xFF; + bitsLeft = 8; + code = currentByte; + } else { + int shift = bitsLeft - 8; + if (shift < 0) + code = currentByte >> (0 - shift); + else + code = currentByte << shift; + } + while (codeSize > bitsLeft) { + if (blockIndex >= blockSize) { + blockSize = readBlock(); + blockIndex = 0; + if (blockSize == 0) return endCode; + } + blockIndex++; + currentByte = block[blockIndex] & 0xFF; + code += currentByte << bitsLeft; + bitsLeft += 8; + } + bitsLeft -= codeSize; + return code & codeMask; } /** * Answer the next pixel to encode in the image */ int nextPixel() { - imageX++; - if (imageX > imageWidth) { - imageY++; - if (imageY >= imageHeight) { - return -1; - } else { - nextPixels(lineArray, imageWidth); - } - imageX = 1; - } - return this.lineArray[imageX - 1] & 0xFF; + imageX++; + if (imageX > imageWidth) { + imageY++; + if (imageY >= imageHeight) { + return -1; + } else { + nextPixels(lineArray, imageWidth); + } + imageX = 1; + } + return this.lineArray[imageX - 1] & 0xFF; } /** * Copy a row of pixel values from the image. */ void nextPixels(byte[] buf, int lineWidth) { - if (image.depth == 8) { + if (image.depth == 8) { System.arraycopy(image.data, imageY * image.bytesPerLine, buf, 0, lineWidth); - } else { - image.getPixels(0, imageY, lineWidth, buf, 0); - } + } else { + image.getPixels(0, imageY, lineWidth, buf, 0); + } } /** * Output aCode to the output stream. */ void nextPutCode(int aCode) { - int codeToDo = aCode; - int codeBitsToDo = codeSize; - // Fill in the remainder of the current byte with the - // *high-order* bits of the code. - int c = codeToDo & MASK_TABLE[bitsLeft - 1]; - currentByte = currentByte | (c << (8 - bitsLeft)); - block[blockIndex] = cast(byte)currentByte; - codeBitsToDo -= bitsLeft; - if (codeBitsToDo < 1) { - // The whole code fit in the first byte, so we are done. - bitsLeft -= codeSize; - if (bitsLeft == 0) { - // We used the whole last byte, so get ready - // for the next one. - bitsLeft = 8; - blockIndex++; - if (blockIndex >= blockSize) { - writeBlock(); - blockIndex = 1; - } - currentByte = 0; - } - return; - } - codeToDo = codeToDo >> bitsLeft; + int codeToDo = aCode; + int codeBitsToDo = codeSize; + // Fill in the remainder of the current byte with the + // *high-order* bits of the code. + int c = codeToDo & MASK_TABLE[bitsLeft - 1]; + currentByte = currentByte | (c << (8 - bitsLeft)); + block[blockIndex] = cast(byte)currentByte; + codeBitsToDo -= bitsLeft; + if (codeBitsToDo < 1) { + // The whole code fit in the first byte, so we are done. + bitsLeft -= codeSize; + if (bitsLeft == 0) { + // We used the whole last byte, so get ready + // for the next one. + bitsLeft = 8; + blockIndex++; + if (blockIndex >= blockSize) { + writeBlock(); + blockIndex = 1; + } + currentByte = 0; + } + return; + } + codeToDo = codeToDo >> bitsLeft; - // Fill in any remaining whole bytes (i.e. not the last one!) - blockIndex++; - if (blockIndex >= blockSize) { - writeBlock(); - blockIndex = 1; - } - while (codeBitsToDo >= 8) { - currentByte = codeToDo & 0xFF; - block[blockIndex] = cast(byte)currentByte; - codeToDo = codeToDo >> 8; - codeBitsToDo -= 8; - blockIndex++; - if (blockIndex >= blockSize) { - writeBlock(); - blockIndex = 1; - } - } - // Fill the *low-order* bits of the last byte with the remainder - bitsLeft = 8 - codeBitsToDo; - currentByte = codeToDo; - block[blockIndex] = cast(byte)currentByte; + // Fill in any remaining whole bytes (i.e. not the last one!) + blockIndex++; + if (blockIndex >= blockSize) { + writeBlock(); + blockIndex = 1; + } + while (codeBitsToDo >= 8) { + currentByte = codeToDo & 0xFF; + block[blockIndex] = cast(byte)currentByte; + codeToDo = codeToDo >> 8; + codeBitsToDo -= 8; + blockIndex++; + if (blockIndex >= blockSize) { + writeBlock(); + blockIndex = 1; + } + } + // Fill the *low-order* bits of the last byte with the remainder + bitsLeft = 8 - codeBitsToDo; + currentByte = codeToDo; + block[blockIndex] = cast(byte)currentByte; } /** * Copy a row of pixel values to the image. */ void nextPutPixels(byte[] buf) { - if (image.depth == 8) { - // Slight optimization for depth = 8. - int start = line * image.bytesPerLine; - for (int i = 0; i < imageWidth; i++) - image.data[start + i] = buf[i]; - } else { - image.setPixels(0, line, imageWidth, buf, 0); - } - if (interlaced) { - if (pass == 1) { - copyRow(buf, 7); - line += 8; - } else if (pass == 2) { - copyRow(buf, 3); - line += 8; - } else if (pass == 3) { - copyRow(buf, 1); - line += 4; - } else if (pass == 4) { - line += 2; - } else if (pass == 5) { - line += 0; - } - if (line >= imageHeight) { - pass++; - if (pass == 2) line = 4; - else if (pass == 3) line = 2; - else if (pass == 4) line = 1; - else if (pass == 5) line = 0; - if (pass < 5) { - if (loader.hasListeners()) { - ImageData imageCopy = cast(ImageData) image.clone(); - loader.notifyListeners( - new ImageLoaderEvent(loader, imageCopy, pass - 2, false)); - } - } - } - if (line >= imageHeight) line = 0; - } else { - line++; - } + if (image.depth == 8) { + // Slight optimization for depth = 8. + int start = line * image.bytesPerLine; + for (int i = 0; i < imageWidth; i++) + image.data[start + i] = buf[i]; + } else { + image.setPixels(0, line, imageWidth, buf, 0); + } + if (interlaced) { + if (pass == 1) { + copyRow(buf, 7); + line += 8; + } else if (pass == 2) { + copyRow(buf, 3); + line += 8; + } else if (pass == 3) { + copyRow(buf, 1); + line += 4; + } else if (pass == 4) { + line += 2; + } else if (pass == 5) { + line += 0; + } + if (line >= imageHeight) { + pass++; + if (pass == 2) line = 4; + else if (pass == 3) line = 2; + else if (pass == 4) line = 1; + else if (pass == 5) line = 0; + if (pass < 5) { + if (loader.hasListeners()) { + ImageData imageCopy = cast(ImageData) image.clone(); + loader.notifyListeners( + new ImageLoaderEvent(loader, imageCopy, pass - 2, false)); + } + } + } + if (line >= imageHeight) line = 0; + } else { + line++; + } } /** * Copy duplicate rows of pixel values to the image. * This is to fill in rows if the image is interlaced. */ void copyRow(byte[] buf, int copies) { - for (int i = 1; i <= copies; i++) { - if (line + i < imageHeight) { - image.setPixels(0, line + i, imageWidth, buf, 0); - } - } + for (int i = 1; i <= copies; i++) { + if (line + i < imageHeight) { + image.setPixels(0, line + i, imageWidth, buf, 0); + } + } } /** * Read a block from the byte stream. @@ -454,31 +454,31 @@ * Throw an exception if the block could not be read. */ int readBlock() { - int size = -1; - try { - size = inputStream.read(); - if (size == -1) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - block[0] = cast(byte)size; - size = inputStream.read(block, 1, size); - if (size == -1) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } - return size; + int size = -1; + try { + size = inputStream.read(); + if (size == -1) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + block[0] = cast(byte)size; + size = inputStream.read(block, 1, size); + if (size == -1) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } + return size; } /** * Write a block to the byte stream. * Throw an exception if the block could not be written. */ void writeBlock() { - try { - outputStream.write(block, 0, (block[0] & 0xFF) + 1); - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } + try { + outputStream.write(block, 0, (block[0] & 0xFF) + 1); + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/LZWNode.d --- a/dwt/internal/image/LZWNode.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/LZWNode.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -12,6 +12,6 @@ final class LZWNode { - public LZWNode left, right, children; - public int code, prefix, suffix; + public LZWNode left, right, children; + public int code, prefix, suffix; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/OS2BMPFileFormat.d --- a/dwt/internal/image/OS2BMPFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/OS2BMPFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -22,279 +22,279 @@ import tango.core.Exception; final class OS2BMPFileFormat : FileFormat { - static final int BMPFileHeaderSize = 14; - static final int BMPHeaderFixedSize = 12; - int width, height, bitCount; + static final int BMPFileHeaderSize = 14; + static final int BMPHeaderFixedSize = 12; + int width, height, bitCount; bool isFileFormat(LEDataInputStream stream) { - try { - byte[] header = new byte[18]; - stream.read(header); - stream.unread(header); - int infoHeaderSize = (header[14] & 0xFF) | ((header[15] & 0xFF) << 8) | ((header[16] & 0xFF) << 16) | ((header[17] & 0xFF) << 24); - return header[0] == 0x42 && header[1] == 0x4D && infoHeaderSize == BMPHeaderFixedSize; - } catch (TracedException e) { - return false; - } + try { + byte[] header = new byte[18]; + stream.read(header); + stream.unread(header); + int infoHeaderSize = (header[14] & 0xFF) | ((header[15] & 0xFF) << 8) | ((header[16] & 0xFF) << 16) | ((header[17] & 0xFF) << 24); + return header[0] == 0x42 && header[1] == 0x4D && infoHeaderSize == BMPHeaderFixedSize; + } catch (TracedException e) { + return false; + } } byte[] loadData(byte[] infoHeader) { - int stride = (width * bitCount + 7) / 8; - stride = (stride + 3) / 4 * 4; // Round up to 4 byte multiple - byte[] data = loadData(infoHeader, stride); - flipScanLines(data, stride, height); - return data; + int stride = (width * bitCount + 7) / 8; + stride = (stride + 3) / 4 * 4; // Round up to 4 byte multiple + byte[] data = loadData(infoHeader, stride); + flipScanLines(data, stride, height); + return data; } byte[] loadData(byte[] infoHeader, int stride) { - int dataSize = height * stride; - byte[] data = new byte[dataSize]; - try { - if (inputStream.read(data) != dataSize) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return data; + int dataSize = height * stride; + byte[] data = new byte[dataSize]; + try { + if (inputStream.read(data) != dataSize) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return data; } int[] loadFileHeader() { - int[] header = new int[5]; - try { - header[0] = inputStream.readShort(); - header[1] = inputStream.readInt(); - header[2] = inputStream.readShort(); - header[3] = inputStream.readShort(); - header[4] = inputStream.readInt(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if (header[0] != 0x4D42) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return header; + int[] header = new int[5]; + try { + header[0] = inputStream.readShort(); + header[1] = inputStream.readInt(); + header[2] = inputStream.readShort(); + header[3] = inputStream.readShort(); + header[4] = inputStream.readInt(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if (header[0] != 0x4D42) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return header; } ImageData[] loadFromByteStream() { - int[] fileHeader = loadFileHeader(); - byte[] infoHeader = new byte[BMPHeaderFixedSize]; - try { - inputStream.read(infoHeader); - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } - width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8); - height = (infoHeader[6] & 0xFF) | ((infoHeader[7] & 0xFF) << 8); - bitCount = (infoHeader[10] & 0xFF) | ((infoHeader[11] & 0xFF) << 8); - PaletteData palette = loadPalette(infoHeader); - if (inputStream.getPosition() < fileHeader[4]) { - // Seek to the specified offset - try { - inputStream.skip(fileHeader[4] - inputStream.getPosition()); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - byte[] data = loadData(infoHeader); - int type = SWT.IMAGE_OS2_BMP; - return [ - ImageData.internal_new( - width, - height, - bitCount, - palette, - 4, - data, - 0, - null, - null, - -1, - -1, - type, - 0, - 0, - 0, - 0) - ]; + int[] fileHeader = loadFileHeader(); + byte[] infoHeader = new byte[BMPHeaderFixedSize]; + try { + inputStream.read(infoHeader); + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } + width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8); + height = (infoHeader[6] & 0xFF) | ((infoHeader[7] & 0xFF) << 8); + bitCount = (infoHeader[10] & 0xFF) | ((infoHeader[11] & 0xFF) << 8); + PaletteData palette = loadPalette(infoHeader); + if (inputStream.getPosition() < fileHeader[4]) { + // Seek to the specified offset + try { + inputStream.skip(fileHeader[4] - inputStream.getPosition()); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + byte[] data = loadData(infoHeader); + int type = SWT.IMAGE_OS2_BMP; + return [ + ImageData.internal_new( + width, + height, + bitCount, + palette, + 4, + data, + 0, + null, + null, + -1, + -1, + type, + 0, + 0, + 0, + 0) + ]; } PaletteData loadPalette(byte[] infoHeader) { - if (bitCount <= 8) { - int numColors = 1 << bitCount; - byte[] buf = new byte[numColors * 3]; - try { - if (inputStream.read(buf) != buf.length) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return paletteFromBytes(buf, numColors); - } - if (bitCount == 16) return new PaletteData(0x7C00, 0x3E0, 0x1F); - if (bitCount == 24) return new PaletteData(0xFF, 0xFF00, 0xFF0000); - return new PaletteData(0xFF00, 0xFF0000, 0xFF000000); + if (bitCount <= 8) { + int numColors = 1 << bitCount; + byte[] buf = new byte[numColors * 3]; + try { + if (inputStream.read(buf) != buf.length) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return paletteFromBytes(buf, numColors); + } + if (bitCount == 16) return new PaletteData(0x7C00, 0x3E0, 0x1F); + if (bitCount == 24) return new PaletteData(0xFF, 0xFF00, 0xFF0000); + return new PaletteData(0xFF00, 0xFF0000, 0xFF000000); } PaletteData paletteFromBytes(byte[] bytes, int numColors) { - int bytesOffset = 0; - RGB[] colors = new RGB[numColors]; - for (int i = 0; i < numColors; i++) { - colors[i] = new RGB(bytes[bytesOffset + 2] & 0xFF, - bytes[bytesOffset + 1] & 0xFF, - bytes[bytesOffset] & 0xFF); - bytesOffset += 3; - } - return new PaletteData(colors); + int bytesOffset = 0; + RGB[] colors = new RGB[numColors]; + for (int i = 0; i < numColors; i++) { + colors[i] = new RGB(bytes[bytesOffset + 2] & 0xFF, + bytes[bytesOffset + 1] & 0xFF, + bytes[bytesOffset] & 0xFF); + bytesOffset += 3; + } + return new PaletteData(colors); } /** * Answer a byte array containing the BMP representation of * the given device independent palette. */ static byte[] paletteToBytes(PaletteData pal) { - int n = pal.colors == null ? 0 : (pal.colors.length < 256 ? pal.colors.length : 256); - byte[] bytes = new byte[n * 3]; - int offset = 0; - for (int i = 0; i < n; i++) { - RGB col = pal.colors[i]; - bytes[offset] = cast(byte)col.blue; - bytes[offset + 1] = cast(byte)col.green; - bytes[offset + 2] = cast(byte)col.red; - offset += 3; - } - return bytes; + int n = pal.colors == null ? 0 : (pal.colors.length < 256 ? pal.colors.length : 256); + byte[] bytes = new byte[n * 3]; + int offset = 0; + for (int i = 0; i < n; i++) { + RGB col = pal.colors[i]; + bytes[offset] = cast(byte)col.blue; + bytes[offset + 1] = cast(byte)col.green; + bytes[offset + 2] = cast(byte)col.red; + offset += 3; + } + return bytes; } /** * Unload the given image's data into the given byte stream. * Answer the number of bytes written. */ int unloadData(ImageData image, OutputStream ostr) { - int bmpBpl = 0; - try { - int bpl = (image.width * image.depth + 7) / 8; - bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes - int linesPerBuf = 32678 / bmpBpl; - byte[] buf = new byte[linesPerBuf * bmpBpl]; - byte[] data = image.data; - int imageBpl = image.bytesPerLine; - int dataIndex = imageBpl * (image.height - 1); // Start at last line - if (image.depth == 16) { - for (int y = 0; y < image.height; y += linesPerBuf) { - int count = image.height - y; - if (linesPerBuf < count) count = linesPerBuf; - int bufOffset = 0; - for (int i = 0; i < count; i++) { - for (int wIndex = 0; wIndex < bpl; wIndex += 2) { - buf[bufOffset + wIndex + 1] = data[dataIndex + wIndex + 1]; - buf[bufOffset + wIndex] = data[dataIndex + wIndex]; - } - bufOffset += bmpBpl; - dataIndex -= imageBpl; - } - ostr.write(buf, 0, bufOffset); - } - } else { - for (int y = 0; y < image.height; y += linesPerBuf) { - int tmp = image.height - y; - int count = tmp < linesPerBuf ? tmp : linesPerBuf; - int bufOffset = 0; - for (int i = 0; i < count; i++) { + int bmpBpl = 0; + try { + int bpl = (image.width * image.depth + 7) / 8; + bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes + int linesPerBuf = 32678 / bmpBpl; + byte[] buf = new byte[linesPerBuf * bmpBpl]; + byte[] data = image.data; + int imageBpl = image.bytesPerLine; + int dataIndex = imageBpl * (image.height - 1); // Start at last line + if (image.depth == 16) { + for (int y = 0; y < image.height; y += linesPerBuf) { + int count = image.height - y; + if (linesPerBuf < count) count = linesPerBuf; + int bufOffset = 0; + for (int i = 0; i < count; i++) { + for (int wIndex = 0; wIndex < bpl; wIndex += 2) { + buf[bufOffset + wIndex + 1] = data[dataIndex + wIndex + 1]; + buf[bufOffset + wIndex] = data[dataIndex + wIndex]; + } + bufOffset += bmpBpl; + dataIndex -= imageBpl; + } + ostr.write(buf, 0, bufOffset); + } + } else { + for (int y = 0; y < image.height; y += linesPerBuf) { + int tmp = image.height - y; + int count = tmp < linesPerBuf ? tmp : linesPerBuf; + int bufOffset = 0; + for (int i = 0; i < count; i++) { System.arraycopy(data, dataIndex, buf, bufOffset, bpl); - bufOffset += bmpBpl; - dataIndex -= imageBpl; - } - ostr.write(buf, 0, bufOffset); - } - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return bmpBpl * image.height; + bufOffset += bmpBpl; + dataIndex -= imageBpl; + } + ostr.write(buf, 0, bufOffset); + } + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return bmpBpl * image.height; } /** * Unload a DeviceIndependentImage using Windows .BMP format into the given * byte stream. */ void unloadIntoByteStream(ImageLoader loader) { - ImageData image = loader.data[0]; - byte[] rgbs; - int numCols; - if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8) || - (image.depth == 16) || (image.depth == 24) || (image.depth == 32))) - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - PaletteData pal = image.palette; - if ((image.depth == 16) || (image.depth == 24) || (image.depth == 32)) { - if (!pal.isDirect) - SWT.error(SWT.ERROR_INVALID_IMAGE); - numCols = 0; - rgbs = null; - } else { - if (pal.isDirect) - SWT.error(SWT.ERROR_INVALID_IMAGE); - numCols = pal.colors.length; - rgbs = paletteToBytes(pal); - } - // Fill in file header, except for bfsize, which is done later. - int headersSize = BMPFileHeaderSize + BMPHeaderFixedSize; - int[] fileHeader = new int[5]; - fileHeader[0] = 0x4D42; // Signature - fileHeader[1] = 0; // File size - filled in later - fileHeader[2] = 0; // Reserved 1 - fileHeader[3] = 0; // Reserved 2 - fileHeader[4] = headersSize; // Offset to data - if (rgbs != null) { - fileHeader[4] += rgbs.length; - } + ImageData image = loader.data[0]; + byte[] rgbs; + int numCols; + if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8) || + (image.depth == 16) || (image.depth == 24) || (image.depth == 32))) + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + PaletteData pal = image.palette; + if ((image.depth == 16) || (image.depth == 24) || (image.depth == 32)) { + if (!pal.isDirect) + SWT.error(SWT.ERROR_INVALID_IMAGE); + numCols = 0; + rgbs = null; + } else { + if (pal.isDirect) + SWT.error(SWT.ERROR_INVALID_IMAGE); + numCols = pal.colors.length; + rgbs = paletteToBytes(pal); + } + // Fill in file header, except for bfsize, which is done later. + int headersSize = BMPFileHeaderSize + BMPHeaderFixedSize; + int[] fileHeader = new int[5]; + fileHeader[0] = 0x4D42; // Signature + fileHeader[1] = 0; // File size - filled in later + fileHeader[2] = 0; // Reserved 1 + fileHeader[3] = 0; // Reserved 2 + fileHeader[4] = headersSize; // Offset to data + if (rgbs != null) { + fileHeader[4] += rgbs.length; + } - // Prepare data. This is done first so we don't have to try to rewind - // the stream and fill in the details later. - ByteArrayOutputStream ostr = new ByteArrayOutputStream(); - unloadData(image, ostr); - byte[] data = ostr.toByteArray(); + // Prepare data. This is done first so we don't have to try to rewind + // the stream and fill in the details later. + ByteArrayOutputStream ostr = new ByteArrayOutputStream(); + unloadData(image, ostr); + byte[] data = ostr.toByteArray(); - // Calculate file size - fileHeader[1] = fileHeader[4] + data.length; + // Calculate file size + fileHeader[1] = fileHeader[4] + data.length; - // Write the headers - try { - outputStream.writeShort(fileHeader[0]); - outputStream.writeInt(fileHeader[1]); - outputStream.writeShort(fileHeader[2]); - outputStream.writeShort(fileHeader[3]); - outputStream.writeInt(fileHeader[4]); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - try { - outputStream.writeInt(BMPHeaderFixedSize); - outputStream.writeShort(image.width); - outputStream.writeShort(image.height); - outputStream.writeShort(1); - outputStream.writeShort(cast(short)image.depth); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + // Write the headers + try { + outputStream.writeShort(fileHeader[0]); + outputStream.writeInt(fileHeader[1]); + outputStream.writeShort(fileHeader[2]); + outputStream.writeShort(fileHeader[3]); + outputStream.writeInt(fileHeader[4]); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + try { + outputStream.writeInt(BMPHeaderFixedSize); + outputStream.writeShort(image.width); + outputStream.writeShort(image.height); + outputStream.writeShort(1); + outputStream.writeShort(cast(short)image.depth); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } - // Unload palette - if (numCols > 0) { - try { - outputStream.write(rgbs); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + // Unload palette + if (numCols > 0) { + try { + outputStream.write(rgbs); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - // Unload the data - try { - outputStream.write(data); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + // Unload the data + try { + outputStream.write(data); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } void flipScanLines(byte[] data, int stride, int height) { - int i1 = 0; - int i2 = (height - 1) * stride; - for (int i = 0; i < height / 2; i++) { - for (int index = 0; index < stride; index++) { - byte b = data[index + i1]; - data[index + i1] = data[index + i2]; - data[index + i2] = b; - } - i1 += stride; - i2 -= stride; - } + int i1 = 0; + int i2 = (height - 1) * stride; + for (int i = 0; i < height / 2; i++) { + for (int index = 0; index < stride; index++) { + byte b = data[index + i1]; + data[index + i1] = data[index + i2]; + data[index + i2] = b; + } + i1 += stride; + i2 -= stride; + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PNGFileFormat.d --- a/dwt/internal/image/PNGFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PNGFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -33,164 +33,164 @@ import tango.core.Exception; final class PNGFileFormat : FileFormat { - static final int SIGNATURE_LENGTH = 8; - static final int PRIME = 65521; - PngIhdrChunk headerChunk; - PngPlteChunk paletteChunk; - ImageData imageData; - byte[] data; - byte[] alphaPalette; - byte headerByte1; - byte headerByte2; - int adler; + static final int SIGNATURE_LENGTH = 8; + static final int PRIME = 65521; + PngIhdrChunk headerChunk; + PngPlteChunk paletteChunk; + ImageData imageData; + byte[] data; + byte[] alphaPalette; + byte headerByte1; + byte headerByte2; + int adler; /** * Skip over signature data. This has already been * verified in isFileFormat(). */ void readSignature() { - byte[] signature = new byte[SIGNATURE_LENGTH]; - inputStream.read(signature); + byte[] signature = new byte[SIGNATURE_LENGTH]; + inputStream.read(signature); } /** * Load the PNG image from the byte stream. */ ImageData[] loadFromByteStream() { - try { - readSignature(); - PngChunkReader chunkReader = new PngChunkReader(inputStream); - headerChunk = chunkReader.getIhdrChunk(); - int width = headerChunk.getWidth(), height = headerChunk.getHeight(); - if (width <= 0 || height <= 0) SWT.error(SWT.ERROR_INVALID_IMAGE); - int imageSize = getAlignedBytesPerRow() * height; - data = new byte[imageSize]; - imageData = ImageData.internal_new( - width, - height, - headerChunk.getSwtBitsPerPixel(), - new PaletteData(0, 0, 0), - 4, - data, - 0, - null, - null, - -1, - -1, - SWT.IMAGE_PNG, - 0, - 0, - 0, - 0); + try { + readSignature(); + PngChunkReader chunkReader = new PngChunkReader(inputStream); + headerChunk = chunkReader.getIhdrChunk(); + int width = headerChunk.getWidth(), height = headerChunk.getHeight(); + if (width <= 0 || height <= 0) SWT.error(SWT.ERROR_INVALID_IMAGE); + int imageSize = getAlignedBytesPerRow() * height; + data = new byte[imageSize]; + imageData = ImageData.internal_new( + width, + height, + headerChunk.getSwtBitsPerPixel(), + new PaletteData(0, 0, 0), + 4, + data, + 0, + null, + null, + -1, + -1, + SWT.IMAGE_PNG, + 0, + 0, + 0, + 0); - if (headerChunk.usesDirectColor()) { - imageData.palette = headerChunk.getPaletteData(); - } + if (headerChunk.usesDirectColor()) { + imageData.palette = headerChunk.getPaletteData(); + } - // Read and process chunks until the IEND chunk is encountered. - while (chunkReader.hasMoreChunks()) { - readNextChunk(chunkReader); - } + // Read and process chunks until the IEND chunk is encountered. + while (chunkReader.hasMoreChunks()) { + readNextChunk(chunkReader); + } - return [imageData]; - } catch (IOException e) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - return null; - } + return [imageData]; + } catch (IOException e) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + return null; + } } /** * Read and handle the next chunk of data from the * PNG file. */ void readNextChunk(PngChunkReader chunkReader) { - PngChunk chunk = chunkReader.readNextChunk(); - switch (chunk.getChunkType()) { - case PngChunk.CHUNK_IEND: - break; - case PngChunk.CHUNK_PLTE: - if (!headerChunk.usesDirectColor()) { - paletteChunk = cast(PngPlteChunk) chunk; - imageData.palette = paletteChunk.getPaletteData(); - } - break; - case PngChunk.CHUNK_tRNS: - PngTrnsChunk trnsChunk = cast(PngTrnsChunk) chunk; - if (trnsChunk.getTransparencyType(headerChunk) == - PngTrnsChunk.TRANSPARENCY_TYPE_PIXEL) - { - imageData.transparentPixel = - trnsChunk.getSwtTransparentPixel(headerChunk); - } else { - alphaPalette = trnsChunk.getAlphaValues(headerChunk, paletteChunk); - int transparentCount = 0, transparentPixel = -1; - for (int i = 0; i < alphaPalette.length; i++) { - if ((alphaPalette[i] & 0xFF) != 255) { - transparentCount++; - transparentPixel = i; - } - } - if (transparentCount == 0) { - alphaPalette = null; - } else if (transparentCount == 1 && alphaPalette[transparentPixel] == 0) { - alphaPalette = null; - imageData.transparentPixel = transparentPixel; - } - } - break; - case PngChunk.CHUNK_IDAT: - if (chunkReader.readPixelData()) { - // All IDAT chunks in an image file must be - // sequential. If the pixel data has already - // been read and another IDAT block is encountered, - // then this is an invalid image. - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - // Read in the pixel data for the image. This should - // go through all the image's IDAT chunks. - PngIdatChunk dataChunk = cast(PngIdatChunk) chunk; - readPixelData(dataChunk, chunkReader); - } - break; - default: - if (chunk.isCritical()) { - // All critical chunks must be supported. - SWT.error(SWT.ERROR_NOT_IMPLEMENTED); - } - } + PngChunk chunk = chunkReader.readNextChunk(); + switch (chunk.getChunkType()) { + case PngChunk.CHUNK_IEND: + break; + case PngChunk.CHUNK_PLTE: + if (!headerChunk.usesDirectColor()) { + paletteChunk = cast(PngPlteChunk) chunk; + imageData.palette = paletteChunk.getPaletteData(); + } + break; + case PngChunk.CHUNK_tRNS: + PngTrnsChunk trnsChunk = cast(PngTrnsChunk) chunk; + if (trnsChunk.getTransparencyType(headerChunk) == + PngTrnsChunk.TRANSPARENCY_TYPE_PIXEL) + { + imageData.transparentPixel = + trnsChunk.getSwtTransparentPixel(headerChunk); + } else { + alphaPalette = trnsChunk.getAlphaValues(headerChunk, paletteChunk); + int transparentCount = 0, transparentPixel = -1; + for (int i = 0; i < alphaPalette.length; i++) { + if ((alphaPalette[i] & 0xFF) != 255) { + transparentCount++; + transparentPixel = i; + } + } + if (transparentCount == 0) { + alphaPalette = null; + } else if (transparentCount == 1 && alphaPalette[transparentPixel] == 0) { + alphaPalette = null; + imageData.transparentPixel = transparentPixel; + } + } + break; + case PngChunk.CHUNK_IDAT: + if (chunkReader.readPixelData()) { + // All IDAT chunks in an image file must be + // sequential. If the pixel data has already + // been read and another IDAT block is encountered, + // then this is an invalid image. + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + // Read in the pixel data for the image. This should + // go through all the image's IDAT chunks. + PngIdatChunk dataChunk = cast(PngIdatChunk) chunk; + readPixelData(dataChunk, chunkReader); + } + break; + default: + if (chunk.isCritical()) { + // All critical chunks must be supported. + SWT.error(SWT.ERROR_NOT_IMPLEMENTED); + } + } } void unloadIntoByteStream(ImageLoader loader) { - PngEncoder encoder = new PngEncoder(loader); - encoder.encode(outputStream); + PngEncoder encoder = new PngEncoder(loader); + encoder.encode(outputStream); } bool isFileFormat(LEDataInputStream stream) { - try { - byte[] signature = new byte[SIGNATURE_LENGTH]; - stream.read(signature); - stream.unread(signature); - if ((signature[0] & 0xFF) != 137) return false; //137 - if ((signature[1] & 0xFF) != 80) return false; //P - if ((signature[2] & 0xFF) != 78) return false; //N - if ((signature[3] & 0xFF) != 71) return false; //G - if ((signature[4] & 0xFF) != 13) return false; // - if ((signature[5] & 0xFF) != 10) return false; // - if ((signature[6] & 0xFF) != 26) return false; // - if ((signature[7] & 0xFF) != 10) return false; // - return true; - } catch (Exception e) { - return false; - } + try { + byte[] signature = new byte[SIGNATURE_LENGTH]; + stream.read(signature); + stream.unread(signature); + if ((signature[0] & 0xFF) != 137) return false; //137 + if ((signature[1] & 0xFF) != 80) return false; //P + if ((signature[2] & 0xFF) != 78) return false; //N + if ((signature[3] & 0xFF) != 71) return false; //G + if ((signature[4] & 0xFF) != 13) return false; // + if ((signature[5] & 0xFF) != 10) return false; // + if ((signature[6] & 0xFF) != 26) return false; // + if ((signature[7] & 0xFF) != 10) return false; // + return true; + } catch (Exception e) { + return false; + } } /** * SWT does not support 16-bit depths. If this image uses * 16-bit depths, convert the data to an 8-bit depth. */ byte[] validateBitDepth(byte[] data) { - if (headerChunk.getBitDepth() > 8) { - byte[] result = new byte[data.length / 2]; - compress16BitDepthTo8BitDepth(data, 0, result, 0, result.length); - return result; - } else { - return data; - } + if (headerChunk.getBitDepth() > 8) { + byte[] result = new byte[data.length / 2]; + compress16BitDepthTo8BitDepth(data, 0, result, 0, result.length); + return result; + } else { + return data; + } } /** * SWT does not support greyscale as a color type. For @@ -201,93 +201,93 @@ * data has already been restricted to 8 or less. */ void setPixelData(byte[] data, ImageData imageData) { - switch (headerChunk.getColorType()) { - case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - { - int width = imageData.width; - int height = imageData.height; - int destBytesPerLine = imageData.bytesPerLine; - /* - * If the image uses 16-bit depth, it is converted - * to an 8-bit depth image. - */ - int srcBytesPerLine = getAlignedBytesPerRow(); - if (headerChunk.getBitDepth() > 8) srcBytesPerLine /= 2; + switch (headerChunk.getColorType()) { + case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + { + int width = imageData.width; + int height = imageData.height; + int destBytesPerLine = imageData.bytesPerLine; + /* + * If the image uses 16-bit depth, it is converted + * to an 8-bit depth image. + */ + int srcBytesPerLine = getAlignedBytesPerRow(); + if (headerChunk.getBitDepth() > 8) srcBytesPerLine /= 2; - byte[] rgbData = new byte[destBytesPerLine * height]; - byte[] alphaData = new byte[width * height]; - for (int y = 0; y < height; y++) { - int srcIndex = srcBytesPerLine * y; - int destIndex = destBytesPerLine * y; - int destAlphaIndex = width * y; - for (int x = 0; x < width; x++) { - byte grey = data[srcIndex]; - byte alpha = data[srcIndex + 1]; - rgbData[destIndex + 0] = grey; - rgbData[destIndex + 1] = grey; - rgbData[destIndex + 2] = grey; - alphaData[destAlphaIndex] = alpha; - srcIndex += 2; - destIndex += 3; - destAlphaIndex++; - } - } - imageData.data = rgbData; - imageData.alphaData = alphaData; - break; - } - case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA: - { - int width = imageData.width; - int height = imageData.height; - int destBytesPerLine = imageData.bytesPerLine; - int srcBytesPerLine = getAlignedBytesPerRow(); - /* - * If the image uses 16-bit depth, it is converted - * to an 8-bit depth image. - */ - if (headerChunk.getBitDepth() > 8) srcBytesPerLine /= 2; + byte[] rgbData = new byte[destBytesPerLine * height]; + byte[] alphaData = new byte[width * height]; + for (int y = 0; y < height; y++) { + int srcIndex = srcBytesPerLine * y; + int destIndex = destBytesPerLine * y; + int destAlphaIndex = width * y; + for (int x = 0; x < width; x++) { + byte grey = data[srcIndex]; + byte alpha = data[srcIndex + 1]; + rgbData[destIndex + 0] = grey; + rgbData[destIndex + 1] = grey; + rgbData[destIndex + 2] = grey; + alphaData[destAlphaIndex] = alpha; + srcIndex += 2; + destIndex += 3; + destAlphaIndex++; + } + } + imageData.data = rgbData; + imageData.alphaData = alphaData; + break; + } + case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA: + { + int width = imageData.width; + int height = imageData.height; + int destBytesPerLine = imageData.bytesPerLine; + int srcBytesPerLine = getAlignedBytesPerRow(); + /* + * If the image uses 16-bit depth, it is converted + * to an 8-bit depth image. + */ + if (headerChunk.getBitDepth() > 8) srcBytesPerLine /= 2; - byte[] rgbData = new byte[destBytesPerLine * height]; - byte[] alphaData = new byte[width * height]; - for (int y = 0; y < height; y++) { - int srcIndex = srcBytesPerLine * y; - int destIndex = destBytesPerLine * y; - int destAlphaIndex = width * y; - for (int x = 0; x < width; x++) { - rgbData[destIndex + 0] = data[srcIndex + 0]; - rgbData[destIndex + 1] = data[srcIndex + 1]; - rgbData[destIndex + 2] = data[srcIndex + 2]; - alphaData[destAlphaIndex] = data[srcIndex + 3]; - srcIndex += 4; - destIndex += 3; - destAlphaIndex++; - } - } - imageData.data = rgbData; - imageData.alphaData = alphaData; - break; - } - case PngIhdrChunk.COLOR_TYPE_RGB: - imageData.data = data; - break; - case PngIhdrChunk.COLOR_TYPE_PALETTE: - imageData.data = data; - if (alphaPalette != null) { - int size = imageData.width * imageData.height; - byte[] alphaData = new byte[size]; - byte[] pixelData = new byte[size]; - imageData.getPixels(0, 0, size, pixelData, 0); - for (int i = 0; i < pixelData.length; i++) { - alphaData[i] = alphaPalette[pixelData[i] & 0xFF]; - } - imageData.alphaData = alphaData; - } - break; - default: - imageData.data = data; - break; - } + byte[] rgbData = new byte[destBytesPerLine * height]; + byte[] alphaData = new byte[width * height]; + for (int y = 0; y < height; y++) { + int srcIndex = srcBytesPerLine * y; + int destIndex = destBytesPerLine * y; + int destAlphaIndex = width * y; + for (int x = 0; x < width; x++) { + rgbData[destIndex + 0] = data[srcIndex + 0]; + rgbData[destIndex + 1] = data[srcIndex + 1]; + rgbData[destIndex + 2] = data[srcIndex + 2]; + alphaData[destAlphaIndex] = data[srcIndex + 3]; + srcIndex += 4; + destIndex += 3; + destAlphaIndex++; + } + } + imageData.data = rgbData; + imageData.alphaData = alphaData; + break; + } + case PngIhdrChunk.COLOR_TYPE_RGB: + imageData.data = data; + break; + case PngIhdrChunk.COLOR_TYPE_PALETTE: + imageData.data = data; + if (alphaPalette != null) { + int size = imageData.width * imageData.height; + byte[] alphaData = new byte[size]; + byte[] pixelData = new byte[size]; + imageData.getPixels(0, 0, size, pixelData, 0); + for (int i = 0; i < pixelData.length; i++) { + alphaData[i] = alphaPalette[pixelData[i] & 0xFF]; + } + imageData.alphaData = alphaData; + } + break; + default: + imageData.data = data; + break; + } } /** * PNG supports some color types and bit depths that are @@ -297,43 +297,43 @@ * format. Then assign the data into the ImageData given. */ void setImageDataValues(byte[] data, ImageData imageData) { - byte[] result = validateBitDepth(data); - setPixelData(result, imageData); + byte[] result = validateBitDepth(data); + setPixelData(result, imageData); } /** * Read the image data from the data stream. This must handle * decoding the data, filtering, and interlacing. */ void readPixelData(PngIdatChunk chunk, PngChunkReader chunkReader) { - InputStream stream = new PngInputStream(chunk, chunkReader); - //TEMPORARY CODE + InputStream stream = new PngInputStream(chunk, chunkReader); + //TEMPORARY CODE //PORTING_FIXME - bool use3_2 = false;//System.getProperty("dwt.internal.image.PNGFileFormat_3.2") != null; - InputStream inflaterStream = use3_2 ? null : Compatibility.newInflaterInputStream(stream); - if (inflaterStream != null) { - stream = new BufferedInputStream(inflaterStream); - } else { - stream = new PngDecodingDataStream(stream); - } - int interlaceMethod = headerChunk.getInterlaceMethod(); - if (interlaceMethod == PngIhdrChunk.INTERLACE_METHOD_NONE) { - readNonInterlacedImage(stream); - } else { - readInterlacedImage(stream); - } - /* - * InflaterInputStream does not consume all bytes in the stream - * when it is closed. This may leave unread IDAT chunks. The fix - * is to read all available bytes before closing it. - */ - while (stream.available() > 0) stream.read(); - stream.close(); + bool use3_2 = false;//System.getProperty("dwt.internal.image.PNGFileFormat_3.2") != null; + InputStream inflaterStream = use3_2 ? null : Compatibility.newInflaterInputStream(stream); + if (inflaterStream != null) { + stream = new BufferedInputStream(inflaterStream); + } else { + stream = new PngDecodingDataStream(stream); + } + int interlaceMethod = headerChunk.getInterlaceMethod(); + if (interlaceMethod == PngIhdrChunk.INTERLACE_METHOD_NONE) { + readNonInterlacedImage(stream); + } else { + readInterlacedImage(stream); + } + /* + * InflaterInputStream does not consume all bytes in the stream + * when it is closed. This may leave unread IDAT chunks. The fix + * is to read all available bytes before closing it. + */ + while (stream.available() > 0) stream.read(); + stream.close(); } /** * Answer the number of bytes in a word-aligned row of pixel data. */ int getAlignedBytesPerRow() { - return ((getBytesPerRow(headerChunk.getWidth()) + 3) / 4) * 4; + return ((getBytesPerRow(headerChunk.getWidth()) + 3) / 4) * 4; } /** * Answer the number of bytes in each row of the image @@ -342,7 +342,7 @@ * end of each row. The value of these bits is undefined. */ int getBytesPerRow() { - return getBytesPerRow(headerChunk.getWidth()); + return getBytesPerRow(headerChunk.getWidth()); } /** * Answer the number of bytes needed to represent a pixel. @@ -352,8 +352,8 @@ * isn't byte-aligned. */ int getBytesPerPixel() { - int bitsPerPixel = headerChunk.getBitsPerPixel(); - return (bitsPerPixel + 7) / 8; + int bitsPerPixel = headerChunk.getBitsPerPixel(); + return (bitsPerPixel + 7) / 8; } /** * Answer the number of bytes in a row of the given pixel @@ -362,10 +362,10 @@ * end of each row. The value of these bits is undefined. */ int getBytesPerRow(int rowWidthInPixels) { - int bitsPerPixel = headerChunk.getBitsPerPixel(); - int bitsPerRow = bitsPerPixel * rowWidthInPixels; - int bitsPerByte = 8; - return (bitsPerRow + (bitsPerByte - 1)) / bitsPerByte; + int bitsPerPixel = headerChunk.getBitsPerPixel(); + int bitsPerRow = bitsPerPixel * rowWidthInPixels; + int bitsPerByte = 8; + return (bitsPerRow + (bitsPerByte - 1)) / bitsPerByte; } /** * 1. Read one of the seven frames of interlaced data. @@ -373,81 +373,81 @@ * 3. Notify the image loader's listeners of the frame load. */ void readInterlaceFrame( - InputStream inputStream, - int rowInterval, - int columnInterval, - int startRow, - int startColumn, - int frameCount) + InputStream inputStream, + int rowInterval, + int columnInterval, + int startRow, + int startColumn, + int frameCount) { - int width = headerChunk.getWidth(); - int alignedBytesPerRow = getAlignedBytesPerRow(); - int height = headerChunk.getHeight(); - if (startRow >= height || startColumn >= width) return; + int width = headerChunk.getWidth(); + int alignedBytesPerRow = getAlignedBytesPerRow(); + int height = headerChunk.getHeight(); + if (startRow >= height || startColumn >= width) return; - int pixelsPerRow = (width - startColumn + columnInterval - 1) / columnInterval; - int bytesPerRow = getBytesPerRow(pixelsPerRow); - byte[] row1 = new byte[bytesPerRow]; - byte[] row2 = new byte[bytesPerRow]; - byte[] currentRow = row1; - byte[] lastRow = row2; - for (int row = startRow; row < height; row += rowInterval) { - byte filterType = cast(byte)inputStream.read(); - int read = 0; - while (read != bytesPerRow) { - read += inputStream.read(currentRow, read, bytesPerRow - read); - } - filterRow(currentRow, lastRow, filterType); - if (headerChunk.getBitDepth() >= 8) { - int bytesPerPixel = getBytesPerPixel(); - int dataOffset = (row * alignedBytesPerRow) + (startColumn * bytesPerPixel); - for (int rowOffset = 0; rowOffset < currentRow.length; rowOffset += bytesPerPixel) { - for (int byteOffset = 0; byteOffset < bytesPerPixel; byteOffset++) { - data[dataOffset + byteOffset] = currentRow[rowOffset + byteOffset]; - } - dataOffset += (columnInterval * bytesPerPixel); - } - } else { - int bitsPerPixel = headerChunk.getBitDepth(); - int pixelsPerByte = 8 / bitsPerPixel; - int column = startColumn; - int rowBase = row * alignedBytesPerRow; - int valueMask = 0; - for (int i = 0; i < bitsPerPixel; i++) { - valueMask <<= 1; - valueMask |= 1; - } - int maxShift = 8 - bitsPerPixel; - for (int byteOffset = 0; byteOffset < currentRow.length; byteOffset++) { - for (int bitOffset = maxShift; bitOffset >= 0; bitOffset -= bitsPerPixel) { - if (column < width) { - int dataOffset = rowBase + (column * bitsPerPixel / 8); - int value = (currentRow[byteOffset] >> bitOffset) & valueMask; - int dataShift = maxShift - (bitsPerPixel * (column % pixelsPerByte)); - data[dataOffset] |= value << dataShift; - } - column += columnInterval; - } - } - } - currentRow = (currentRow == row1) ? row2 : row1; - lastRow = (lastRow == row1) ? row2 : row1; - } - setImageDataValues(data, imageData); - fireInterlacedFrameEvent(frameCount); + int pixelsPerRow = (width - startColumn + columnInterval - 1) / columnInterval; + int bytesPerRow = getBytesPerRow(pixelsPerRow); + byte[] row1 = new byte[bytesPerRow]; + byte[] row2 = new byte[bytesPerRow]; + byte[] currentRow = row1; + byte[] lastRow = row2; + for (int row = startRow; row < height; row += rowInterval) { + byte filterType = cast(byte)inputStream.read(); + int read = 0; + while (read != bytesPerRow) { + read += inputStream.read(currentRow, read, bytesPerRow - read); + } + filterRow(currentRow, lastRow, filterType); + if (headerChunk.getBitDepth() >= 8) { + int bytesPerPixel = getBytesPerPixel(); + int dataOffset = (row * alignedBytesPerRow) + (startColumn * bytesPerPixel); + for (int rowOffset = 0; rowOffset < currentRow.length; rowOffset += bytesPerPixel) { + for (int byteOffset = 0; byteOffset < bytesPerPixel; byteOffset++) { + data[dataOffset + byteOffset] = currentRow[rowOffset + byteOffset]; + } + dataOffset += (columnInterval * bytesPerPixel); + } + } else { + int bitsPerPixel = headerChunk.getBitDepth(); + int pixelsPerByte = 8 / bitsPerPixel; + int column = startColumn; + int rowBase = row * alignedBytesPerRow; + int valueMask = 0; + for (int i = 0; i < bitsPerPixel; i++) { + valueMask <<= 1; + valueMask |= 1; + } + int maxShift = 8 - bitsPerPixel; + for (int byteOffset = 0; byteOffset < currentRow.length; byteOffset++) { + for (int bitOffset = maxShift; bitOffset >= 0; bitOffset -= bitsPerPixel) { + if (column < width) { + int dataOffset = rowBase + (column * bitsPerPixel / 8); + int value = (currentRow[byteOffset] >> bitOffset) & valueMask; + int dataShift = maxShift - (bitsPerPixel * (column % pixelsPerByte)); + data[dataOffset] |= value << dataShift; + } + column += columnInterval; + } + } + } + currentRow = (currentRow == row1) ? row2 : row1; + lastRow = (lastRow == row1) ? row2 : row1; + } + setImageDataValues(data, imageData); + fireInterlacedFrameEvent(frameCount); } /** * Read the pixel data for an interlaced image from the * data stream. */ void readInterlacedImage(InputStream inputStream) { - readInterlaceFrame(inputStream, 8, 8, 0, 0, 0); - readInterlaceFrame(inputStream, 8, 8, 0, 4, 1); - readInterlaceFrame(inputStream, 8, 4, 4, 0, 2); - readInterlaceFrame(inputStream, 4, 4, 0, 2, 3); - readInterlaceFrame(inputStream, 4, 2, 2, 0, 4); - readInterlaceFrame(inputStream, 2, 2, 0, 1, 5); - readInterlaceFrame(inputStream, 2, 1, 1, 0, 6); + readInterlaceFrame(inputStream, 8, 8, 0, 0, 0); + readInterlaceFrame(inputStream, 8, 8, 0, 4, 1); + readInterlaceFrame(inputStream, 8, 4, 4, 0, 2); + readInterlaceFrame(inputStream, 4, 4, 0, 2, 3); + readInterlaceFrame(inputStream, 4, 2, 2, 0, 4); + readInterlaceFrame(inputStream, 2, 2, 0, 1, 5); + readInterlaceFrame(inputStream, 2, 1, 1, 0, 6); } /** * Fire an event to let listeners know that an interlaced @@ -456,11 +456,11 @@ * loading, false if there are more frames to come. */ void fireInterlacedFrameEvent(int frameCount) { - if (loader.hasListeners()) { - ImageData image = cast(ImageData) imageData.clone(); - bool finalFrame = frameCount == 6; - loader.notifyListeners(new ImageLoaderEvent(loader, image, frameCount, finalFrame)); - } + if (loader.hasListeners()) { + ImageData image = cast(ImageData) imageData.clone(); + bool finalFrame = frameCount == 6; + loader.notifyListeners(new ImageLoaderEvent(loader, image, frameCount, finalFrame)); + } } /** * Read the pixel data for a non-interlaced image from the @@ -468,27 +468,27 @@ * Update the imageData to reflect the new data. */ void readNonInterlacedImage(InputStream inputStream) { - int dataOffset = 0; - int alignedBytesPerRow = getAlignedBytesPerRow(); - int bytesPerRow = getBytesPerRow(); - byte[] row1 = new byte[bytesPerRow]; - byte[] row2 = new byte[bytesPerRow]; - byte[] currentRow = row1; - byte[] lastRow = row2; - int height = headerChunk.getHeight(); - for (int row = 0; row < height; row++) { - byte filterType = cast(byte)inputStream.read(); - int read = 0; - while (read != bytesPerRow) { - read += inputStream.read(currentRow, read, bytesPerRow - read); - } - filterRow(currentRow, lastRow, filterType); + int dataOffset = 0; + int alignedBytesPerRow = getAlignedBytesPerRow(); + int bytesPerRow = getBytesPerRow(); + byte[] row1 = new byte[bytesPerRow]; + byte[] row2 = new byte[bytesPerRow]; + byte[] currentRow = row1; + byte[] lastRow = row2; + int height = headerChunk.getHeight(); + for (int row = 0; row < height; row++) { + byte filterType = cast(byte)inputStream.read(); + int read = 0; + while (read != bytesPerRow) { + read += inputStream.read(currentRow, read, bytesPerRow - read); + } + filterRow(currentRow, lastRow, filterType); System.arraycopy(currentRow, 0, data, dataOffset, bytesPerRow); - dataOffset += alignedBytesPerRow; - currentRow = (currentRow == row1) ? row2 : row1; - lastRow = (lastRow == row1) ? row2 : row1; - } - setImageDataValues(data, imageData); + dataOffset += alignedBytesPerRow; + currentRow = (currentRow == row1) ? row2 : row1; + lastRow = (lastRow == row1) ? row2 : row1; + } + setImageDataValues(data, imageData); } /** * SWT does not support 16-bit depth color formats. @@ -500,21 +500,21 @@ * byte of the 16-bit value. */ static void compress16BitDepthTo8BitDepth( - byte[] source, - int sourceOffset, - byte[] destination, - int destinationOffset, - int numberOfValues) + byte[] source, + int sourceOffset, + byte[] destination, + int destinationOffset, + int numberOfValues) { - //double multiplier = (Compatibility.pow2(8) - 1) / (Compatibility.pow2(16) - 1); - for (int i = 0; i < numberOfValues; i++) { - int sourceIndex = sourceOffset + (2 * i); - int destinationIndex = destinationOffset + i; - //int value = (source[sourceIndex] << 8) | source[sourceIndex + 1]; - //byte compressedValue = (byte)(value * multiplier); - byte compressedValue = source[sourceIndex]; - destination[destinationIndex] = compressedValue; - } + //double multiplier = (Compatibility.pow2(8) - 1) / (Compatibility.pow2(16) - 1); + for (int i = 0; i < numberOfValues; i++) { + int sourceIndex = sourceOffset + (2 * i); + int destinationIndex = destinationOffset + i; + //int value = (source[sourceIndex] << 8) | source[sourceIndex + 1]; + //byte compressedValue = (byte)(value * multiplier); + byte compressedValue = source[sourceIndex]; + destination[destinationIndex] = compressedValue; + } } /** * SWT does not support 16-bit depth color formats. @@ -526,9 +526,9 @@ * byte of the 16-bit value. */ static int compress16BitDepthTo8BitDepth(int value) { - //double multiplier = (Compatibility.pow2(8) - 1) / (Compatibility.pow2(16) - 1); - //byte compressedValue = (byte)(value * multiplier); - return value >> 8; + //double multiplier = (Compatibility.pow2(8) - 1) / (Compatibility.pow2(16) - 1); + //byte compressedValue = (byte)(value * multiplier); + return value >> 8; } /** * PNG supports four filtering types. These types are applied @@ -536,57 +536,57 @@ * based on the filterType. */ void filterRow(byte[] row, byte[] previousRow, int filterType) { - int byteOffset = headerChunk.getFilterByteOffset(); - switch (filterType) { - case PngIhdrChunk.FILTER_NONE: - break; - case PngIhdrChunk.FILTER_SUB: - for (int i = byteOffset; i < row.length; i++) { - int current = row[i] & 0xFF; - int left = row[i - byteOffset] & 0xFF; - row[i] = cast(byte)((current + left) & 0xFF); - } - break; - case PngIhdrChunk.FILTER_UP: - for (int i = 0; i < row.length; i++) { - int current = row[i] & 0xFF; - int above = previousRow[i] & 0xFF; - row[i] = cast(byte)((current + above) & 0xFF); - } - break; - case PngIhdrChunk.FILTER_AVERAGE: - for (int i = 0; i < row.length; i++) { - int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF; - int above = previousRow[i] & 0xFF; - int current = row[i] & 0xFF; - row[i] = cast(byte)((current + ((left + above) / 2)) & 0xFF); - } - break; - case PngIhdrChunk.FILTER_PAETH: - for (int i = 0; i < row.length; i++) { - int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF; - int aboveLeft = (i < byteOffset) ? 0 : previousRow[i - byteOffset] & 0xFF; - int above = previousRow[i] & 0xFF; + int byteOffset = headerChunk.getFilterByteOffset(); + switch (filterType) { + case PngIhdrChunk.FILTER_NONE: + break; + case PngIhdrChunk.FILTER_SUB: + for (int i = byteOffset; i < row.length; i++) { + int current = row[i] & 0xFF; + int left = row[i - byteOffset] & 0xFF; + row[i] = cast(byte)((current + left) & 0xFF); + } + break; + case PngIhdrChunk.FILTER_UP: + for (int i = 0; i < row.length; i++) { + int current = row[i] & 0xFF; + int above = previousRow[i] & 0xFF; + row[i] = cast(byte)((current + above) & 0xFF); + } + break; + case PngIhdrChunk.FILTER_AVERAGE: + for (int i = 0; i < row.length; i++) { + int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF; + int above = previousRow[i] & 0xFF; + int current = row[i] & 0xFF; + row[i] = cast(byte)((current + ((left + above) / 2)) & 0xFF); + } + break; + case PngIhdrChunk.FILTER_PAETH: + for (int i = 0; i < row.length; i++) { + int left = (i < byteOffset) ? 0 : row[i - byteOffset] & 0xFF; + int aboveLeft = (i < byteOffset) ? 0 : previousRow[i - byteOffset] & 0xFF; + int above = previousRow[i] & 0xFF; - int a = Math.abs(above - aboveLeft); - int b = Math.abs(left - aboveLeft); - int c = Math.abs(left - aboveLeft + above - aboveLeft); + int a = Math.abs(above - aboveLeft); + int b = Math.abs(left - aboveLeft); + int c = Math.abs(left - aboveLeft + above - aboveLeft); - int preductor = 0; - if (a <= b && a <= c) { - preductor = left; - } else if (b <= c) { - preductor = above; - } else { - preductor = aboveLeft; - } + int preductor = 0; + if (a <= b && a <= c) { + preductor = left; + } else if (b <= c) { + preductor = above; + } else { + preductor = aboveLeft; + } - int currentValue = row[i] & 0xFF; - row[i] = cast(byte) ((currentValue + preductor) & 0xFF); - } - break; + int currentValue = row[i] & 0xFF; + row[i] = cast(byte) ((currentValue + preductor) & 0xFF); + } + break; default: - } + } } -} \ No newline at end of file +} diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngChunk.d --- a/dwt/internal/image/PngChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -24,56 +24,56 @@ import tango.text.convert.Format; class PngChunk { - byte[] reference; + byte[] reference; - static const int LENGTH_OFFSET = 0; - static const int TYPE_OFFSET = 4; - static const int DATA_OFFSET = 8; + static const int LENGTH_OFFSET = 0; + static const int TYPE_OFFSET = 4; + static const int DATA_OFFSET = 8; - static const int TYPE_FIELD_LENGTH = 4; - static const int LENGTH_FIELD_LENGTH = 4; - static const int MIN_LENGTH = 12; + static const int TYPE_FIELD_LENGTH = 4; + static const int LENGTH_FIELD_LENGTH = 4; + static const int MIN_LENGTH = 12; - static const int CHUNK_UNKNOWN = -1; - // Critical chunks. - static const int CHUNK_IHDR = 0; - static const int CHUNK_PLTE = 1; - static const int CHUNK_IDAT = 2; - static const int CHUNK_IEND = 3; - // Non-critical chunks. - static const int CHUNK_tRNS = 5; + static const int CHUNK_UNKNOWN = -1; + // Critical chunks. + static const int CHUNK_IHDR = 0; + static const int CHUNK_PLTE = 1; + static const int CHUNK_IDAT = 2; + static const int CHUNK_IEND = 3; + // Non-critical chunks. + static const int CHUNK_tRNS = 5; - static const byte[] TYPE_IHDR = cast(byte[])"IHDR";//{(byte) 'I', (byte) 'H', (byte) 'D', (byte) 'R'}; - static const byte[] TYPE_PLTE = cast(byte[])"PLTE";//{(byte) 'P', (byte) 'L', (byte) 'T', (byte) 'E'}; - static const byte[] TYPE_IDAT = cast(byte[])"IDAT";//{(byte) 'I', (byte) 'D', (byte) 'A', (byte) 'T'}; - static const byte[] TYPE_IEND = cast(byte[])"IEND";//{(byte) 'I', (byte) 'E', (byte) 'N', (byte) 'D'}; - static const byte[] TYPE_tRNS = cast(byte[])"tRNS";//{(byte) 't', (byte) 'R', (byte) 'N', (byte) 'S'}; + static const byte[] TYPE_IHDR = cast(byte[])"IHDR";//{(byte) 'I', (byte) 'H', (byte) 'D', (byte) 'R'}; + static const byte[] TYPE_PLTE = cast(byte[])"PLTE";//{(byte) 'P', (byte) 'L', (byte) 'T', (byte) 'E'}; + static const byte[] TYPE_IDAT = cast(byte[])"IDAT";//{(byte) 'I', (byte) 'D', (byte) 'A', (byte) 'T'}; + static const byte[] TYPE_IEND = cast(byte[])"IEND";//{(byte) 'I', (byte) 'E', (byte) 'N', (byte) 'D'}; + static const byte[] TYPE_tRNS = cast(byte[])"tRNS";//{(byte) 't', (byte) 'R', (byte) 'N', (byte) 'S'}; - static /*const*/ int[] CRC_TABLE; + static /*const*/ int[] CRC_TABLE; public static void static_this() { - CRC_TABLE = new int[256]; - for (int i = 0; i < 256; i++) { - CRC_TABLE[i] = i; - for (int j = 0; j < 8; j++) { - if ((CRC_TABLE[i] & 0x1) == 0) { - CRC_TABLE[i] = (CRC_TABLE[i] >> 1) & 0x7FFFFFFF; - } else { - CRC_TABLE[i] = 0xEDB88320 ^ ((CRC_TABLE[i] >> 1) & 0x7FFFFFFF); - } - } - } - } + CRC_TABLE = new int[256]; + for (int i = 0; i < 256; i++) { + CRC_TABLE[i] = i; + for (int j = 0; j < 8; j++) { + if ((CRC_TABLE[i] & 0x1) == 0) { + CRC_TABLE[i] = (CRC_TABLE[i] >> 1) & 0x7FFFFFFF; + } else { + CRC_TABLE[i] = 0xEDB88320 ^ ((CRC_TABLE[i] >> 1) & 0x7FFFFFFF); + } + } + } + } - int length; + int length; /** * Construct a PngChunk using the reference bytes * given. */ this(byte[] reference) { - setReference(reference); - if (reference.length < LENGTH_OFFSET + LENGTH_FIELD_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); - length = getInt32(LENGTH_OFFSET); + setReference(reference); + if (reference.length < LENGTH_OFFSET + LENGTH_FIELD_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); + length = getInt32(LENGTH_OFFSET); } /** @@ -81,22 +81,22 @@ * data bytes. */ this(int dataLength) { - this(new byte[MIN_LENGTH + dataLength]); - setLength(dataLength); + this(new byte[MIN_LENGTH + dataLength]); + setLength(dataLength); } /** * Get the PngChunk's reference byteArray; */ byte[] getReference() { - return reference; + return reference; } /** * Set the PngChunk's reference byteArray; */ void setReference(byte[] reference) { - this.reference = reference; + this.reference = reference; } /** @@ -104,10 +104,10 @@ * array at the given offset. */ int getInt16(int offset) { - int answer = 0; - answer |= (reference[offset] & 0xFF) << 8; - answer |= (reference[offset + 1] & 0xFF); - return answer; + int answer = 0; + answer |= (reference[offset] & 0xFF) << 8; + answer |= (reference[offset + 1] & 0xFF); + return answer; } /** @@ -115,8 +115,8 @@ * array at the given offset. */ void setInt16(int offset, int value) { - reference[offset] = cast(byte) ((value >> 8) & 0xFF); - reference[offset + 1] = cast(byte) (value & 0xFF); + reference[offset] = cast(byte) ((value >> 8) & 0xFF); + reference[offset + 1] = cast(byte) (value & 0xFF); } /** @@ -124,12 +124,12 @@ * array at the given offset. */ int getInt32(int offset) { - int answer = 0; - answer |= (reference[offset] & 0xFF) << 24; - answer |= (reference[offset + 1] & 0xFF) << 16; - answer |= (reference[offset + 2] & 0xFF) << 8; - answer |= (reference[offset + 3] & 0xFF); - return answer; + int answer = 0; + answer |= (reference[offset] & 0xFF) << 24; + answer |= (reference[offset + 1] & 0xFF) << 16; + answer |= (reference[offset + 2] & 0xFF) << 8; + answer |= (reference[offset + 3] & 0xFF); + return answer; } /** @@ -137,10 +137,10 @@ * array at the given offset. */ void setInt32(int offset, int value) { - reference[offset] = cast(byte) ((value >> 24) & 0xFF); - reference[offset + 1] = cast(byte) ((value >> 16) & 0xFF); - reference[offset + 2] = cast(byte) ((value >> 8) & 0xFF); - reference[offset + 3] = cast(byte) (value & 0xFF); + reference[offset] = cast(byte) ((value >> 24) & 0xFF); + reference[offset + 1] = cast(byte) ((value >> 16) & 0xFF); + reference[offset + 2] = cast(byte) ((value >> 8) & 0xFF); + reference[offset + 3] = cast(byte) (value & 0xFF); } /** @@ -148,7 +148,7 @@ * This is not the length of the entire chunk. */ int getLength() { - return length; + return length; } /** @@ -156,8 +156,8 @@ * This is not the length of the entire chunk. */ void setLength(int value) { - setInt32(LENGTH_OFFSET, value); - length = value; + setInt32(LENGTH_OFFSET, value); + length = value; } /** @@ -185,9 +185,9 @@ * Public chunk types are defined by the PNG Development Group. */ void setType(byte[] value) { - if (value.length != TYPE_FIELD_LENGTH) { - SWT.error (SWT.ERROR_INVALID_ARGUMENT); - } + if (value.length != TYPE_FIELD_LENGTH) { + SWT.error (SWT.ERROR_INVALID_ARGUMENT); + } System.arraycopy(value, 0, reference, TYPE_OFFSET, TYPE_FIELD_LENGTH); } @@ -195,10 +195,10 @@ * Get the chunk's data. */ byte[] getData() { - int dataLength = getLength(); - if (reference.length < MIN_LENGTH + dataLength) { - SWT.error (SWT.ERROR_INVALID_RANGE); - } + int dataLength = getLength(); + if (reference.length < MIN_LENGTH + dataLength) { + SWT.error (SWT.ERROR_INVALID_RANGE); + } byte[] data = new byte[dataLength]; System.arraycopy(reference, DATA_OFFSET, data, 0, dataLength); return data; @@ -213,9 +213,9 @@ * value of the data array given. */ void setData(byte[] data) { - setLength(data.length); + setLength(data.length); System.arraycopy(data, 0, reference, DATA_OFFSET, data.length); - setCRC(computeCRC()); + setCRC(computeCRC()); } /** @@ -224,8 +224,8 @@ * value before making this call. */ int getCRC() { - int crcOffset = DATA_OFFSET + getLength(); - return getInt32(crcOffset); + int crcOffset = DATA_OFFSET + getLength(); + return getInt32(crcOffset); } /** @@ -234,15 +234,15 @@ * value before making this call. */ void setCRC(int value) { - int crcOffset = DATA_OFFSET + getLength(); - setInt32(crcOffset, value); + int crcOffset = DATA_OFFSET + getLength(); + setInt32(crcOffset, value); } /** * Get the chunk's total size including the length, type, and crc fields. */ int getSize() { - return MIN_LENGTH + getLength(); + return MIN_LENGTH + getLength(); } /** @@ -251,46 +251,46 @@ * chunk. */ bool checkCRC() { - int crc = computeCRC(); - int storedCRC = getCRC(); - return crc == storedCRC; + int crc = computeCRC(); + int storedCRC = getCRC(); + return crc == storedCRC; } /** * Answer the CRC value of chunk's data. */ int computeCRC() { - int crc = 0xFFFFFFFF; - int start = TYPE_OFFSET; - int stop = DATA_OFFSET + getLength(); - for (int i = start; i < stop; i++) { - int index = (crc ^ reference[i]) & 0xFF; - crc = CRC_TABLE[index] ^ ((crc >> 8) & 0x00FFFFFF); - } - return ~crc; + int crc = 0xFFFFFFFF; + int start = TYPE_OFFSET; + int stop = DATA_OFFSET + getLength(); + for (int i = start; i < stop; i++) { + int index = (crc ^ reference[i]) & 0xFF; + crc = CRC_TABLE[index] ^ ((crc >> 8) & 0x00FFFFFF); + } + return ~crc; } bool typeMatchesArray(byte[] array) { - for (int i = 0; i < TYPE_FIELD_LENGTH; i++) { - if (reference[TYPE_OFFSET + i] != array[i]){ - return false; - } - } - return true; + for (int i = 0; i < TYPE_FIELD_LENGTH; i++) { + if (reference[TYPE_OFFSET + i] != array[i]){ + return false; + } + } + return true; } bool isCritical() { - char c = cast(char) getTypeBytes()[0]; - return 'A' <= c && c <= 'Z'; + char c = cast(char) getTypeBytes()[0]; + return 'A' <= c && c <= 'Z'; } int getChunkType() { - if (typeMatchesArray(TYPE_IHDR)) return CHUNK_IHDR; - if (typeMatchesArray(TYPE_PLTE)) return CHUNK_PLTE; - if (typeMatchesArray(TYPE_IDAT)) return CHUNK_IDAT; - if (typeMatchesArray(TYPE_IEND)) return CHUNK_IEND; - if (typeMatchesArray(TYPE_tRNS)) return CHUNK_tRNS; - return CHUNK_UNKNOWN; + if (typeMatchesArray(TYPE_IHDR)) return CHUNK_IHDR; + if (typeMatchesArray(TYPE_PLTE)) return CHUNK_PLTE; + if (typeMatchesArray(TYPE_IDAT)) return CHUNK_IDAT; + if (typeMatchesArray(TYPE_IEND)) return CHUNK_IEND; + if (typeMatchesArray(TYPE_tRNS)) return CHUNK_tRNS; + return CHUNK_UNKNOWN; } /** @@ -298,61 +298,61 @@ * If unable to read a chunk, return null. */ static PngChunk readNextFromStream(LEDataInputStream stream) { - try { - int headerLength = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH; - byte[] headerBytes = new byte[headerLength]; - int result = stream.read(headerBytes, 0, headerLength); - stream.unread(headerBytes); - if (result != headerLength) return null; + try { + int headerLength = LENGTH_FIELD_LENGTH + TYPE_FIELD_LENGTH; + byte[] headerBytes = new byte[headerLength]; + int result = stream.read(headerBytes, 0, headerLength); + stream.unread(headerBytes); + if (result != headerLength) return null; - PngChunk tempChunk = new PngChunk(headerBytes); + PngChunk tempChunk = new PngChunk(headerBytes); - int chunkLength = tempChunk.getSize(); - byte[] chunk = new byte[chunkLength]; - result = stream.read(chunk, 0, chunkLength); - if (result != chunkLength) return null; + int chunkLength = tempChunk.getSize(); + byte[] chunk = new byte[chunkLength]; + result = stream.read(chunk, 0, chunkLength); + if (result != chunkLength) return null; - switch (tempChunk.getChunkType()) { - case CHUNK_IHDR: - return new PngIhdrChunk(chunk); - case CHUNK_PLTE: - return new PngPlteChunk(chunk); - case CHUNK_IDAT: - return new PngIdatChunk(chunk); - case CHUNK_IEND: - return new PngIendChunk(chunk); - case CHUNK_tRNS: - return new PngTrnsChunk(chunk); - default: - return new PngChunk(chunk); - } - } catch (IOException e) { - return null; - } + switch (tempChunk.getChunkType()) { + case CHUNK_IHDR: + return new PngIhdrChunk(chunk); + case CHUNK_PLTE: + return new PngPlteChunk(chunk); + case CHUNK_IDAT: + return new PngIdatChunk(chunk); + case CHUNK_IEND: + return new PngIendChunk(chunk); + case CHUNK_tRNS: + return new PngTrnsChunk(chunk); + default: + return new PngChunk(chunk); + } + } catch (IOException e) { + return null; + } } /** * Answer whether the chunk is a valid PNG chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { - if (reference.length < MIN_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (reference.length < MIN_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); - byte[] type = getTypeBytes(); + byte[] type = getTypeBytes(); - // The third character MUST be upper case. - char c = cast(char) type[2]; - if (!('A' <= c && c <= 'Z')) SWT.error(SWT.ERROR_INVALID_IMAGE); + // The third character MUST be upper case. + char c = cast(char) type[2]; + if (!('A' <= c && c <= 'Z')) SWT.error(SWT.ERROR_INVALID_IMAGE); - // All characters must be letters. - for (int i = 0; i < TYPE_FIELD_LENGTH; i++) { - c = cast(char) type[i]; - if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - } + // All characters must be letters. + for (int i = 0; i < TYPE_FIELD_LENGTH; i++) { + c = cast(char) type[i]; + if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + } - // The stored CRC must match the data's computed CRC. - if (!checkCRC()) SWT.error(SWT.ERROR_INVALID_IMAGE); + // The stored CRC must match the data's computed CRC. + if (!checkCRC()) SWT.error(SWT.ERROR_INVALID_IMAGE); } /** @@ -370,12 +370,12 @@ * @return a string representation of the event */ public char[] toString() { - char[] buffer = Format( "{\n\tLength: {}\n\tType: {}{}\n\tCRC: {:X}\n}", + char[] buffer = Format( "{\n\tLength: {}\n\tType: {}{}\n\tCRC: {:X}\n}", getLength(), cast(char[]) getTypeBytes(), contributeToString(), getCRC()); - return buffer; + return buffer; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngChunkReader.d --- a/dwt/internal/image/PngChunkReader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngChunkReader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -20,19 +20,19 @@ import dwt.internal.image.PngChunk; public class PngChunkReader { - LEDataInputStream inputStream; - PngFileReadState readState; - PngIhdrChunk headerChunk; - PngPlteChunk paletteChunk; + LEDataInputStream inputStream; + PngFileReadState readState; + PngIhdrChunk headerChunk; + PngPlteChunk paletteChunk; this(LEDataInputStream inputStream) { - this.inputStream = inputStream; - readState = new PngFileReadState(); - headerChunk = null; + this.inputStream = inputStream; + readState = new PngFileReadState(); + headerChunk = null; } PngIhdrChunk getIhdrChunk() { - if (headerChunk is null) { + if (headerChunk is null) { PngChunk chunk = PngChunk.readNextFromStream(inputStream); if (chunk is null) SWT.error(SWT.ERROR_INVALID_IMAGE); if(( headerChunk = cast(PngIhdrChunk) chunk ) !is null ){ @@ -41,38 +41,38 @@ else{ SWT.error(SWT.ERROR_INVALID_IMAGE); } - } - return headerChunk; + } + return headerChunk; } PngChunk readNextChunk() { - if (headerChunk is null) return getIhdrChunk(); + if (headerChunk is null) return getIhdrChunk(); - PngChunk chunk = PngChunk.readNextFromStream(inputStream); - if (chunk is null) SWT.error(SWT.ERROR_INVALID_IMAGE); - switch (chunk.getChunkType()) { - case PngChunk.CHUNK_tRNS: - (cast(PngTrnsChunk) chunk).validate(readState, headerChunk, paletteChunk); - break; - case PngChunk.CHUNK_PLTE: - chunk.validate(readState, headerChunk); - paletteChunk = cast(PngPlteChunk) chunk; - break; - default: - chunk.validate(readState, headerChunk); - } - if (readState.readIDAT && !(chunk.getChunkType() == PngChunk.CHUNK_IDAT)) { - readState.readPixelData = true; - } - return chunk; + PngChunk chunk = PngChunk.readNextFromStream(inputStream); + if (chunk is null) SWT.error(SWT.ERROR_INVALID_IMAGE); + switch (chunk.getChunkType()) { + case PngChunk.CHUNK_tRNS: + (cast(PngTrnsChunk) chunk).validate(readState, headerChunk, paletteChunk); + break; + case PngChunk.CHUNK_PLTE: + chunk.validate(readState, headerChunk); + paletteChunk = cast(PngPlteChunk) chunk; + break; + default: + chunk.validate(readState, headerChunk); + } + if (readState.readIDAT && !(chunk.getChunkType() == PngChunk.CHUNK_IDAT)) { + readState.readPixelData = true; + } + return chunk; } bool readPixelData() { - return readState.readPixelData; + return readState.readPixelData; } bool hasMoreChunks() { - return !readState.readIEND; + return !readState.readIEND; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngDecodingDataStream.d --- a/dwt/internal/image/PngDecodingDataStream.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngDecodingDataStream.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -18,24 +18,24 @@ public class PngDecodingDataStream : InputStream { alias InputStream.read read; - InputStream stream; - byte currentByte; - int nextBitIndex; + InputStream stream; + byte currentByte; + int nextBitIndex; - PngLzBlockReader lzBlockReader; - int adlerValue; + PngLzBlockReader lzBlockReader; + int adlerValue; - static final int PRIME = 65521; - static final int MAX_BIT = 7; + static final int PRIME = 65521; + static final int MAX_BIT = 7; this(InputStream stream) { - super(); - this.stream = stream; - nextBitIndex = MAX_BIT + 1; - adlerValue = 1; - lzBlockReader = new PngLzBlockReader(this); - readCompressedDataHeader(); - lzBlockReader.readNextBlockHeader(); + super(); + this.stream = stream; + nextBitIndex = MAX_BIT + 1; + adlerValue = 1; + lzBlockReader = new PngLzBlockReader(this); + readCompressedDataHeader(); + lzBlockReader.readNextBlockHeader(); } /** @@ -46,91 +46,91 @@ * the method will read them and ensure that they are empty. */ void assertImageDataAtEnd() { - lzBlockReader.assertCompressedDataAtEnd(); + lzBlockReader.assertCompressedDataAtEnd(); } public void close() { - assertImageDataAtEnd(); - checkAdler(); + assertImageDataAtEnd(); + checkAdler(); } int getNextIdatBits(int length) { - int value = 0; - for (int i = 0; i < length; i++) { - value |= (getNextIdatBit() << i); - } - return value; + int value = 0; + for (int i = 0; i < length; i++) { + value |= (getNextIdatBit() << i); + } + return value; } int getNextIdatBit() { - if (nextBitIndex > MAX_BIT) { - currentByte = getNextIdatByte(); - nextBitIndex = 0; - } - return (currentByte & (1 << nextBitIndex)) >> nextBitIndex++; + if (nextBitIndex > MAX_BIT) { + currentByte = getNextIdatByte(); + nextBitIndex = 0; + } + return (currentByte & (1 << nextBitIndex)) >> nextBitIndex++; } byte getNextIdatByte() { - byte nextByte = cast(byte)stream.read(); - nextBitIndex = MAX_BIT + 1; - return nextByte; + byte nextByte = cast(byte)stream.read(); + nextBitIndex = MAX_BIT + 1; + return nextByte; } void updateAdler(byte value) { - int low = adlerValue & 0xFFFF; - int high = (adlerValue >> 16) & 0xFFFF; - int valueInt = value & 0xFF; - low = (low + valueInt) % PRIME; - high = (low + high) % PRIME; - adlerValue = (high << 16) | low; + int low = adlerValue & 0xFFFF; + int high = (adlerValue >> 16) & 0xFFFF; + int valueInt = value & 0xFF; + low = (low + valueInt) % PRIME; + high = (low + high) % PRIME; + adlerValue = (high << 16) | low; } public override int read() { - byte nextDecodedByte = lzBlockReader.getNextByte(); - updateAdler(nextDecodedByte); - return nextDecodedByte & 0xFF; + byte nextDecodedByte = lzBlockReader.getNextByte(); + updateAdler(nextDecodedByte); + return nextDecodedByte & 0xFF; } public override int read(byte[] buffer, int off, int len) { - for (int i = 0; i < len; i++) { - int b = read(); - if (b == -1) return i; - buffer[off + i] = cast(byte)b; - } - return len; + for (int i = 0; i < len; i++) { + int b = read(); + if (b == -1) return i; + buffer[off + i] = cast(byte)b; + } + return len; } void error() { - SWT.error(SWT.ERROR_INVALID_IMAGE); + SWT.error(SWT.ERROR_INVALID_IMAGE); } private void readCompressedDataHeader() { - byte headerByte1 = getNextIdatByte(); - byte headerByte2 = getNextIdatByte(); + byte headerByte1 = getNextIdatByte(); + byte headerByte2 = getNextIdatByte(); - int number = ((headerByte1 & 0xFF) << 8) | (headerByte2 & 0xFF); - if (number % 31 != 0) error(); + int number = ((headerByte1 & 0xFF) << 8) | (headerByte2 & 0xFF); + if (number % 31 != 0) error(); - int compressionMethod = headerByte1 & 0x0F; - if (compressionMethod != 8) error(); + int compressionMethod = headerByte1 & 0x0F; + if (compressionMethod != 8) error(); - int windowSizeHint = (headerByte1 & 0xF0) >> 4; - if (windowSizeHint > 7) error(); - int windowSize = (1 << (windowSizeHint + 8)); - lzBlockReader.setWindowSize(windowSize); + int windowSizeHint = (headerByte1 & 0xF0) >> 4; + if (windowSizeHint > 7) error(); + int windowSize = (1 << (windowSizeHint + 8)); + lzBlockReader.setWindowSize(windowSize); - int dictionary = (headerByte2 & (1 << 5)); - if (dictionary != 0) error(); + int dictionary = (headerByte2 & (1 << 5)); + if (dictionary != 0) error(); -// int compressionLevel = (headerByte2 & 0xC0) >> 6; +// int compressionLevel = (headerByte2 & 0xC0) >> 6; } void checkAdler() { - int storedAdler = ((getNextIdatByte() & 0xFF) << 24) - | ((getNextIdatByte() & 0xFF) << 16) - | ((getNextIdatByte() & 0xFF) << 8) - | (getNextIdatByte() & 0xFF); - if (storedAdler != adlerValue) error(); + int storedAdler = ((getNextIdatByte() & 0xFF) << 24) + | ((getNextIdatByte() & 0xFF) << 16) + | ((getNextIdatByte() & 0xFF) << 8) + | (getNextIdatByte() & 0xFF); + if (storedAdler != adlerValue) error(); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngDeflater.d --- a/dwt/internal/image/PngDeflater.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngDeflater.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -14,24 +14,24 @@ public class PngDeflater { - static const int BASE = 65521; - static const int WINDOW = 32768; - static const int MIN_LENGTH = 3; - static const int MAX_MATCHES = 32; - static const int HASH = 8209; + static const int BASE = 65521; + static const int WINDOW = 32768; + static const int MIN_LENGTH = 3; + static const int MAX_MATCHES = 32; + static const int HASH = 8209; - byte[] istr; - int inLength; + byte[] istr; + int inLength; ByteArrayOutputStream bytes; - int adler32 = 1; + int adler32 = 1; - int buffer, bitCount; + int buffer, bitCount; - Link[HASH] hashtable;// = new Link[HASH]; - Link[WINDOW] window;// = new Link[WINDOW]; - int nextWindow; + Link[HASH] hashtable;// = new Link[HASH]; + Link[WINDOW] window;// = new Link[WINDOW]; + int nextWindow; public this(){ bytes = new ByteArrayOutputStream(1024); @@ -39,30 +39,30 @@ class Link { - int hash, value; - Link previous, next; + int hash, value; + Link previous, next; - this() { + this() { - this.hash = 0; - this.value = 0; - this.previous = null; - this.next = null; + this.hash = 0; + this.value = 0; + this.previous = null; + this.next = null; - } + } } class Match { - int length, distance; + int length, distance; - this(int length, int distance) { + this(int length, int distance) { - this.length = length; - this.distance = distance; + this.length = length; + this.distance = distance; - } + } } @@ -105,14 +105,14 @@ static class Code { - int code, extraBits, min, max; + int code, extraBits, min, max; - this(int code, int extraBits, int min, int max) { + this(int code, int extraBits, int min, int max) { - this.code = code; - this.extraBits = extraBits; - this.min = min; - this.max = max; + this.code = code; + this.extraBits = extraBits; + this.min = min; + this.max = max; } @@ -188,433 +188,433 @@ void writeShortLSB(ByteArrayOutputStream baos, int theShort) { - byte byte1 = cast(byte) (theShort & 0xff); - byte byte2 = cast(byte) ((theShort >> 8) & 0xff); - byte[] temp = [byte1, byte2]; - baos.write(temp, 0, 2); + byte byte1 = cast(byte) (theShort & 0xff); + byte byte2 = cast(byte) ((theShort >> 8) & 0xff); + byte[] temp = [byte1, byte2]; + baos.write(temp, 0, 2); } void writeInt(ByteArrayOutputStream baos, int theInt) { - byte byte1 = cast(byte) ((theInt >> 24) & 0xff); - byte byte2 = cast(byte) ((theInt >> 16) & 0xff); - byte byte3 = cast(byte) ((theInt >> 8) & 0xff); - byte byte4 = cast(byte) (theInt & 0xff); - byte[] temp = [byte1, byte2, byte3, byte4]; - baos.write(temp, 0, 4); + byte byte1 = cast(byte) ((theInt >> 24) & 0xff); + byte byte2 = cast(byte) ((theInt >> 16) & 0xff); + byte byte3 = cast(byte) ((theInt >> 8) & 0xff); + byte byte4 = cast(byte) (theInt & 0xff); + byte[] temp = [byte1, byte2, byte3, byte4]; + baos.write(temp, 0, 4); } void updateAdler(byte value) { - int low = adler32 & 0xffff; - int high = (adler32 >> 16) & 0xffff; - int valueInt = value & 0xff; - low = (low + valueInt) % BASE; - high = (low + high) % BASE; - adler32 = (high << 16) | low; + int low = adler32 & 0xffff; + int high = (adler32 >> 16) & 0xffff; + int valueInt = value & 0xff; + low = (low + valueInt) % BASE; + high = (low + high) % BASE; + adler32 = (high << 16) | low; } int hash(byte[] bytes) { - int hash = ((bytes[0] & 0xff) << 24 | (bytes[1] & 0xff) << 16 | (bytes[2] & 0xff) << 8) % HASH; - if (hash < 0) { - hash = hash + HASH; - } - return hash; + int hash = ((bytes[0] & 0xff) << 24 | (bytes[1] & 0xff) << 16 | (bytes[2] & 0xff) << 8) % HASH; + if (hash < 0) { + hash = hash + HASH; + } + return hash; } void writeBits(int value, int count) { - buffer |= value << bitCount; - bitCount += count; - if (bitCount >= 16) { - bytes.write(cast(byte) buffer); - bytes.write(cast(byte) (buffer >>> 8)); - buffer >>>= 16; - bitCount -= 16; - } + buffer |= value << bitCount; + bitCount += count; + if (bitCount >= 16) { + bytes.write(cast(byte) buffer); + bytes.write(cast(byte) (buffer >>> 8)); + buffer >>>= 16; + bitCount -= 16; + } } void alignToByte() { - if (bitCount > 0) { - bytes.write(cast(byte) buffer); - if (bitCount > 8) bytes.write(cast(byte) (buffer >>> 8)); - } - buffer = 0; - bitCount = 0; + if (bitCount > 0) { + bytes.write(cast(byte) buffer); + if (bitCount > 8) bytes.write(cast(byte) (buffer >>> 8)); + } + buffer = 0; + bitCount = 0; } void outputLiteral(byte literal) { - int i = literal & 0xff; + int i = literal & 0xff; - if (i <= 143) { - // 0 through 143 are 8 bits long starting at 00110000 - writeBits(mirrorBytes[0x30 + i], 8); - } - else { - // 144 through 255 are 9 bits long starting at 110010000 - writeBits(1 + 2 * mirrorBytes[0x90 - 144 + i], 9); - } + if (i <= 143) { + // 0 through 143 are 8 bits long starting at 00110000 + writeBits(mirrorBytes[0x30 + i], 8); + } + else { + // 144 through 255 are 9 bits long starting at 110010000 + writeBits(1 + 2 * mirrorBytes[0x90 - 144 + i], 9); + } } Code findCode(int value, Code[] codes) { - int i, j, k; + int i, j, k; - i = -1; - j = codes.length; - while (true) { - k = (j + i) / 2; - if (value < codes[k].min) { - j = k; - } - else if (value > codes[k].max) { - i = k; - } - else { - return codes[k]; - } - } + i = -1; + j = codes.length; + while (true) { + k = (j + i) / 2; + if (value < codes[k].min) { + j = k; + } + else if (value > codes[k].max) { + i = k; + } + else { + return codes[k]; + } + } } void outputMatch(int length, int distance) { - Code d, l; - int thisLength; + Code d, l; + int thisLength; - while (length > 0) { + while (length > 0) { - // we can transmit matches of lengths 3 through 258 inclusive - // so if length exceeds 258, we must transmit in several steps, - // with 258 or less in each step + // we can transmit matches of lengths 3 through 258 inclusive + // so if length exceeds 258, we must transmit in several steps, + // with 258 or less in each step - if (length > 260) { - thisLength = 258; - } - else if (length <= 258) { - thisLength = length; - } - else { - thisLength = length - 3; - } + if (length > 260) { + thisLength = 258; + } + else if (length <= 258) { + thisLength = length; + } + else { + thisLength = length - 3; + } - length = length - thisLength; + length = length - thisLength; - // find length code - l = findCode(thisLength, lengthCodes); + // find length code + l = findCode(thisLength, lengthCodes); - // transmit the length code - // 256 through 279 are 7 bits long starting at 0000000 - // 280 through 287 are 8 bits long starting at 11000000 - if (l.code <= 279) { - writeBits(mirrorBytes[(l.code - 256) * 2], 7); - } - else { - writeBits(mirrorBytes[0xc0 - 280 + l.code], 8); - } + // transmit the length code + // 256 through 279 are 7 bits long starting at 0000000 + // 280 through 287 are 8 bits long starting at 11000000 + if (l.code <= 279) { + writeBits(mirrorBytes[(l.code - 256) * 2], 7); + } + else { + writeBits(mirrorBytes[0xc0 - 280 + l.code], 8); + } - // transmit the extra bits - if (l.extraBits != 0) { - writeBits(thisLength - l.min, l.extraBits); - } + // transmit the extra bits + if (l.extraBits != 0) { + writeBits(thisLength - l.min, l.extraBits); + } - // find distance code - d = findCode(distance, distanceCodes); + // find distance code + d = findCode(distance, distanceCodes); - // transmit the distance code - // 5 bits long starting at 00000 - writeBits(mirrorBytes[d.code * 8], 5); + // transmit the distance code + // 5 bits long starting at 00000 + writeBits(mirrorBytes[d.code * 8], 5); - // transmit the extra bits - if (d.extraBits != 0) { - writeBits(distance - d.min, d.extraBits); - } + // transmit the extra bits + if (d.extraBits != 0) { + writeBits(distance - d.min, d.extraBits); + } - } + } } Match findLongestMatch(int position, Link firstPosition) { - Link link = firstPosition; - int numberOfMatches = 0; - Match bestMatch = new Match(-1, -1); + Link link = firstPosition; + int numberOfMatches = 0; + Match bestMatch = new Match(-1, -1); - while (true) { + while (true) { - int matchPosition = link.value; + int matchPosition = link.value; - if (position - matchPosition < WINDOW && matchPosition != 0) { + if (position - matchPosition < WINDOW && matchPosition != 0) { - int i; + int i; - for (i = 1; position + i < inLength; i++) { - if (istr[position + i] != istr[matchPosition + i]) { - break; - } - } + for (i = 1; position + i < inLength; i++) { + if (istr[position + i] != istr[matchPosition + i]) { + break; + } + } - if (i >= MIN_LENGTH) { + if (i >= MIN_LENGTH) { - if (i > bestMatch.length) { - bestMatch.length = i; - bestMatch.distance = position - matchPosition; - } + if (i > bestMatch.length) { + bestMatch.length = i; + bestMatch.distance = position - matchPosition; + } - numberOfMatches = numberOfMatches + 1; + numberOfMatches = numberOfMatches + 1; - if (numberOfMatches == MAX_MATCHES) { - break; - } + if (numberOfMatches == MAX_MATCHES) { + break; + } - } + } - } + } - link = link.next; - if (link == null) { - break; - } + link = link.next; + if (link == null) { + break; + } - } + } - if (bestMatch.length < MIN_LENGTH || bestMatch.distance < 1 || bestMatch.distance > WINDOW) { - return null; - } + if (bestMatch.length < MIN_LENGTH || bestMatch.distance < 1 || bestMatch.distance > WINDOW) { + return null; + } - return bestMatch; + return bestMatch; } void updateHashtable(int to, int from) { - byte[] data = new byte[3]; - int hashval; - Link temp; + byte[] data = new byte[3]; + int hashval; + Link temp; - for (int i = to; i < from; i++) { + for (int i = to; i < from; i++) { - if (i + MIN_LENGTH > inLength) { - break; - } + if (i + MIN_LENGTH > inLength) { + break; + } - data[0] = istr[i]; - data[1] = istr[i + 1]; - data[2] = istr[i + 2]; + data[0] = istr[i]; + data[1] = istr[i + 1]; + data[2] = istr[i + 2]; - hashval = hash(data); + hashval = hash(data); - if (window[nextWindow].previous != null) { - window[nextWindow].previous.next = null; - } - else if (window[nextWindow].hash != 0) { - hashtable[window[nextWindow].hash].next = null; - } + if (window[nextWindow].previous != null) { + window[nextWindow].previous.next = null; + } + else if (window[nextWindow].hash != 0) { + hashtable[window[nextWindow].hash].next = null; + } - window[nextWindow].hash = hashval; - window[nextWindow].value = i; - window[nextWindow].previous = null; - temp = window[nextWindow].next = hashtable[hashval].next; - hashtable[hashval].next = window[nextWindow]; - if (temp != null) { - temp.previous = window[nextWindow]; - } + window[nextWindow].hash = hashval; + window[nextWindow].value = i; + window[nextWindow].previous = null; + temp = window[nextWindow].next = hashtable[hashval].next; + hashtable[hashval].next = window[nextWindow]; + if (temp != null) { + temp.previous = window[nextWindow]; + } - nextWindow = nextWindow + 1; - if (nextWindow == WINDOW) { - nextWindow = 0; - } + nextWindow = nextWindow + 1; + if (nextWindow == WINDOW) { + nextWindow = 0; + } - } + } } void compress() { - int position, newPosition; - byte[] data = new byte[3]; - int hashval; - for (int i = 0; i < HASH; i++) { - hashtable[i] = new Link(); - } - for (int i = 0; i < WINDOW; i++) { - window[i] = new Link(); - } - nextWindow = 0; - Link firstPosition; - Match match; - int deferredPosition = -1; - Match deferredMatch = null; + int position, newPosition; + byte[] data = new byte[3]; + int hashval; + for (int i = 0; i < HASH; i++) { + hashtable[i] = new Link(); + } + for (int i = 0; i < WINDOW; i++) { + window[i] = new Link(); + } + nextWindow = 0; + Link firstPosition; + Match match; + int deferredPosition = -1; + Match deferredMatch = null; - writeBits(0x01, 1); // BFINAL = 0x01 (final block) - writeBits(0x01, 2); // BTYPE = 0x01 (compression with fixed Huffman codes) + writeBits(0x01, 1); // BFINAL = 0x01 (final block) + writeBits(0x01, 2); // BTYPE = 0x01 (compression with fixed Huffman codes) - // just output first byte so we never match at zero - outputLiteral(istr[0]); - position = 1; + // just output first byte so we never match at zero + outputLiteral(istr[0]); + position = 1; - while (position < inLength) { + while (position < inLength) { - if (inLength - position < MIN_LENGTH) { - outputLiteral(istr[position]); - position = position + 1; - continue; - } + if (inLength - position < MIN_LENGTH) { + outputLiteral(istr[position]); + position = position + 1; + continue; + } - data[0] = istr[position]; - data[1] = istr[position + 1]; - data[2] = istr[position + 2]; + data[0] = istr[position]; + data[1] = istr[position + 1]; + data[2] = istr[position + 2]; - hashval = hash(data); - firstPosition = hashtable[hashval]; + hashval = hash(data); + firstPosition = hashtable[hashval]; - match = findLongestMatch(position, firstPosition); + match = findLongestMatch(position, firstPosition); - updateHashtable(position, position + 1); + updateHashtable(position, position + 1); - if (match != null) { + if (match != null) { - if (deferredMatch != null) { - if (match.length > deferredMatch.length + 1) { - // output literal at deferredPosition - outputLiteral(istr[deferredPosition]); - // defer this match - deferredPosition = position; - deferredMatch = match; - position = position + 1; - } - else { - // output deferredMatch - outputMatch(deferredMatch.length, deferredMatch.distance); - newPosition = deferredPosition + deferredMatch.length; - deferredPosition = -1; - deferredMatch = null; - updateHashtable(position + 1, newPosition); - position = newPosition; - } - } - else { - // defer this match - deferredPosition = position; - deferredMatch = match; - position = position + 1; - } + if (deferredMatch != null) { + if (match.length > deferredMatch.length + 1) { + // output literal at deferredPosition + outputLiteral(istr[deferredPosition]); + // defer this match + deferredPosition = position; + deferredMatch = match; + position = position + 1; + } + else { + // output deferredMatch + outputMatch(deferredMatch.length, deferredMatch.distance); + newPosition = deferredPosition + deferredMatch.length; + deferredPosition = -1; + deferredMatch = null; + updateHashtable(position + 1, newPosition); + position = newPosition; + } + } + else { + // defer this match + deferredPosition = position; + deferredMatch = match; + position = position + 1; + } - } + } - else { + else { - // no match found - if (deferredMatch != null) { - outputMatch(deferredMatch.length, deferredMatch.distance); - newPosition = deferredPosition + deferredMatch.length; - deferredPosition = -1; - deferredMatch = null; - updateHashtable(position + 1, newPosition); - position = newPosition; - } - else { - outputLiteral(istr[position]); - position = position + 1; - } + // no match found + if (deferredMatch != null) { + outputMatch(deferredMatch.length, deferredMatch.distance); + newPosition = deferredPosition + deferredMatch.length; + deferredPosition = -1; + deferredMatch = null; + updateHashtable(position + 1, newPosition); + position = newPosition; + } + else { + outputLiteral(istr[position]); + position = position + 1; + } - } + } - } + } - writeBits(0, 7); // end of block code - alignToByte(); + writeBits(0, 7); // end of block code + alignToByte(); } void compressHuffmanOnly() { - int position; + int position; - writeBits(0x01, 1); // BFINAL = 0x01 (final block) - writeBits(0x01, 2); // BTYPE = 0x01 (compression with fixed Huffman codes) + writeBits(0x01, 1); // BFINAL = 0x01 (final block) + writeBits(0x01, 2); // BTYPE = 0x01 (compression with fixed Huffman codes) - for (position = 0; position < inLength;) { + for (position = 0; position < inLength;) { - outputLiteral(istr[position]); - position = position + 1; + outputLiteral(istr[position]); + position = position + 1; - } + } - writeBits(0, 7); // end of block code - alignToByte(); + writeBits(0, 7); // end of block code + alignToByte(); } void store() { - // stored blocks are limited to 0xffff bytes + // stored blocks are limited to 0xffff bytes - int start = 0; - int length = inLength; - int blockLength; - int BFINAL = 0x00; // BFINAL = 0x00 or 0x01 (if final block), BTYPE = 0x00 (no compression) + int start = 0; + int length = inLength; + int blockLength; + int BFINAL = 0x00; // BFINAL = 0x00 or 0x01 (if final block), BTYPE = 0x00 (no compression) - while (length > 0) { + while (length > 0) { - if (length < 65535) { - blockLength = length; - BFINAL = 0x01; - } - else { - blockLength = 65535; - BFINAL = 0x00; - } + if (length < 65535) { + blockLength = length; + BFINAL = 0x01; + } + else { + blockLength = 65535; + BFINAL = 0x00; + } - // write data header - bytes.write(cast(byte) BFINAL); - writeShortLSB(bytes, blockLength); // LEN - writeShortLSB(bytes, blockLength ^ 0xffff); // NLEN (one's complement of LEN) + // write data header + bytes.write(cast(byte) BFINAL); + writeShortLSB(bytes, blockLength); // LEN + writeShortLSB(bytes, blockLength ^ 0xffff); // NLEN (one's complement of LEN) - // write actual data - bytes.write(istr, start, blockLength); + // write actual data + bytes.write(istr, start, blockLength); - length = length - blockLength; - start = start + blockLength; + length = length - blockLength; + start = start + blockLength; - } + } } public byte[] deflate(byte[] input) { - istr = input; - inLength = input.length; + istr = input; + inLength = input.length; - // write zlib header - bytes.write(cast(byte) 0x78); // window size = 0x70 (32768), compression method = 0x08 - bytes.write(cast(byte) 0x9C); // compression level = 0x80 (default), check bits = 0x1C + // write zlib header + bytes.write(cast(byte) 0x78); // window size = 0x70 (32768), compression method = 0x08 + bytes.write(cast(byte) 0x9C); // compression level = 0x80 (default), check bits = 0x1C - // compute checksum - for (int i = 0; i < inLength; i++) { - updateAdler(istr[i]); - } + // compute checksum + for (int i = 0; i < inLength; i++) { + updateAdler(istr[i]); + } - //store(); + //store(); - //compressHuffmanOnly(); + //compressHuffmanOnly(); - compress(); + compress(); - // write checksum - writeInt(bytes, adler32); + // write checksum + writeInt(bytes, adler32); - return bytes.toByteArray(); + return bytes.toByteArray(); } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngEncoder.d --- a/dwt/internal/image/PngEncoder.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngEncoder.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -23,334 +23,334 @@ final class PngEncoder { - static const byte SIGNATURE[] = [cast(byte) '\211', cast(byte) 'P', cast(byte) 'N', cast(byte) 'G', cast(byte) '\r', cast(byte) '\n', cast(byte) '\032', cast(byte) '\n']; - static const byte TAG_IHDR[] = [cast(byte) 'I', cast(byte) 'H', cast(byte) 'D', cast(byte) 'R']; - static const byte TAG_PLTE[] = [cast(byte) 'P', cast(byte) 'L', cast(byte) 'T', cast(byte) 'E']; - static const byte TAG_TRNS[] = [cast(byte) 't', cast(byte) 'R', cast(byte) 'N', cast(byte) 'S']; - static const byte TAG_IDAT[] = [cast(byte) 'I', cast(byte) 'D', cast(byte) 'A', cast(byte) 'T']; - static const byte TAG_IEND[] = [cast(byte) 'I', cast(byte) 'E', cast(byte) 'N', cast(byte) 'D']; + static const byte SIGNATURE[] = [cast(byte) '\211', cast(byte) 'P', cast(byte) 'N', cast(byte) 'G', cast(byte) '\r', cast(byte) '\n', cast(byte) '\032', cast(byte) '\n']; + static const byte TAG_IHDR[] = [cast(byte) 'I', cast(byte) 'H', cast(byte) 'D', cast(byte) 'R']; + static const byte TAG_PLTE[] = [cast(byte) 'P', cast(byte) 'L', cast(byte) 'T', cast(byte) 'E']; + static const byte TAG_TRNS[] = [cast(byte) 't', cast(byte) 'R', cast(byte) 'N', cast(byte) 'S']; + static const byte TAG_IDAT[] = [cast(byte) 'I', cast(byte) 'D', cast(byte) 'A', cast(byte) 'T']; + static const byte TAG_IEND[] = [cast(byte) 'I', cast(byte) 'E', cast(byte) 'N', cast(byte) 'D']; - ByteArrayOutputStream bytes; - PngChunk chunk; + ByteArrayOutputStream bytes; + PngChunk chunk; - ImageLoader loader; - ImageData data; - int transparencyType; + ImageLoader loader; + ImageData data; + int transparencyType; - int width, height, bitDepth, colorType; + int width, height, bitDepth, colorType; - int compressionMethod = 0; - int filterMethod = 0; - int interlaceMethod = 0; + int compressionMethod = 0; + int filterMethod = 0; + int interlaceMethod = 0; public this(ImageLoader loader) { this.bytes = new ByteArrayOutputStream(1024); - this.loader = loader; - this.data = loader.data[0]; - this.transparencyType = data.getTransparencyType(); + this.loader = loader; + this.data = loader.data[0]; + this.transparencyType = data.getTransparencyType(); - this.width = data.width; - this.height = data.height; + this.width = data.width; + this.height = data.height; - this.bitDepth = 8; + this.bitDepth = 8; - this.colorType = 2; + this.colorType = 2; - if (data.palette.isDirect) { - if (transparencyType == SWT.TRANSPARENCY_ALPHA) { - this.colorType = 6; - } - } - else { - this.colorType = 3; - } + if (data.palette.isDirect) { + if (transparencyType == SWT.TRANSPARENCY_ALPHA) { + this.colorType = 6; + } + } + else { + this.colorType = 3; + } - if (!(colorType == 2 || colorType == 3 || colorType == 6)) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (!(colorType == 2 || colorType == 3 || colorType == 6)) SWT.error(SWT.ERROR_INVALID_IMAGE); } void writeShort(ByteArrayOutputStream baos, int theShort) { - byte byte1 = cast(byte) ((theShort >> 8) & 0xff); - byte byte2 = cast(byte) (theShort & 0xff); - byte[] temp = [byte1, byte2]; - baos.write(temp, 0, 2); + byte byte1 = cast(byte) ((theShort >> 8) & 0xff); + byte byte2 = cast(byte) (theShort & 0xff); + byte[] temp = [byte1, byte2]; + baos.write(temp, 0, 2); } void writeInt(ByteArrayOutputStream baos, int theInt) { - byte byte1 = cast(byte) ((theInt >> 24) & 0xff); - byte byte2 = cast(byte) ((theInt >> 16) & 0xff); - byte byte3 = cast(byte) ((theInt >> 8) & 0xff); - byte byte4 = cast(byte) (theInt & 0xff); - byte[] temp = [byte1, byte2, byte3, byte4]; - baos.write(temp, 0, 4); + byte byte1 = cast(byte) ((theInt >> 24) & 0xff); + byte byte2 = cast(byte) ((theInt >> 16) & 0xff); + byte byte3 = cast(byte) ((theInt >> 8) & 0xff); + byte byte4 = cast(byte) (theInt & 0xff); + byte[] temp = [byte1, byte2, byte3, byte4]; + baos.write(temp, 0, 4); } void writeChunk(byte[] tag, byte[] buffer) { - int bufferLength = (buffer != null) ? buffer.length : 0; + int bufferLength = (buffer != null) ? buffer.length : 0; - chunk = new PngChunk(bufferLength); + chunk = new PngChunk(bufferLength); - writeInt(bytes, bufferLength); - bytes.write(tag, 0, 4); - chunk.setType(tag); - if (bufferLength != 0) { - bytes.write(buffer, 0, bufferLength); - chunk.setData(buffer); - } - else { - chunk.setCRC(chunk.computeCRC()); - } - writeInt(bytes, chunk.getCRC()); + writeInt(bytes, bufferLength); + bytes.write(tag, 0, 4); + chunk.setType(tag); + if (bufferLength != 0) { + bytes.write(buffer, 0, bufferLength); + chunk.setData(buffer); + } + else { + chunk.setCRC(chunk.computeCRC()); + } + writeInt(bytes, chunk.getCRC()); } void writeSignature() { - bytes.write(SIGNATURE, 0, 8); + bytes.write(SIGNATURE, 0, 8); } void writeHeader() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(13); + ByteArrayOutputStream baos = new ByteArrayOutputStream(13); - writeInt(baos, width); - writeInt(baos, height); - baos.write(bitDepth); - baos.write(colorType); - baos.write(compressionMethod); - baos.write(filterMethod); - baos.write(interlaceMethod); + writeInt(baos, width); + writeInt(baos, height); + baos.write(bitDepth); + baos.write(colorType); + baos.write(compressionMethod); + baos.write(filterMethod); + baos.write(interlaceMethod); - writeChunk(TAG_IHDR, baos.toByteArray()); + writeChunk(TAG_IHDR, baos.toByteArray()); } void writePalette() { - RGB[] RGBs = data.palette.getRGBs(); + RGB[] RGBs = data.palette.getRGBs(); - if (RGBs.length > 256) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (RGBs.length > 256) SWT.error(SWT.ERROR_INVALID_IMAGE); - ByteArrayOutputStream baos = new ByteArrayOutputStream(RGBs.length); + ByteArrayOutputStream baos = new ByteArrayOutputStream(RGBs.length); - for (int i = 0; i < RGBs.length; i++) { + for (int i = 0; i < RGBs.length; i++) { - baos.write(cast(byte) RGBs[i].red); - baos.write(cast(byte) RGBs[i].green); - baos.write(cast(byte) RGBs[i].blue); + baos.write(cast(byte) RGBs[i].red); + baos.write(cast(byte) RGBs[i].green); + baos.write(cast(byte) RGBs[i].blue); - } + } - writeChunk(TAG_PLTE, baos.toByteArray()); + writeChunk(TAG_PLTE, baos.toByteArray()); } void writeTransparency() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - switch (transparencyType) { + switch (transparencyType) { - case SWT.TRANSPARENCY_ALPHA: + case SWT.TRANSPARENCY_ALPHA: - int pixelValue, alphaValue; + int pixelValue, alphaValue; - byte[] alphas = new byte[data.palette.getRGBs().length]; + byte[] alphas = new byte[data.palette.getRGBs().length]; - for (int y = 0; y < height; y++) { + for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { + for (int x = 0; x < width; x++) { - pixelValue = data.getPixel(x, y); - alphaValue = data.getAlpha(x, y); + pixelValue = data.getPixel(x, y); + alphaValue = data.getAlpha(x, y); - alphas[pixelValue] = cast(byte) alphaValue; + alphas[pixelValue] = cast(byte) alphaValue; - } + } - } + } - baos.write(alphas, 0, alphas.length); + baos.write(alphas, 0, alphas.length); - break; + break; - case SWT.TRANSPARENCY_PIXEL: + case SWT.TRANSPARENCY_PIXEL: - int pixel = data.transparentPixel; + int pixel = data.transparentPixel; - if (colorType == 2) { + if (colorType == 2) { - int redMask = data.palette.redMask; - int redShift = data.palette.redShift; - int greenMask = data.palette.greenMask; - int greenShift = data.palette.greenShift; - int blueShift = data.palette.blueShift; - int blueMask = data.palette.blueMask; + int redMask = data.palette.redMask; + int redShift = data.palette.redShift; + int greenMask = data.palette.greenMask; + int greenShift = data.palette.greenShift; + int blueShift = data.palette.blueShift; + int blueMask = data.palette.blueMask; - int r = pixel & redMask; - r = (redShift < 0) ? r >>> -redShift : r << redShift; - int g = pixel & greenMask; - g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; - int b = pixel & blueMask; - b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; + int r = pixel & redMask; + r = (redShift < 0) ? r >>> -redShift : r << redShift; + int g = pixel & greenMask; + g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; + int b = pixel & blueMask; + b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; - writeShort(baos, r); - writeShort(baos, g); - writeShort(baos, b); + writeShort(baos, r); + writeShort(baos, g); + writeShort(baos, b); - } + } - if (colorType == 3) { + if (colorType == 3) { - byte[] padding = new byte[pixel + 1]; + byte[] padding = new byte[pixel + 1]; - for (int i = 0; i < pixel; i++) { + for (int i = 0; i < pixel; i++) { - padding[i] = cast(byte) 255; + padding[i] = cast(byte) 255; - } + } - padding[pixel] = cast(byte) 0; + padding[pixel] = cast(byte) 0; - baos.write(padding, 0, padding.length); + baos.write(padding, 0, padding.length); - } + } - break; + break; default: - } + } - writeChunk(TAG_TRNS, baos.toByteArray()); + writeChunk(TAG_TRNS, baos.toByteArray()); } void writeImageData() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); + ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); - if (colorType == 3) { + if (colorType == 3) { - int[] lineData = new int[width]; + int[] lineData = new int[width]; - for (int y = 0; y < height; y++) { + for (int y = 0; y < height; y++) { - byte filter[] = [0]; - baos.write(filter, 0, 1); + byte filter[] = [0]; + baos.write(filter, 0, 1); - data.getPixels(0, y, width, lineData, 0); + data.getPixels(0, y, width, lineData, 0); - for (int x = 0; x < lineData.length; x++) { + for (int x = 0; x < lineData.length; x++) { - baos.write(cast(byte) lineData[x]); + baos.write(cast(byte) lineData[x]); - } + } - } + } - } + } - else { + else { - int[] lineData = new int[width]; - byte[] alphaData = new byte[width]; + int[] lineData = new int[width]; + byte[] alphaData = new byte[width]; - int redMask = data.palette.redMask; - int redShift = data.palette.redShift; - int greenMask = data.palette.greenMask; - int greenShift = data.palette.greenShift; - int blueShift = data.palette.blueShift; - int blueMask = data.palette.blueMask; + int redMask = data.palette.redMask; + int redShift = data.palette.redShift; + int greenMask = data.palette.greenMask; + int greenShift = data.palette.greenShift; + int blueShift = data.palette.blueShift; + int blueMask = data.palette.blueMask; - for (int y = 0; y < height; y++) { + for (int y = 0; y < height; y++) { - byte filter[] = [0]; - baos.write(filter, 0, 1); + byte filter[] = [0]; + baos.write(filter, 0, 1); - data.getPixels(0, y, width, lineData, 0); + data.getPixels(0, y, width, lineData, 0); - if (colorType == 6) { - data.getAlphas(0, y, width, alphaData, 0); - } + if (colorType == 6) { + data.getAlphas(0, y, width, alphaData, 0); + } - for (int x = 0; x < lineData.length; x++) { + for (int x = 0; x < lineData.length; x++) { - int pixel = lineData[x]; + int pixel = lineData[x]; - int r = pixel & redMask; - r = (redShift < 0) ? r >>> -redShift : r << redShift; - int g = pixel & greenMask; - g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; - int b = pixel & blueMask; - b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; + int r = pixel & redMask; + r = (redShift < 0) ? r >>> -redShift : r << redShift; + int g = pixel & greenMask; + g = (greenShift < 0) ? g >>> -greenShift : g << greenShift; + int b = pixel & blueMask; + b = (blueShift < 0) ? b >>> -blueShift : b << blueShift; - byte pixels[] = [cast(byte) r, cast(byte) g, cast(byte) b]; - baos.write(pixels, 0, 3); + byte pixels[] = [cast(byte) r, cast(byte) g, cast(byte) b]; + baos.write(pixels, 0, 3); - if (colorType == 6) { + if (colorType == 6) { - byte alpha[] = [alphaData[x]]; - baos.write(alpha, 0, 1); + byte alpha[] = [alphaData[x]]; + baos.write(alpha, 0, 1); - } + } - } + } - } + } - } + } - PngDeflater deflater = new PngDeflater(); - byte[] compressed = deflater.deflate(baos.toByteArray()); + PngDeflater deflater = new PngDeflater(); + byte[] compressed = deflater.deflate(baos.toByteArray()); - writeChunk(TAG_IDAT, compressed); + writeChunk(TAG_IDAT, compressed); } void writeEnd() { - writeChunk(TAG_IEND, null); + writeChunk(TAG_IEND, null); } public void encode(LEDataOutputStream outputStream) { - try { + try { - writeSignature(); - writeHeader(); + writeSignature(); + writeHeader(); - if (colorType == 3) { - writePalette(); - } + if (colorType == 3) { + writePalette(); + } - bool transparencyAlpha = (transparencyType == SWT.TRANSPARENCY_ALPHA); - bool transparencyPixel = (transparencyType == SWT.TRANSPARENCY_PIXEL); - bool type2Transparency = (colorType == 2 && transparencyPixel); - bool type3Transparency = (colorType == 3 && (transparencyAlpha || transparencyPixel)); + bool transparencyAlpha = (transparencyType == SWT.TRANSPARENCY_ALPHA); + bool transparencyPixel = (transparencyType == SWT.TRANSPARENCY_PIXEL); + bool type2Transparency = (colorType == 2 && transparencyPixel); + bool type3Transparency = (colorType == 3 && (transparencyAlpha || transparencyPixel)); - if (type2Transparency || type3Transparency) { - writeTransparency(); - } + if (type2Transparency || type3Transparency) { + writeTransparency(); + } - writeImageData(); - writeEnd(); + writeImageData(); + writeEnd(); - outputStream.write(bytes.toByteArray()); + outputStream.write(bytes.toByteArray()); - } + } - catch (IOException e) { + catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); + SWT.error(SWT.ERROR_IO, e); - } + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngFileReadState.d --- a/dwt/internal/image/PngFileReadState.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngFileReadState.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2004 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 @@ -12,14 +12,14 @@ class PngFileReadState { - bool readIHDR; - bool readPLTE; - bool readIDAT; - bool readIEND; + bool readIHDR; + bool readPLTE; + bool readIDAT; + bool readIEND; - // Non - critical chunks - bool readTRNS; + // Non - critical chunks + bool readTRNS; - // Set to true after IDATs have been read. - bool readPixelData; + // Set to true after IDATs have been read. + bool readPixelData; } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngHuffmanTable.d --- a/dwt/internal/image/PngHuffmanTable.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngHuffmanTable.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -13,112 +13,112 @@ import dwt.internal.image.PngDecodingDataStream; public class PngHuffmanTable { - CodeLengthInfo[] codeLengthInfo; - int[] codeValues; + CodeLengthInfo[] codeLengthInfo; + int[] codeValues; - static const int MAX_CODE_LENGTH = 15; - static const int BAD_CODE = 0xFFFFFFF; - static const int incs[] = [1391376, 463792, 198768, 86961, 33936, 13776, 4592, 1968, 861, 336, 112, 48, 21, 7, 3, 1]; + static const int MAX_CODE_LENGTH = 15; + static const int BAD_CODE = 0xFFFFFFF; + static const int incs[] = [1391376, 463792, 198768, 86961, 33936, 13776, 4592, 1968, 861, 336, 112, 48, 21, 7, 3, 1]; this (int[] lengths) { - initialize(lengths); - generateTable(lengths); + initialize(lengths); + generateTable(lengths); } private void initialize(int[] lengths) { - codeValues = new int[lengths.length]; - for (int i = 0; i < codeValues.length; i++) { - codeValues[i] = i; - } + codeValues = new int[lengths.length]; + for (int i = 0; i < codeValues.length; i++) { + codeValues[i] = i; + } - // minCodesByLength[n] : The smallest Huffman code of length n + 1. - // maxCodesByLength[n] : The largest Huffman code of length n + 1. - // indexesByLength[n] : Index into the values array. First value with a code of length n + 1. - codeLengthInfo = new CodeLengthInfo[MAX_CODE_LENGTH]; - for (int i = 0; i < MAX_CODE_LENGTH; i++) { - codeLengthInfo[i] = new CodeLengthInfo(); - codeLengthInfo[i].length = i; - codeLengthInfo[i].baseIndex = 0; - codeLengthInfo[i].min = BAD_CODE; - codeLengthInfo[i].max = -1; - } + // minCodesByLength[n] : The smallest Huffman code of length n + 1. + // maxCodesByLength[n] : The largest Huffman code of length n + 1. + // indexesByLength[n] : Index into the values array. First value with a code of length n + 1. + codeLengthInfo = new CodeLengthInfo[MAX_CODE_LENGTH]; + for (int i = 0; i < MAX_CODE_LENGTH; i++) { + codeLengthInfo[i] = new CodeLengthInfo(); + codeLengthInfo[i].length = i; + codeLengthInfo[i].baseIndex = 0; + codeLengthInfo[i].min = BAD_CODE; + codeLengthInfo[i].max = -1; + } } private void generateTable(int[] lengths) { - // Sort the values using shellsort. Primary key is code size. Secondary key is value. - int codeValuesTemp; - for (int k = 0; k < 16; k++) { - for (int h = incs[k], i = h; i < lengths.length; i++) { - int v = lengths[i]; - codeValuesTemp = codeValues[i]; - int j = i; - while (j >= h && (lengths[j - h] > v || (lengths[j - h] == v && codeValues[j - h] > codeValuesTemp))) { - lengths[j] = lengths[j - h]; - codeValues[j] = codeValues[j - h]; - j -= h; - } - lengths[j] = v; - codeValues[j] = codeValuesTemp; - } - } + // Sort the values using shellsort. Primary key is code size. Secondary key is value. + int codeValuesTemp; + for (int k = 0; k < 16; k++) { + for (int h = incs[k], i = h; i < lengths.length; i++) { + int v = lengths[i]; + codeValuesTemp = codeValues[i]; + int j = i; + while (j >= h && (lengths[j - h] > v || (lengths[j - h] == v && codeValues[j - h] > codeValuesTemp))) { + lengths[j] = lengths[j - h]; + codeValues[j] = codeValues[j - h]; + j -= h; + } + lengths[j] = v; + codeValues[j] = codeValuesTemp; + } + } - // These values in these arrays correspond to the elements of the - // "values" array. The Huffman code for codeValues[N] is codes[N] - // and the length of the code is lengths[N]. - int[] codes = new int[lengths.length]; - int lastLength = 0; - int code = 0; - for (int i = 0; i < lengths.length; i++) { - while (lastLength != lengths[i]) { - lastLength++; - code <<= 1; - } - if (lastLength != 0) { - codes[i] = code; - code++; - } - } + // These values in these arrays correspond to the elements of the + // "values" array. The Huffman code for codeValues[N] is codes[N] + // and the length of the code is lengths[N]. + int[] codes = new int[lengths.length]; + int lastLength = 0; + int code = 0; + for (int i = 0; i < lengths.length; i++) { + while (lastLength != lengths[i]) { + lastLength++; + code <<= 1; + } + if (lastLength != 0) { + codes[i] = code; + code++; + } + } - int last = 0; - for (int i = 0; i < lengths.length; i++) { - if (last != lengths[i]) { - last = lengths[i]; - codeLengthInfo[last - 1].baseIndex = i; - codeLengthInfo[last - 1].min = codes[i]; - } - if (last != 0) codeLengthInfo[last - 1].max = codes[i]; - } + int last = 0; + for (int i = 0; i < lengths.length; i++) { + if (last != lengths[i]) { + last = lengths[i]; + codeLengthInfo[last - 1].baseIndex = i; + codeLengthInfo[last - 1].min = codes[i]; + } + if (last != 0) codeLengthInfo[last - 1].max = codes[i]; + } } int getNextValue(PngDecodingDataStream stream) { - int code = stream.getNextIdatBit(); - int codelength = 0; + int code = stream.getNextIdatBit(); + int codelength = 0; - // Here we are taking advantage of the fact that 1 bits are used as - // a prefix to the longer codeValues. - while (codelength < MAX_CODE_LENGTH && code > codeLengthInfo[codelength].max) { - code = ((code << 1) | stream.getNextIdatBit()); + // Here we are taking advantage of the fact that 1 bits are used as + // a prefix to the longer codeValues. + while (codelength < MAX_CODE_LENGTH && code > codeLengthInfo[codelength].max) { + code = ((code << 1) | stream.getNextIdatBit()); codelength++; - } - if (codelength >= MAX_CODE_LENGTH) stream.error(); + } + if (codelength >= MAX_CODE_LENGTH) stream.error(); - // Now we have a Huffman code of length (codelength + 1) that - // is somewhere in the range - // minCodesByLength[codelength]..maxCodesByLength[codelength]. - // This code is the (offset + 1)'th code of (codelength + 1); - int offset = code - codeLengthInfo[codelength].min; + // Now we have a Huffman code of length (codelength + 1) that + // is somewhere in the range + // minCodesByLength[codelength]..maxCodesByLength[codelength]. + // This code is the (offset + 1)'th code of (codelength + 1); + int offset = code - codeLengthInfo[codelength].min; - // indexesByLength[codelength] is the first code of length (codelength + 1) - // so now we can look up the value for the Huffman code in the table. - int index = codeLengthInfo[codelength].baseIndex + offset; - return codeValues[index]; + // indexesByLength[codelength] is the first code of length (codelength + 1) + // so now we can look up the value for the Huffman code in the table. + int index = codeLengthInfo[codelength].baseIndex + offset; + return codeValues[index]; } class CodeLengthInfo { - int length; - int max; - int min; - int baseIndex; + int length; + int max; + int min; + int baseIndex; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngHuffmanTables.d --- a/dwt/internal/image/PngHuffmanTables.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngHuffmanTables.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -15,14 +15,14 @@ import dwt.internal.image.PngLzBlockReader; public class PngHuffmanTables { - PngHuffmanTable literalTable; - PngHuffmanTable distanceTable; + PngHuffmanTable literalTable; + PngHuffmanTable distanceTable; - static PngHuffmanTable FixedLiteralTable; - static PngHuffmanTable FixedDistanceTable; + static PngHuffmanTable FixedLiteralTable; + static PngHuffmanTable FixedDistanceTable; - static final int LiteralTableSize = 288; - static final int[] FixedLiteralLengths = [ + static final int LiteralTableSize = 288; + static final int[] FixedLiteralLengths = [ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, @@ -35,128 +35,128 @@ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, - ]; + ]; - static final int DistanceTableSize = 32; - static final int[] FixedDistanceLengths = [ - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - ]; + static final int DistanceTableSize = 32; + static final int[] FixedDistanceLengths = [ + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + ]; - static final int LengthCodeTableSize = 19; - static final int[] LengthCodeOrder = [ - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, - 11, 4, 12, 3, 13, 2, 14, 1, 15 - ]; + static final int LengthCodeTableSize = 19; + static final int[] LengthCodeOrder = [ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, + 11, 4, 12, 3, 13, 2, 14, 1, 15 + ]; static PngHuffmanTables getDynamicTables(PngDecodingDataStream stream) { - return new PngHuffmanTables(stream); + return new PngHuffmanTables(stream); } static PngHuffmanTables getFixedTables() { - return new PngHuffmanTables(); + return new PngHuffmanTables(); } private PngHuffmanTable getFixedLiteralTable() { - if (FixedLiteralTable == null) { - FixedLiteralTable = new PngHuffmanTable(FixedLiteralLengths); - } - return FixedLiteralTable; + if (FixedLiteralTable == null) { + FixedLiteralTable = new PngHuffmanTable(FixedLiteralLengths); + } + return FixedLiteralTable; } private PngHuffmanTable getFixedDistanceTable() { - if (FixedDistanceTable == null) { - FixedDistanceTable = new PngHuffmanTable(FixedDistanceLengths); - } - return FixedDistanceTable; + if (FixedDistanceTable == null) { + FixedDistanceTable = new PngHuffmanTable(FixedDistanceLengths); + } + return FixedDistanceTable; } private this () { - literalTable = getFixedLiteralTable(); - distanceTable = getFixedDistanceTable(); + literalTable = getFixedLiteralTable(); + distanceTable = getFixedDistanceTable(); } private this (PngDecodingDataStream stream) { - int literals = PngLzBlockReader.FIRST_LENGTH_CODE - + stream.getNextIdatBits(5); - int distances = PngLzBlockReader.FIRST_DISTANCE_CODE - + stream.getNextIdatBits(5); - int codeLengthCodes = PngLzBlockReader.FIRST_CODE_LENGTH_CODE - + stream.getNextIdatBits(4); + int literals = PngLzBlockReader.FIRST_LENGTH_CODE + + stream.getNextIdatBits(5); + int distances = PngLzBlockReader.FIRST_DISTANCE_CODE + + stream.getNextIdatBits(5); + int codeLengthCodes = PngLzBlockReader.FIRST_CODE_LENGTH_CODE + + stream.getNextIdatBits(4); - if (codeLengthCodes > PngLzBlockReader.LAST_CODE_LENGTH_CODE) { - stream.error(); - } + if (codeLengthCodes > PngLzBlockReader.LAST_CODE_LENGTH_CODE) { + stream.error(); + } - /* Tricky, tricky, tricky. The length codes are stored in - * a very odd order. (For the order, see the definition of - * the static field lengthCodeOrder.) Also, the data may - * not contain values for all the codes. It may just contain - * values for the first X number of codes. The table should - * be of size regardless of the number - * of values actually given in the table. - */ - int[] lengthCodes = new int[LengthCodeTableSize]; - for (int i = 0; i < codeLengthCodes; i++) { - lengthCodes[LengthCodeOrder[i]] = stream.getNextIdatBits(3); - } - PngHuffmanTable codeLengthsTable = new PngHuffmanTable(lengthCodes); + /* Tricky, tricky, tricky. The length codes are stored in + * a very odd order. (For the order, see the definition of + * the static field lengthCodeOrder.) Also, the data may + * not contain values for all the codes. It may just contain + * values for the first X number of codes. The table should + * be of size regardless of the number + * of values actually given in the table. + */ + int[] lengthCodes = new int[LengthCodeTableSize]; + for (int i = 0; i < codeLengthCodes; i++) { + lengthCodes[LengthCodeOrder[i]] = stream.getNextIdatBits(3); + } + PngHuffmanTable codeLengthsTable = new PngHuffmanTable(lengthCodes); - int[] literalLengths = readLengths( - stream, literals, codeLengthsTable, LiteralTableSize); - int[] distanceLengths = readLengths( - stream, distances, codeLengthsTable, DistanceTableSize); + int[] literalLengths = readLengths( + stream, literals, codeLengthsTable, LiteralTableSize); + int[] distanceLengths = readLengths( + stream, distances, codeLengthsTable, DistanceTableSize); - literalTable = new PngHuffmanTable(literalLengths); - distanceTable = new PngHuffmanTable(distanceLengths); + literalTable = new PngHuffmanTable(literalLengths); + distanceTable = new PngHuffmanTable(distanceLengths); } private int [] readLengths (PngDecodingDataStream stream, - int numLengths, - PngHuffmanTable lengthsTable, - int tableSize) + int numLengths, + PngHuffmanTable lengthsTable, + int tableSize) { - int[] lengths = new int[tableSize]; + int[] lengths = new int[tableSize]; - for (int index = 0; index < numLengths;) { - int value = lengthsTable.getNextValue(stream); - if (value < 16) { - // Literal value - lengths[index] = value; - index++; - } else if (value == 16) { - // Repeat the previous code 3-6 times. - int count = stream.getNextIdatBits(2) + 3; - for (int i = 0; i < count; i++) { - lengths[index] = lengths [index - 1]; - index++; - } - } else if (value == 17) { - // Repeat 0 3-10 times. - int count = stream.getNextIdatBits(3) + 3; - for (int i = 0; i < count; i++) { - lengths[index] = 0; - index++; - } - } else if (value == 18) { - // Repeat 0 11-138 times. - int count = stream.getNextIdatBits(7) + 11; - for (int i = 0; i < count; i++) { - lengths[index] = 0; - index++; - } - } else { - stream.error(); - } - } - return lengths; + for (int index = 0; index < numLengths;) { + int value = lengthsTable.getNextValue(stream); + if (value < 16) { + // Literal value + lengths[index] = value; + index++; + } else if (value == 16) { + // Repeat the previous code 3-6 times. + int count = stream.getNextIdatBits(2) + 3; + for (int i = 0; i < count; i++) { + lengths[index] = lengths [index - 1]; + index++; + } + } else if (value == 17) { + // Repeat 0 3-10 times. + int count = stream.getNextIdatBits(3) + 3; + for (int i = 0; i < count; i++) { + lengths[index] = 0; + index++; + } + } else if (value == 18) { + // Repeat 0 11-138 times. + int count = stream.getNextIdatBits(7) + 11; + for (int i = 0; i < count; i++) { + lengths[index] = 0; + index++; + } + } else { + stream.error(); + } + } + return lengths; } int getNextLiteralValue(PngDecodingDataStream stream) { - return literalTable.getNextValue(stream); + return literalTable.getNextValue(stream); } int getNextDistanceValue(PngDecodingDataStream stream) { - return distanceTable.getNextValue(stream); + return distanceTable.getNextValue(stream); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngIdatChunk.d --- a/dwt/internal/image/PngIdatChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngIdatChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -18,48 +18,48 @@ class PngIdatChunk : PngChunk { - static const int HEADER_BYTES_LENGTH = 2; - static const int ADLER_FIELD_LENGTH = 4; - static const int HEADER_BYTE1_DATA_OFFSET = DATA_OFFSET + 0; - static const int HEADER_BYTE2_DATA_OFFSET = DATA_OFFSET + 1; - static const int ADLER_DATA_OFFSET = DATA_OFFSET + 2; // plus variable compressed data length + static const int HEADER_BYTES_LENGTH = 2; + static const int ADLER_FIELD_LENGTH = 4; + static const int HEADER_BYTE1_DATA_OFFSET = DATA_OFFSET + 0; + static const int HEADER_BYTE2_DATA_OFFSET = DATA_OFFSET + 1; + static const int ADLER_DATA_OFFSET = DATA_OFFSET + 2; // plus variable compressed data length this(byte headerByte1, byte headerByte2, byte[] data, int adler) { - super(data.length + HEADER_BYTES_LENGTH + ADLER_FIELD_LENGTH); - setType(TYPE_IDAT); - reference[HEADER_BYTE1_DATA_OFFSET] = headerByte1; - reference[HEADER_BYTE2_DATA_OFFSET] = headerByte2; + super(data.length + HEADER_BYTES_LENGTH + ADLER_FIELD_LENGTH); + setType(TYPE_IDAT); + reference[HEADER_BYTE1_DATA_OFFSET] = headerByte1; + reference[HEADER_BYTE2_DATA_OFFSET] = headerByte2; System.arraycopy(data, 0, reference, DATA_OFFSET, data.length); - setInt32(ADLER_DATA_OFFSET, adler); - setCRC(computeCRC()); + setInt32(ADLER_DATA_OFFSET, adler); + setCRC(computeCRC()); } this(byte[] reference) { - super(reference); + super(reference); } int getChunkType() { - return CHUNK_IDAT; + return CHUNK_IDAT; } /** * Answer whether the chunk is a valid IDAT chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { - if (!readState.readIHDR - || (headerChunk.getMustHavePalette() && !readState.readPLTE) - || readState.readIEND) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - readState.readIDAT = true; - } + if (!readState.readIHDR + || (headerChunk.getMustHavePalette() && !readState.readPLTE) + || readState.readIEND) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + readState.readIDAT = true; + } - super.validate(readState, headerChunk); + super.validate(readState, headerChunk); } byte getDataByteAtOffset(int offset) { - return reference[DATA_OFFSET + offset]; + return reference[DATA_OFFSET + offset]; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngIendChunk.d --- a/dwt/internal/image/PngIendChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngIendChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -19,40 +19,40 @@ class PngIendChunk : PngChunk { this() { - super(0); - setType(TYPE_IEND); - setCRC(computeCRC()); + super(0); + setType(TYPE_IEND); + setCRC(computeCRC()); } this(byte[] reference){ - super(reference); + super(reference); } int getChunkType() { - return CHUNK_IEND; + return CHUNK_IEND; } /** * Answer whether the chunk is a valid IEND chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { - // An IEND chunk is invalid if no IHDR has been read. - // Or if a palette is required and has not been read. - // Or if no IDAT chunk has been read. - if (!readState.readIHDR - || (headerChunk.getMustHavePalette() && !readState.readPLTE) - || !readState.readIDAT - || readState.readIEND) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - readState.readIEND = true; - } + // An IEND chunk is invalid if no IHDR has been read. + // Or if a palette is required and has not been read. + // Or if no IDAT chunk has been read. + if (!readState.readIHDR + || (headerChunk.getMustHavePalette() && !readState.readPLTE) + || !readState.readIDAT + || readState.readIEND) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + readState.readIEND = true; + } - super.validate(readState, headerChunk); + super.validate(readState, headerChunk); - // IEND chunks are not allowed to have any data. - if (getLength() > 0) SWT.error(SWT.ERROR_INVALID_IMAGE); + // IEND chunks are not allowed to have any data. + if (getLength() > 0) SWT.error(SWT.ERROR_INVALID_IMAGE); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngIhdrChunk.d --- a/dwt/internal/image/PngIhdrChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngIhdrChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -20,48 +20,48 @@ import tango.text.convert.Format; class PngIhdrChunk : PngChunk { - static const int IHDR_DATA_LENGTH = 13; + static const int IHDR_DATA_LENGTH = 13; - static const int WIDTH_DATA_OFFSET = DATA_OFFSET + 0; - static const int HEIGHT_DATA_OFFSET = DATA_OFFSET + 4; - static const int BIT_DEPTH_OFFSET = DATA_OFFSET + 8; - static const int COLOR_TYPE_OFFSET = DATA_OFFSET + 9; - static const int COMPRESSION_METHOD_OFFSET = DATA_OFFSET + 10; - static const int FILTER_METHOD_OFFSET = DATA_OFFSET + 11; - static const int INTERLACE_METHOD_OFFSET = DATA_OFFSET + 12; + static const int WIDTH_DATA_OFFSET = DATA_OFFSET + 0; + static const int HEIGHT_DATA_OFFSET = DATA_OFFSET + 4; + static const int BIT_DEPTH_OFFSET = DATA_OFFSET + 8; + static const int COLOR_TYPE_OFFSET = DATA_OFFSET + 9; + static const int COMPRESSION_METHOD_OFFSET = DATA_OFFSET + 10; + static const int FILTER_METHOD_OFFSET = DATA_OFFSET + 11; + static const int INTERLACE_METHOD_OFFSET = DATA_OFFSET + 12; - static const byte COLOR_TYPE_GRAYSCALE = 0; - static const byte COLOR_TYPE_RGB = 2; - static const byte COLOR_TYPE_PALETTE = 3; - static const byte COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4; - static const byte COLOR_TYPE_RGB_WITH_ALPHA = 6; + static const byte COLOR_TYPE_GRAYSCALE = 0; + static const byte COLOR_TYPE_RGB = 2; + static const byte COLOR_TYPE_PALETTE = 3; + static const byte COLOR_TYPE_GRAYSCALE_WITH_ALPHA = 4; + static const byte COLOR_TYPE_RGB_WITH_ALPHA = 6; - static const int INTERLACE_METHOD_NONE = 0; - static const int INTERLACE_METHOD_ADAM7 = 1; + static const int INTERLACE_METHOD_NONE = 0; + static const int INTERLACE_METHOD_ADAM7 = 1; - static const int FILTER_NONE = 0; - static const int FILTER_SUB = 1; - static const int FILTER_UP = 2; - static const int FILTER_AVERAGE = 3; - static const int FILTER_PAETH = 4; + static const int FILTER_NONE = 0; + static const int FILTER_SUB = 1; + static const int FILTER_UP = 2; + static const int FILTER_AVERAGE = 3; + static const int FILTER_PAETH = 4; - static const byte[] ValidBitDepths = [ cast(byte)1, 2, 4, 8, 16]; - static const byte[] ValidColorTypes = [ cast(byte)0, 2, 3, 4, 6]; + static const byte[] ValidBitDepths = [ cast(byte)1, 2, 4, 8, 16]; + static const byte[] ValidColorTypes = [ cast(byte)0, 2, 3, 4, 6]; - int width, height; - byte bitDepth, colorType, compressionMethod, filterMethod, interlaceMethod; + int width, height; + byte bitDepth, colorType, compressionMethod, filterMethod, interlaceMethod; this(int width, int height, byte bitDepth, byte colorType, byte compressionMethod, byte filterMethod, byte interlaceMethod) { - super(IHDR_DATA_LENGTH); - setType(TYPE_IHDR); - setWidth(width); - setHeight(height); - setBitDepth(bitDepth); - setColorType(colorType); - setCompressionMethod(compressionMethod); - setFilterMethod(filterMethod); - setInterlaceMethod(interlaceMethod); - setCRC(computeCRC()); + super(IHDR_DATA_LENGTH); + setType(TYPE_IHDR); + setWidth(width); + setHeight(height); + setBitDepth(bitDepth); + setColorType(colorType); + setCompressionMethod(compressionMethod); + setFilterMethod(filterMethod); + setInterlaceMethod(interlaceMethod); + setCRC(computeCRC()); } /** @@ -69,49 +69,49 @@ * given. */ this(byte[] reference) { - super(reference); - if (reference.length <= IHDR_DATA_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); - width = getInt32(WIDTH_DATA_OFFSET); - height = getInt32(HEIGHT_DATA_OFFSET); - bitDepth = reference[BIT_DEPTH_OFFSET]; - colorType = reference[COLOR_TYPE_OFFSET]; - compressionMethod = reference[COMPRESSION_METHOD_OFFSET]; - filterMethod = reference[FILTER_METHOD_OFFSET]; - interlaceMethod = reference[INTERLACE_METHOD_OFFSET]; + super(reference); + if (reference.length <= IHDR_DATA_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); + width = getInt32(WIDTH_DATA_OFFSET); + height = getInt32(HEIGHT_DATA_OFFSET); + bitDepth = reference[BIT_DEPTH_OFFSET]; + colorType = reference[COLOR_TYPE_OFFSET]; + compressionMethod = reference[COMPRESSION_METHOD_OFFSET]; + filterMethod = reference[FILTER_METHOD_OFFSET]; + interlaceMethod = reference[INTERLACE_METHOD_OFFSET]; } int getChunkType() { - return CHUNK_IHDR; + return CHUNK_IHDR; } /** * Get the image's width in pixels. */ int getWidth() { - return width; + return width; } /** * Set the image's width in pixels. */ void setWidth(int value) { - setInt32(WIDTH_DATA_OFFSET, value); - width = value; + setInt32(WIDTH_DATA_OFFSET, value); + width = value; } /** * Get the image's height in pixels. */ int getHeight() { - return height; + return height; } /** * Set the image's height in pixels. */ void setHeight(int value) { - setInt32(HEIGHT_DATA_OFFSET, value); - height = value; + setInt32(HEIGHT_DATA_OFFSET, value); + height = value; } /** @@ -119,7 +119,7 @@ * This is limited to the values 1, 2, 4, 8, or 16. */ byte getBitDepth() { - return bitDepth; + return bitDepth; } /** @@ -127,8 +127,8 @@ * This is limited to the values 1, 2, 4, 8, or 16. */ void setBitDepth(byte value) { - reference[BIT_DEPTH_OFFSET] = value; - bitDepth = value; + reference[BIT_DEPTH_OFFSET] = value; + bitDepth = value; } /** @@ -141,7 +141,7 @@ * 6 - RGB with Alpha channel. */ byte getColorType() { - return colorType; + return colorType; } /** @@ -154,8 +154,8 @@ * 6 - RGB with Alpha channel. */ void setColorType(byte value) { - reference[COLOR_TYPE_OFFSET] = value; - colorType = value; + reference[COLOR_TYPE_OFFSET] = value; + colorType = value; } /** @@ -163,7 +163,7 @@ * This value must be 0. */ byte getCompressionMethod() { - return compressionMethod; + return compressionMethod; } /** @@ -171,8 +171,8 @@ * This value must be 0. */ void setCompressionMethod(byte value) { - reference[COMPRESSION_METHOD_OFFSET] = value; - compressionMethod = value; + reference[COMPRESSION_METHOD_OFFSET] = value; + compressionMethod = value; } /** @@ -180,7 +180,7 @@ * This value must be 0. */ byte getFilterMethod() { - return filterMethod; + return filterMethod; } /** @@ -188,8 +188,8 @@ * This value must be 0. */ void setFilterMethod(byte value) { - reference[FILTER_METHOD_OFFSET] = value; - filterMethod = value; + reference[FILTER_METHOD_OFFSET] = value; + filterMethod = value; } /** @@ -199,7 +199,7 @@ * 1 - Adam7 interlacing used. */ byte getInterlaceMethod() { - return interlaceMethod; + return interlaceMethod; } /** @@ -209,94 +209,94 @@ * 1 - Adam7 interlacing used. */ void setInterlaceMethod(byte value) { - reference[INTERLACE_METHOD_OFFSET] = value; - interlaceMethod = value; + reference[INTERLACE_METHOD_OFFSET] = value; + interlaceMethod = value; } /** * Answer whether the chunk is a valid IHDR chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { - // An IHDR chunk is invalid if any other chunk has - // been read. - if (readState.readIHDR - || readState.readPLTE - || readState.readIDAT - || readState.readIEND) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - readState.readIHDR = true; - } + // An IHDR chunk is invalid if any other chunk has + // been read. + if (readState.readIHDR + || readState.readPLTE + || readState.readIDAT + || readState.readIEND) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + readState.readIHDR = true; + } - super.validate(readState, headerChunk); + super.validate(readState, headerChunk); - if (length != IHDR_DATA_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); - if (compressionMethod != 0) SWT.error(SWT.ERROR_INVALID_IMAGE); - if (interlaceMethod != INTERLACE_METHOD_NONE && - interlaceMethod != INTERLACE_METHOD_ADAM7) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + if (length != IHDR_DATA_LENGTH) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (compressionMethod != 0) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (interlaceMethod != INTERLACE_METHOD_NONE && + interlaceMethod != INTERLACE_METHOD_ADAM7) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } - bool colorTypeIsValid = false; - for (int i = 0; i < ValidColorTypes.length; i++) { - if (ValidColorTypes[i] == colorType) { - colorTypeIsValid = true; - break; - } - } - if (!colorTypeIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE); + bool colorTypeIsValid = false; + for (int i = 0; i < ValidColorTypes.length; i++) { + if (ValidColorTypes[i] == colorType) { + colorTypeIsValid = true; + break; + } + } + if (!colorTypeIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE); - bool bitDepthIsValid = false; - for (int i = 0; i < ValidBitDepths.length; i++) { - if (ValidBitDepths[i] == bitDepth) { - bitDepthIsValid = true; - break; - } - } - if (!bitDepthIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE); + bool bitDepthIsValid = false; + for (int i = 0; i < ValidBitDepths.length; i++) { + if (ValidBitDepths[i] == bitDepth) { + bitDepthIsValid = true; + break; + } + } + if (!bitDepthIsValid) SWT.error(SWT.ERROR_INVALID_IMAGE); - if ((colorType == COLOR_TYPE_RGB - || colorType == COLOR_TYPE_RGB_WITH_ALPHA - || colorType == COLOR_TYPE_GRAYSCALE_WITH_ALPHA) - && bitDepth < 8) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + if ((colorType == COLOR_TYPE_RGB + || colorType == COLOR_TYPE_RGB_WITH_ALPHA + || colorType == COLOR_TYPE_GRAYSCALE_WITH_ALPHA) + && bitDepth < 8) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } - if (colorType == COLOR_TYPE_PALETTE && bitDepth > 8) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + if (colorType == COLOR_TYPE_PALETTE && bitDepth > 8) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } } char[] getColorTypeString() { - switch (colorType) { - case COLOR_TYPE_GRAYSCALE: return "Grayscale"; - case COLOR_TYPE_RGB: return "RGB"; - case COLOR_TYPE_PALETTE: return "Palette"; - case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return "Grayscale with Alpha"; - case COLOR_TYPE_RGB_WITH_ALPHA: return "RGB with Alpha"; - default: return "Unknown - " ~ cast(char)colorType; - } + switch (colorType) { + case COLOR_TYPE_GRAYSCALE: return "Grayscale"; + case COLOR_TYPE_RGB: return "RGB"; + case COLOR_TYPE_PALETTE: return "Palette"; + case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: return "Grayscale with Alpha"; + case COLOR_TYPE_RGB_WITH_ALPHA: return "RGB with Alpha"; + default: return "Unknown - " ~ cast(char)colorType; + } } char[] getFilterMethodString() { - switch (filterMethod) { - case FILTER_NONE: return "None"; - case FILTER_SUB: return "Sub"; - case FILTER_UP: return "Up"; - case FILTER_AVERAGE: return "Average"; - case FILTER_PAETH: return "Paeth"; - default: return "Unknown"; - } + switch (filterMethod) { + case FILTER_NONE: return "None"; + case FILTER_SUB: return "Sub"; + case FILTER_UP: return "Up"; + case FILTER_AVERAGE: return "Average"; + case FILTER_PAETH: return "Paeth"; + default: return "Unknown"; + } } char[] getInterlaceMethodString() { - switch (interlaceMethod) { - case INTERLACE_METHOD_NONE: return "Not Interlaced"; - case INTERLACE_METHOD_ADAM7: return "Interlaced - ADAM7"; - default: return "Unknown"; - } + switch (interlaceMethod) { + case INTERLACE_METHOD_NONE: return "Not Interlaced"; + case INTERLACE_METHOD_ADAM7: return "Interlaced - ADAM7"; + default: return "Unknown"; + } } override char[] contributeToString() { @@ -305,12 +305,12 @@ } bool getMustHavePalette() { - return colorType == COLOR_TYPE_PALETTE; + return colorType == COLOR_TYPE_PALETTE; } bool getCanHavePalette() { - return colorType != COLOR_TYPE_GRAYSCALE && - colorType != COLOR_TYPE_GRAYSCALE_WITH_ALPHA; + return colorType != COLOR_TYPE_GRAYSCALE && + colorType != COLOR_TYPE_GRAYSCALE_WITH_ALPHA; } /** @@ -318,20 +318,20 @@ * and bit depth. */ int getBitsPerPixel() { - switch (colorType) { - case COLOR_TYPE_RGB_WITH_ALPHA: - return 4 * bitDepth; - case COLOR_TYPE_RGB: - return 3 * bitDepth; - case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - return 2 * bitDepth; - case COLOR_TYPE_GRAYSCALE: - case COLOR_TYPE_PALETTE: - return bitDepth; - default: - SWT.error(SWT.ERROR_INVALID_IMAGE); - return 0; - } + switch (colorType) { + case COLOR_TYPE_RGB_WITH_ALPHA: + return 4 * bitDepth; + case COLOR_TYPE_RGB: + return 3 * bitDepth; + case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + return 2 * bitDepth; + case COLOR_TYPE_GRAYSCALE: + case COLOR_TYPE_PALETTE: + return bitDepth; + default: + SWT.error(SWT.ERROR_INVALID_IMAGE); + return 0; + } } /** @@ -339,61 +339,61 @@ * and bit depth. */ int getSwtBitsPerPixel() { - switch (colorType) { - case COLOR_TYPE_RGB_WITH_ALPHA: - case COLOR_TYPE_RGB: - case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - return 24; - case COLOR_TYPE_GRAYSCALE: - case COLOR_TYPE_PALETTE: - return Math.min(bitDepth, 8); - default: - SWT.error(SWT.ERROR_INVALID_IMAGE); - return 0; - } + switch (colorType) { + case COLOR_TYPE_RGB_WITH_ALPHA: + case COLOR_TYPE_RGB: + case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + return 24; + case COLOR_TYPE_GRAYSCALE: + case COLOR_TYPE_PALETTE: + return Math.min(bitDepth, 8); + default: + SWT.error(SWT.ERROR_INVALID_IMAGE); + return 0; + } } int getFilterByteOffset() { - if (bitDepth < 8) return 1; - return getBitsPerPixel() / 8; + if (bitDepth < 8) return 1; + return getBitsPerPixel() / 8; } bool usesDirectColor() { - switch (colorType) { - case COLOR_TYPE_GRAYSCALE: - case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - case COLOR_TYPE_RGB: - case COLOR_TYPE_RGB_WITH_ALPHA: - return true; - default: - return false; - } + switch (colorType) { + case COLOR_TYPE_GRAYSCALE: + case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + case COLOR_TYPE_RGB: + case COLOR_TYPE_RGB_WITH_ALPHA: + return true; + default: + return false; + } } PaletteData createGrayscalePalette() { - int depth = Math.min(bitDepth, 8); - int max = (1 << depth) - 1; - int delta = 255 / max; - int gray = 0; - RGB[] rgbs = new RGB[max + 1]; - for (int i = 0; i <= max; i++) { - rgbs[i] = new RGB(gray, gray, gray); - gray += delta; - } - return new PaletteData(rgbs); + int depth = Math.min(bitDepth, 8); + int max = (1 << depth) - 1; + int delta = 255 / max; + int gray = 0; + RGB[] rgbs = new RGB[max + 1]; + for (int i = 0; i <= max; i++) { + rgbs[i] = new RGB(gray, gray, gray); + gray += delta; + } + return new PaletteData(rgbs); } PaletteData getPaletteData() { - switch (colorType) { - case COLOR_TYPE_GRAYSCALE: - return createGrayscalePalette(); - case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - case COLOR_TYPE_RGB: - case COLOR_TYPE_RGB_WITH_ALPHA: - return new PaletteData(0xFF0000, 0xFF00, 0xFF); - default: - return null; - } + switch (colorType) { + case COLOR_TYPE_GRAYSCALE: + return createGrayscalePalette(); + case COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + case COLOR_TYPE_RGB: + case COLOR_TYPE_RGB_WITH_ALPHA: + return new PaletteData(0xFF0000, 0xFF00, 0xFF); + default: + return null; + } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngInputStream.d --- a/dwt/internal/image/PngInputStream.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngInputStream.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -22,49 +22,49 @@ public class PngInputStream : InputStream { alias InputStream.read read; - PngChunkReader reader; - PngChunk chunk; - int offset, length; + PngChunkReader reader; + PngChunk chunk; + int offset, length; - final static int DATA_OFFSET = 8; + final static int DATA_OFFSET = 8; public this(PngIdatChunk chunk, PngChunkReader reader) { - this.chunk = chunk; - this.reader = reader; - length = chunk.getLength(); - offset = 0; + this.chunk = chunk; + this.reader = reader; + length = chunk.getLength(); + offset = 0; } private bool checkChunk() { - while (offset == length) { - chunk = reader.readNextChunk(); - if (chunk == null) throw new IOException("no data"); - if (chunk.getChunkType() == PngChunk.CHUNK_IEND) return false; - if (chunk.getChunkType() != PngChunk.CHUNK_IDAT) throw new IOException(""); - length = chunk.getLength(); - offset = 0; - } - return true; + while (offset == length) { + chunk = reader.readNextChunk(); + if (chunk == null) throw new IOException("no data"); + if (chunk.getChunkType() == PngChunk.CHUNK_IEND) return false; + if (chunk.getChunkType() != PngChunk.CHUNK_IDAT) throw new IOException(""); + length = chunk.getLength(); + offset = 0; + } + return true; } public override void close() { - chunk = null; + chunk = null; } public override int read() { - if (chunk == null) throw new IOException(""); - if (offset == length && !checkChunk()) return -1; - int b = chunk.reference[DATA_OFFSET + offset] & 0xFF; - offset++; - return b; + if (chunk == null) throw new IOException(""); + if (offset == length && !checkChunk()) return -1; + int b = chunk.reference[DATA_OFFSET + offset] & 0xFF; + offset++; + return b; } public override int read(byte[] b, int off, int len) { - if (chunk == null) throw new IOException(""); - if (offset == length && !checkChunk()) return -1; - len = Math.min(len, length - offset); + if (chunk == null) throw new IOException(""); + if (offset == length && !checkChunk()) return -1; + len = Math.min(len, length - offset); System.arraycopy(chunk.reference, DATA_OFFSET + offset, b, off, len); - offset += len; - return len; + offset += len; + return len; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngLzBlockReader.d --- a/dwt/internal/image/PngLzBlockReader.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngLzBlockReader.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -14,160 +14,160 @@ import dwt.internal.image.PngHuffmanTables; public class PngLzBlockReader { - bool isLastBlock; - byte compressionType; - int uncompressedBytesRemaining; - PngDecodingDataStream stream; - PngHuffmanTables huffmanTables; + bool isLastBlock; + byte compressionType; + int uncompressedBytesRemaining; + PngDecodingDataStream stream; + PngHuffmanTables huffmanTables; - byte[] window; - int windowIndex; - int copyIndex; - int copyBytesRemaining; + byte[] window; + int windowIndex; + int copyIndex; + int copyBytesRemaining; - static const int UNCOMPRESSED = 0; - static const int COMPRESSED_FIXED = 1; - static const int COMPRESSED_DYNAMIC = 2; + static const int UNCOMPRESSED = 0; + static const int COMPRESSED_FIXED = 1; + static const int COMPRESSED_DYNAMIC = 2; - static const int END_OF_COMPRESSED_BLOCK = 256; - static const int FIRST_LENGTH_CODE = 257; - static const int LAST_LENGTH_CODE = 285; - static const int FIRST_DISTANCE_CODE = 1; - static const int LAST_DISTANCE_CODE = 29; - static const int FIRST_CODE_LENGTH_CODE = 4; - static const int LAST_CODE_LENGTH_CODE = 19; + static const int END_OF_COMPRESSED_BLOCK = 256; + static const int FIRST_LENGTH_CODE = 257; + static const int LAST_LENGTH_CODE = 285; + static const int FIRST_DISTANCE_CODE = 1; + static const int LAST_DISTANCE_CODE = 29; + static const int FIRST_CODE_LENGTH_CODE = 4; + static const int LAST_CODE_LENGTH_CODE = 19; - static const int[] lengthBases = [ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, - 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 - ]; - static const int[] extraLengthBits = [ - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, - ]; - static const int[] distanceBases = [ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, - 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, - 6145, 8193, 12289, 16385, 24577, - ]; - static const int[] extraDistanceBits = [ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, - 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, - ]; + static const int[] lengthBases = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 + ]; + static const int[] extraLengthBits = [ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, + ]; + static const int[] distanceBases = [ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, + 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, + 6145, 8193, 12289, 16385, 24577, + ]; + static const int[] extraDistanceBits = [ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, + 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, + ]; this(PngDecodingDataStream stream) { - this.stream = stream; - isLastBlock = false; + this.stream = stream; + isLastBlock = false; } void setWindowSize(int windowSize) { - window = new byte[windowSize]; + window = new byte[windowSize]; } void readNextBlockHeader() { - isLastBlock = stream.getNextIdatBit() != 0; - compressionType = cast(byte)(stream.getNextIdatBits(2) & 0xFF); - if (compressionType > 2) stream.error(); + isLastBlock = stream.getNextIdatBit() != 0; + compressionType = cast(byte)(stream.getNextIdatBits(2) & 0xFF); + if (compressionType > 2) stream.error(); - if (compressionType == UNCOMPRESSED) { - byte b1 = stream.getNextIdatByte(); - byte b2 = stream.getNextIdatByte(); - byte b3 = stream.getNextIdatByte(); - byte b4 = stream.getNextIdatByte(); - if (b1 != ~b3 || b2 != ~b4) stream.error(); - uncompressedBytesRemaining = (b1 & 0xFF) | ((b2 & 0xFF) << 8); - } else if (compressionType == COMPRESSED_DYNAMIC) { - huffmanTables = PngHuffmanTables.getDynamicTables(stream); - } else { - huffmanTables = PngHuffmanTables.getFixedTables(); - } + if (compressionType == UNCOMPRESSED) { + byte b1 = stream.getNextIdatByte(); + byte b2 = stream.getNextIdatByte(); + byte b3 = stream.getNextIdatByte(); + byte b4 = stream.getNextIdatByte(); + if (b1 != ~b3 || b2 != ~b4) stream.error(); + uncompressedBytesRemaining = (b1 & 0xFF) | ((b2 & 0xFF) << 8); + } else if (compressionType == COMPRESSED_DYNAMIC) { + huffmanTables = PngHuffmanTables.getDynamicTables(stream); + } else { + huffmanTables = PngHuffmanTables.getFixedTables(); + } } byte getNextByte() { - if (compressionType == UNCOMPRESSED) { - if (uncompressedBytesRemaining == 0) { - readNextBlockHeader(); - return getNextByte(); - } - uncompressedBytesRemaining--; - return stream.getNextIdatByte(); - } else { - byte value = getNextCompressedByte(); - if (value == END_OF_COMPRESSED_BLOCK) { - if (isLastBlock) stream.error(); - readNextBlockHeader(); - return getNextByte(); - } else { - return value; - } - } + if (compressionType == UNCOMPRESSED) { + if (uncompressedBytesRemaining == 0) { + readNextBlockHeader(); + return getNextByte(); + } + uncompressedBytesRemaining--; + return stream.getNextIdatByte(); + } else { + byte value = getNextCompressedByte(); + if (value == END_OF_COMPRESSED_BLOCK) { + if (isLastBlock) stream.error(); + readNextBlockHeader(); + return getNextByte(); + } else { + return value; + } + } } private void assertBlockAtEnd() { - if (compressionType == UNCOMPRESSED) { - if (uncompressedBytesRemaining > 0) stream.error(); - } else if (copyBytesRemaining > 0 || - (huffmanTables.getNextLiteralValue(stream) != END_OF_COMPRESSED_BLOCK)) - { - stream.error(); - } + if (compressionType == UNCOMPRESSED) { + if (uncompressedBytesRemaining > 0) stream.error(); + } else if (copyBytesRemaining > 0 || + (huffmanTables.getNextLiteralValue(stream) != END_OF_COMPRESSED_BLOCK)) + { + stream.error(); + } } void assertCompressedDataAtEnd() { - assertBlockAtEnd(); - while (!isLastBlock) { - readNextBlockHeader(); - assertBlockAtEnd(); - } + assertBlockAtEnd(); + while (!isLastBlock) { + readNextBlockHeader(); + assertBlockAtEnd(); + } } private byte getNextCompressedByte() { - if (copyBytesRemaining > 0) { - byte value = window[copyIndex]; - window[windowIndex] = value; - copyBytesRemaining--; + if (copyBytesRemaining > 0) { + byte value = window[copyIndex]; + window[windowIndex] = value; + copyBytesRemaining--; - copyIndex++; - windowIndex++; - if (copyIndex == window.length) copyIndex = 0; - if (windowIndex == window.length) windowIndex = 0; + copyIndex++; + windowIndex++; + if (copyIndex == window.length) copyIndex = 0; + if (windowIndex == window.length) windowIndex = 0; - return value; - } + return value; + } - int value = huffmanTables.getNextLiteralValue(stream); - if (value < END_OF_COMPRESSED_BLOCK) { - window[windowIndex] = cast(byte) (value & 0xFF); - windowIndex++; - if (windowIndex >= window.length) windowIndex = 0; - return cast(byte) (value & 0xFF); - } else if (value == END_OF_COMPRESSED_BLOCK) { - readNextBlockHeader(); - return getNextByte(); - } else if (value <= LAST_LENGTH_CODE) { - int extraBits = extraLengthBits[value - FIRST_LENGTH_CODE]; - int length = lengthBases[value - FIRST_LENGTH_CODE]; - if (extraBits > 0) { - length += stream.getNextIdatBits(extraBits); - } + int value = huffmanTables.getNextLiteralValue(stream); + if (value < END_OF_COMPRESSED_BLOCK) { + window[windowIndex] = cast(byte) (value & 0xFF); + windowIndex++; + if (windowIndex >= window.length) windowIndex = 0; + return cast(byte) (value & 0xFF); + } else if (value == END_OF_COMPRESSED_BLOCK) { + readNextBlockHeader(); + return getNextByte(); + } else if (value <= LAST_LENGTH_CODE) { + int extraBits = extraLengthBits[value - FIRST_LENGTH_CODE]; + int length = lengthBases[value - FIRST_LENGTH_CODE]; + if (extraBits > 0) { + length += stream.getNextIdatBits(extraBits); + } - value = huffmanTables.getNextDistanceValue(stream); - if (value > LAST_DISTANCE_CODE) stream.error(); - extraBits = extraDistanceBits[value]; - int distance = distanceBases[value]; - if (extraBits > 0) { - distance += stream.getNextIdatBits(extraBits); - } + value = huffmanTables.getNextDistanceValue(stream); + if (value > LAST_DISTANCE_CODE) stream.error(); + extraBits = extraDistanceBits[value]; + int distance = distanceBases[value]; + if (extraBits > 0) { + distance += stream.getNextIdatBits(extraBits); + } - copyIndex = windowIndex - distance; - if (copyIndex < 0) copyIndex += window.length; + copyIndex = windowIndex - distance; + if (copyIndex < 0) copyIndex += window.length; - copyBytesRemaining = length; - return getNextCompressedByte(); - } else { - stream.error(); - return 0; - } + copyBytesRemaining = length; + return getNextCompressedByte(); + } else { + stream.error(); + return 0; + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngPlteChunk.d --- a/dwt/internal/image/PngPlteChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngPlteChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -22,30 +22,30 @@ class PngPlteChunk : PngChunk { - int paletteSize; + int paletteSize; this(PaletteData palette) { - super(palette.getRGBs().length * 3); - paletteSize = length / 3; - setType(TYPE_PLTE); - setPaletteData(palette); - setCRC(computeCRC()); + super(palette.getRGBs().length * 3); + paletteSize = length / 3; + setType(TYPE_PLTE); + setPaletteData(palette); + setCRC(computeCRC()); } this(byte[] reference){ - super(reference); - paletteSize = length / 3; + super(reference); + paletteSize = length / 3; } int getChunkType() { - return CHUNK_PLTE; + return CHUNK_PLTE; } /** * Get the number of colors in this palette. */ int getPaletteSize() { - return paletteSize; + return paletteSize; } /** @@ -55,17 +55,17 @@ * does not store the palette data created. */ PaletteData getPaletteData() { - RGB[] rgbs = new RGB[paletteSize]; -// int start = DATA_OFFSET; -// int end = DATA_OFFSET + length; - for (int i = 0; i < rgbs.length; i++) { - int offset = DATA_OFFSET + (i * 3); - int red = reference[offset] & 0xFF; - int green = reference[offset + 1] & 0xFF; - int blue = reference[offset + 2] & 0xFF; - rgbs[i] = new RGB(red, green, blue); - } - return new PaletteData(rgbs); + RGB[] rgbs = new RGB[paletteSize]; +// int start = DATA_OFFSET; +// int end = DATA_OFFSET + length; + for (int i = 0; i < rgbs.length; i++) { + int offset = DATA_OFFSET + (i * 3); + int red = reference[offset] & 0xFF; + int green = reference[offset + 1] & 0xFF; + int blue = reference[offset + 2] & 0xFF; + rgbs[i] = new RGB(red, green, blue); + } + return new PaletteData(rgbs); } /** @@ -73,56 +73,56 @@ * stored in the specified PaletteData object. */ void setPaletteData(PaletteData palette) { - RGB[] rgbs = palette.getRGBs(); - for (int i = 0; i < rgbs.length; i++) { - int offset = DATA_OFFSET + (i * 3); - reference[offset] = cast(byte) rgbs[i].red; - reference[offset + 1] = cast(byte) rgbs[i].green; - reference[offset + 2] = cast(byte) rgbs[i].blue; - } + RGB[] rgbs = palette.getRGBs(); + for (int i = 0; i < rgbs.length; i++) { + int offset = DATA_OFFSET + (i * 3); + reference[offset] = cast(byte) rgbs[i].red; + reference[offset + 1] = cast(byte) rgbs[i].green; + reference[offset + 2] = cast(byte) rgbs[i].blue; + } } /** * Answer whether the chunk is a valid PLTE chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk) { - // A PLTE chunk is invalid if no IHDR has been read or if any PLTE, - // IDAT, or IEND chunk has been read. - if (!readState.readIHDR - || readState.readPLTE - || readState.readTRNS - || readState.readIDAT - || readState.readIEND) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - readState.readPLTE = true; - } + // A PLTE chunk is invalid if no IHDR has been read or if any PLTE, + // IDAT, or IEND chunk has been read. + if (!readState.readIHDR + || readState.readPLTE + || readState.readTRNS + || readState.readIDAT + || readState.readIEND) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + readState.readPLTE = true; + } - super.validate(readState, headerChunk); + super.validate(readState, headerChunk); - // Palettes cannot be included in grayscale images. - // - // Note: just ignore the palette. -// if (!headerChunk.getCanHavePalette()) SWT.error(SWT.ERROR_INVALID_IMAGE); + // Palettes cannot be included in grayscale images. + // + // Note: just ignore the palette. +// if (!headerChunk.getCanHavePalette()) SWT.error(SWT.ERROR_INVALID_IMAGE); - // Palette chunks' data fields must be event multiples - // of 3. Each 3-byte group represents an RGB value. - if (getLength() % 3 != 0) SWT.error(SWT.ERROR_INVALID_IMAGE); + // Palette chunks' data fields must be event multiples + // of 3. Each 3-byte group represents an RGB value. + if (getLength() % 3 != 0) SWT.error(SWT.ERROR_INVALID_IMAGE); - // Palettes cannot have more entries than 2^bitDepth - // where bitDepth is the bit depth of the image given - // in the IHDR chunk. - if (1 << headerChunk.getBitDepth() < paletteSize) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + // Palettes cannot have more entries than 2^bitDepth + // where bitDepth is the bit depth of the image given + // in the IHDR chunk. + if (1 << headerChunk.getBitDepth() < paletteSize) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } - // Palettes cannot have more than 256 entries. - if (256 < paletteSize) SWT.error(SWT.ERROR_INVALID_IMAGE); + // Palettes cannot have more than 256 entries. + if (256 < paletteSize) SWT.error(SWT.ERROR_INVALID_IMAGE); } override char[] contributeToString() { - return Format("\n\tPalette size:{}", paletteSize ); + return Format("\n\tPalette size:{}", paletteSize ); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/PngTrnsChunk.d --- a/dwt/internal/image/PngTrnsChunk.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/PngTrnsChunk.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -20,78 +20,78 @@ import dwt.internal.image.PngPlteChunk; public class PngTrnsChunk : PngChunk { - static const int TRANSPARENCY_TYPE_PIXEL = 0; - static const int TRANSPARENCY_TYPE_ALPHAS = 1; - static const int RGB_DATA_LENGTH = 6; + static const int TRANSPARENCY_TYPE_PIXEL = 0; + static const int TRANSPARENCY_TYPE_ALPHAS = 1; + static const int RGB_DATA_LENGTH = 6; this(RGB rgb) { - super(RGB_DATA_LENGTH); - setType(TYPE_tRNS); - setInt16(DATA_OFFSET, rgb.red); - setInt16(DATA_OFFSET + 2, rgb.green); - setInt16(DATA_OFFSET + 4, rgb.blue); - setCRC(computeCRC()); + super(RGB_DATA_LENGTH); + setType(TYPE_tRNS); + setInt16(DATA_OFFSET, rgb.red); + setInt16(DATA_OFFSET + 2, rgb.green); + setInt16(DATA_OFFSET + 4, rgb.blue); + setCRC(computeCRC()); } this(byte[] reference){ - super(reference); + super(reference); } int getChunkType() { - return CHUNK_tRNS; + return CHUNK_tRNS; } void validateLength(PngIhdrChunk header, PngPlteChunk paletteChunk) { - bool valid; - switch (header.getColorType()) { - case PngIhdrChunk.COLOR_TYPE_RGB: - // Three 2-byte values (RGB) - valid = getLength() == 6; - break; - case PngIhdrChunk.COLOR_TYPE_PALETTE: - // Three 2-byte values (RGB) - valid = getLength() <= paletteChunk.getLength(); - break; - case PngIhdrChunk.COLOR_TYPE_GRAYSCALE: - // One 2-byte value - valid = getLength() == 2; - break; - // Cannot use both Alpha and tRNS - case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA: - case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA: - default: - valid = false; - } - if (!valid) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } + bool valid; + switch (header.getColorType()) { + case PngIhdrChunk.COLOR_TYPE_RGB: + // Three 2-byte values (RGB) + valid = getLength() == 6; + break; + case PngIhdrChunk.COLOR_TYPE_PALETTE: + // Three 2-byte values (RGB) + valid = getLength() <= paletteChunk.getLength(); + break; + case PngIhdrChunk.COLOR_TYPE_GRAYSCALE: + // One 2-byte value + valid = getLength() == 2; + break; + // Cannot use both Alpha and tRNS + case PngIhdrChunk.COLOR_TYPE_RGB_WITH_ALPHA: + case PngIhdrChunk.COLOR_TYPE_GRAYSCALE_WITH_ALPHA: + default: + valid = false; + } + if (!valid) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } } /** * Answer whether the chunk is a valid tRNS chunk. */ void validate(PngFileReadState readState, PngIhdrChunk headerChunk, PngPlteChunk paletteChunk) { - if (!readState.readIHDR - || (headerChunk.getMustHavePalette() && !readState.readPLTE) - || readState.readIDAT - || readState.readIEND) - { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } else { - readState.readTRNS = true; - } + if (!readState.readIHDR + || (headerChunk.getMustHavePalette() && !readState.readPLTE) + || readState.readIDAT + || readState.readIEND) + { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } else { + readState.readTRNS = true; + } - validateLength(headerChunk, paletteChunk); + validateLength(headerChunk, paletteChunk); - super.validate(readState, headerChunk); + super.validate(readState, headerChunk); } int getTransparencyType(PngIhdrChunk header) { - if (header.getColorType() == PngIhdrChunk.COLOR_TYPE_PALETTE) { - return TRANSPARENCY_TYPE_ALPHAS; - } - return TRANSPARENCY_TYPE_PIXEL; + if (header.getColorType() == PngIhdrChunk.COLOR_TYPE_PALETTE) { + return TRANSPARENCY_TYPE_ALPHAS; + } + return TRANSPARENCY_TYPE_PIXEL; } /** @@ -104,31 +104,31 @@ * RGB. */ int getSwtTransparentPixel(PngIhdrChunk header) { - switch (header.getColorType()) { - case PngIhdrChunk.COLOR_TYPE_GRAYSCALE: - int gray = ((reference[DATA_OFFSET] & 0xFF) << 8) - + (reference[DATA_OFFSET + 1] & 0xFF); - if (header.getBitDepth() > 8) { - return PNGFileFormat.compress16BitDepthTo8BitDepth(gray); - } - return gray & 0xFF; - case PngIhdrChunk.COLOR_TYPE_RGB: - int red = ((reference[DATA_OFFSET] & 0xFF) << 8) - | (reference[DATA_OFFSET + 1] & 0xFF); - int green = ((reference[DATA_OFFSET + 2] & 0xFF) << 8) - | (reference[DATA_OFFSET + 3] & 0xFF); - int blue = ((reference[DATA_OFFSET + 4] & 0xFF) << 8) - | (reference[DATA_OFFSET + 5] & 0xFF); - if (header.getBitDepth() > 8) { - red = PNGFileFormat.compress16BitDepthTo8BitDepth(red); - green = PNGFileFormat.compress16BitDepthTo8BitDepth(green); - blue = PNGFileFormat.compress16BitDepthTo8BitDepth(blue); - } - return (red << 16) | (green << 8) | blue; - default: - SWT.error(SWT.ERROR_INVALID_IMAGE); - return -1; - } + switch (header.getColorType()) { + case PngIhdrChunk.COLOR_TYPE_GRAYSCALE: + int gray = ((reference[DATA_OFFSET] & 0xFF) << 8) + + (reference[DATA_OFFSET + 1] & 0xFF); + if (header.getBitDepth() > 8) { + return PNGFileFormat.compress16BitDepthTo8BitDepth(gray); + } + return gray & 0xFF; + case PngIhdrChunk.COLOR_TYPE_RGB: + int red = ((reference[DATA_OFFSET] & 0xFF) << 8) + | (reference[DATA_OFFSET + 1] & 0xFF); + int green = ((reference[DATA_OFFSET + 2] & 0xFF) << 8) + | (reference[DATA_OFFSET + 3] & 0xFF); + int blue = ((reference[DATA_OFFSET + 4] & 0xFF) << 8) + | (reference[DATA_OFFSET + 5] & 0xFF); + if (header.getBitDepth() > 8) { + red = PNGFileFormat.compress16BitDepthTo8BitDepth(red); + green = PNGFileFormat.compress16BitDepthTo8BitDepth(green); + blue = PNGFileFormat.compress16BitDepthTo8BitDepth(blue); + } + return (red << 16) | (green << 8) | blue; + default: + SWT.error(SWT.ERROR_INVALID_IMAGE); + return -1; + } } /** @@ -137,23 +137,23 @@ * This is only valid for the COLOR_TYPE_PALETTE color type. */ byte[] getAlphaValues(PngIhdrChunk header, PngPlteChunk paletteChunk) { - if (header.getColorType() != PngIhdrChunk.COLOR_TYPE_PALETTE) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - byte[] alphas = new byte[paletteChunk.getPaletteSize()]; - int dataLength = getLength(); - int i = 0; - for (i = 0; i < dataLength; i++) { - alphas[i] = reference[DATA_OFFSET + i]; - } - /** - * Any palette entries which do not have a corresponding - * alpha value in the tRNS chunk are spec'd to have an - * alpha of 255. - */ - for (int j = i; j < alphas.length; j++) { - alphas[j] = cast(byte) 255; - } - return alphas; + if (header.getColorType() != PngIhdrChunk.COLOR_TYPE_PALETTE) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + byte[] alphas = new byte[paletteChunk.getPaletteSize()]; + int dataLength = getLength(); + int i = 0; + for (i = 0; i < dataLength; i++) { + alphas[i] = reference[DATA_OFFSET + i]; + } + /** + * Any palette entries which do not have a corresponding + * alpha value in the tRNS chunk are spec'd to have an + * alpha of 255. + */ + for (int j = i; j < alphas.length; j++) { + alphas[j] = cast(byte) 255; + } + return alphas; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/TIFFDirectory.d --- a/dwt/internal/image/TIFFDirectory.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/TIFFDirectory.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -26,610 +26,610 @@ final class TIFFDirectory { - TIFFRandomFileAccess file; - bool isLittleEndian; - ImageLoader loader; - int depth; + TIFFRandomFileAccess file; + bool isLittleEndian; + ImageLoader loader; + int depth; - /* Directory fields */ - int imageWidth; - int imageLength; - int[] bitsPerSample; - int compression; - int photometricInterpretation; - int[] stripOffsets; - int samplesPerPixel; - int rowsPerStrip; - int[] stripByteCounts; - int t4Options; - int colorMapOffset; + /* Directory fields */ + int imageWidth; + int imageLength; + int[] bitsPerSample; + int compression; + int photometricInterpretation; + int[] stripOffsets; + int samplesPerPixel; + int rowsPerStrip; + int[] stripByteCounts; + int t4Options; + int colorMapOffset; - /* Encoder fields */ - ImageData image; - LEDataOutputStream ostr; + /* Encoder fields */ + ImageData image; + LEDataOutputStream ostr; - static const int NO_VALUE = -1; + static const int NO_VALUE = -1; - static const short TAG_ImageWidth = 256; - static const short TAG_ImageLength = 257; - static const short TAG_BitsPerSample = 258; - static const short TAG_Compression = 259; - static const short TAG_PhotometricInterpretation = 262; - static const short TAG_StripOffsets = 273; - static const short TAG_SamplesPerPixel = 277; - static const short TAG_RowsPerStrip = 278; - static const short TAG_StripByteCounts = 279; - static const short TAG_XResolution = 282; - static const short TAG_YResolution = 283; - static const short TAG_T4Options = 292; - static const short TAG_ResolutionUnit = 296; - static const short TAG_ColorMap = 320; + static const short TAG_ImageWidth = 256; + static const short TAG_ImageLength = 257; + static const short TAG_BitsPerSample = 258; + static const short TAG_Compression = 259; + static const short TAG_PhotometricInterpretation = 262; + static const short TAG_StripOffsets = 273; + static const short TAG_SamplesPerPixel = 277; + static const short TAG_RowsPerStrip = 278; + static const short TAG_StripByteCounts = 279; + static const short TAG_XResolution = 282; + static const short TAG_YResolution = 283; + static const short TAG_T4Options = 292; + static const short TAG_ResolutionUnit = 296; + static const short TAG_ColorMap = 320; - static const int TYPE_BYTE = 1; - static const int TYPE_ASCII = 2; - static const int TYPE_SHORT = 3; - static const int TYPE_LONG = 4; - static const int TYPE_RATIONAL = 5; + static const int TYPE_BYTE = 1; + static const int TYPE_ASCII = 2; + static const int TYPE_SHORT = 3; + static const int TYPE_LONG = 4; + static const int TYPE_RATIONAL = 5; - /* Different compression schemes */ - static const int COMPRESSION_NONE = 1; - static const int COMPRESSION_CCITT_3_1 = 2; - static const int COMPRESSION_PACKBITS = 32773; + /* Different compression schemes */ + static const int COMPRESSION_NONE = 1; + static const int COMPRESSION_CCITT_3_1 = 2; + static const int COMPRESSION_PACKBITS = 32773; - static const int IFD_ENTRY_SIZE = 12; + static const int IFD_ENTRY_SIZE = 12; public this(TIFFRandomFileAccess file, bool isLittleEndian, ImageLoader loader) { - this.file = file; - this.isLittleEndian = isLittleEndian; - this.loader = loader; + this.file = file; + this.isLittleEndian = isLittleEndian; + this.loader = loader; } public this(ImageData image) { - this.image = image; + this.image = image; } /* PackBits decoder */ int decodePackBits(byte[] src, byte[] dest, int offsetDest) { - int destIndex = offsetDest; - int srcIndex = 0; - while (srcIndex < src.length) { - byte n = src[srcIndex]; - if (0 <= n && n <= 127) { - /* Copy next n+1 bytes literally */ + int destIndex = offsetDest; + int srcIndex = 0; + while (srcIndex < src.length) { + byte n = src[srcIndex]; + if (0 <= n && n <= 127) { + /* Copy next n+1 bytes literally */ System.arraycopy(src, ++srcIndex, dest, destIndex, n + 1); - srcIndex += n + 1; - destIndex += n + 1; - } else if (-127 <= n && n <= -1) { - /* Copy next byte -n+1 times */ - byte value = src[++srcIndex]; - for (int j = 0; j < -n + 1; j++) { - dest[destIndex++] = value; - } - srcIndex++; - } else { - /* Noop when n == -128 */ - srcIndex++; - } - } - /* Number of bytes copied */ - return destIndex - offsetDest; + srcIndex += n + 1; + destIndex += n + 1; + } else if (-127 <= n && n <= -1) { + /* Copy next byte -n+1 times */ + byte value = src[++srcIndex]; + for (int j = 0; j < -n + 1; j++) { + dest[destIndex++] = value; + } + srcIndex++; + } else { + /* Noop when n == -128 */ + srcIndex++; + } + } + /* Number of bytes copied */ + return destIndex - offsetDest; } int getEntryValue(int type, byte[] buffer, int index) { - return toInt(buffer, index + 8, type); + return toInt(buffer, index + 8, type); } void getEntryValue(int type, byte[] buffer, int index, int[] values) { - int start = index + 8; - int size; - int offset = toInt(buffer, start, TYPE_LONG); - switch (type) { - case TYPE_SHORT: size = 2; break; - case TYPE_LONG: size = 4; break; - case TYPE_RATIONAL: size = 8; break; - case TYPE_ASCII: - case TYPE_BYTE: size = 1; break; - default: SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); return; - } - if (values.length * size > 4) { - buffer = new byte[values.length * size]; - file.seek(offset); - file.read(buffer); - start = 0; - } - for (int i = 0; i < values.length; i++) { - values[i] = toInt(buffer, start + i * size, type); - } + int start = index + 8; + int size; + int offset = toInt(buffer, start, TYPE_LONG); + switch (type) { + case TYPE_SHORT: size = 2; break; + case TYPE_LONG: size = 4; break; + case TYPE_RATIONAL: size = 8; break; + case TYPE_ASCII: + case TYPE_BYTE: size = 1; break; + default: SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); return; + } + if (values.length * size > 4) { + buffer = new byte[values.length * size]; + file.seek(offset); + file.read(buffer); + start = 0; + } + for (int i = 0; i < values.length; i++) { + values[i] = toInt(buffer, start + i * size, type); + } } void decodePixels(ImageData image) { - /* Each row is byte aligned */ - byte[] imageData = new byte[(imageWidth * depth + 7) / 8 * imageLength]; - image.data = imageData; - int destIndex = 0; - int length = stripOffsets.length; - for (int i = 0; i < length; i++) { - /* Read a strip */ - byte[] data = new byte[](stripByteCounts[i]); - file.seek(stripOffsets[i]); - file.read(data); - if (compression == COMPRESSION_NONE) { + /* Each row is byte aligned */ + byte[] imageData = new byte[(imageWidth * depth + 7) / 8 * imageLength]; + image.data = imageData; + int destIndex = 0; + int length = stripOffsets.length; + for (int i = 0; i < length; i++) { + /* Read a strip */ + byte[] data = new byte[](stripByteCounts[i]); + file.seek(stripOffsets[i]); + file.read(data); + if (compression == COMPRESSION_NONE) { System.arraycopy(data, 0, imageData, destIndex, data.length); - destIndex += data.length; - } else if (compression == COMPRESSION_PACKBITS) { - destIndex += decodePackBits(data, imageData, destIndex); - } else if (compression == COMPRESSION_CCITT_3_1 || compression == 3) { - TIFFModifiedHuffmanCodec codec = new TIFFModifiedHuffmanCodec(); - int nRows = rowsPerStrip; - if (i == length -1) { - int n = imageLength % rowsPerStrip; - if (n != 0) nRows = n; - } - destIndex += codec.decode(data, imageData, destIndex, imageWidth, nRows); - } - if (loader.hasListeners()) { - loader.notifyListeners(new ImageLoaderEvent(loader, image, i, i == length - 1)); - } - } + destIndex += data.length; + } else if (compression == COMPRESSION_PACKBITS) { + destIndex += decodePackBits(data, imageData, destIndex); + } else if (compression == COMPRESSION_CCITT_3_1 || compression == 3) { + TIFFModifiedHuffmanCodec codec = new TIFFModifiedHuffmanCodec(); + int nRows = rowsPerStrip; + if (i == length -1) { + int n = imageLength % rowsPerStrip; + if (n != 0) nRows = n; + } + destIndex += codec.decode(data, imageData, destIndex, imageWidth, nRows); + } + if (loader.hasListeners()) { + loader.notifyListeners(new ImageLoaderEvent(loader, image, i, i == length - 1)); + } + } } PaletteData getColorMap() { - int numColors = 1 << bitsPerSample[0]; - /* R, G, B entries are 16 bit wide (2 bytes) */ - int numBytes = 3 * 2 * numColors; - byte[] buffer = new byte[numBytes]; - file.seek(colorMapOffset); - file.read(buffer); - RGB[] colors = new RGB[numColors]; - /** - * SWT does not support 16-bit depth color formats. - * Convert the 16-bit data to 8-bit data. - * The correct way to do this is to multiply each - * 16 bit value by the value: - * (2^8 - 1) / (2^16 - 1). - * The fast way to do this is just to drop the low - * byte of the 16-bit value. - */ - int offset = isLittleEndian ? 1 : 0; - int startG = 2 * numColors; - int startB = startG + 2 * numColors; - for (int i = 0; i < numColors; i++) { - int r = buffer[offset] & 0xFF; - int g = buffer[startG + offset] & 0xFF; - int b = buffer[startB + offset] & 0xFF; - colors[i] = new RGB(r, g, b); - offset += 2; - } - return new PaletteData(colors); + int numColors = 1 << bitsPerSample[0]; + /* R, G, B entries are 16 bit wide (2 bytes) */ + int numBytes = 3 * 2 * numColors; + byte[] buffer = new byte[numBytes]; + file.seek(colorMapOffset); + file.read(buffer); + RGB[] colors = new RGB[numColors]; + /** + * SWT does not support 16-bit depth color formats. + * Convert the 16-bit data to 8-bit data. + * The correct way to do this is to multiply each + * 16 bit value by the value: + * (2^8 - 1) / (2^16 - 1). + * The fast way to do this is just to drop the low + * byte of the 16-bit value. + */ + int offset = isLittleEndian ? 1 : 0; + int startG = 2 * numColors; + int startB = startG + 2 * numColors; + for (int i = 0; i < numColors; i++) { + int r = buffer[offset] & 0xFF; + int g = buffer[startG + offset] & 0xFF; + int b = buffer[startB + offset] & 0xFF; + colors[i] = new RGB(r, g, b); + offset += 2; + } + return new PaletteData(colors); } PaletteData getGrayPalette() { - int numColors = 1 << bitsPerSample[0]; - RGB[] rgbs = new RGB[numColors]; - for (int i = 0; i < numColors; i++) { - int value = i * 0xFF / (numColors - 1); - if (photometricInterpretation == 0) value = 0xFF - value; - rgbs[i] = new RGB(value, value, value); - } - return new PaletteData(rgbs); + int numColors = 1 << bitsPerSample[0]; + RGB[] rgbs = new RGB[numColors]; + for (int i = 0; i < numColors; i++) { + int value = i * 0xFF / (numColors - 1); + if (photometricInterpretation == 0) value = 0xFF - value; + rgbs[i] = new RGB(value, value, value); + } + return new PaletteData(rgbs); } PaletteData getRGBPalette(int bitsR, int bitsG, int bitsB) { - int blueMask = 0; - for (int i = 0; i < bitsB; i++) { - blueMask |= 1 << i; - } - int greenMask = 0; - for (int i = bitsB; i < bitsB + bitsG; i++) { - greenMask |= 1 << i; - } - int redMask = 0; - for (int i = bitsB + bitsG; i < bitsB + bitsG + bitsR; i++) { - redMask |= 1 << i; - } - return new PaletteData(redMask, greenMask, blueMask); + int blueMask = 0; + for (int i = 0; i < bitsB; i++) { + blueMask |= 1 << i; + } + int greenMask = 0; + for (int i = bitsB; i < bitsB + bitsG; i++) { + greenMask |= 1 << i; + } + int redMask = 0; + for (int i = bitsB + bitsG; i < bitsB + bitsG + bitsR; i++) { + redMask |= 1 << i; + } + return new PaletteData(redMask, greenMask, blueMask); } int formatStrips(int rowByteSize, int nbrRows, byte[] data, int maxStripByteSize, int offsetPostIFD, int extraBytes, int[][] strips) { - /* - * Calculate the nbr of required strips given the following requirements: - * - each strip should, if possible, not be greater than maxStripByteSize - * - each strip should contain 1 or more entire rows - * - * Format the strip fields arrays so that the image data is stored in one - * contiguous block. This block is stored after the IFD and after any tag - * info described in the IFD. - */ - int n, nbrRowsPerStrip; - if (rowByteSize > maxStripByteSize) { - /* Each strip contains 1 row */ - n = data.length / rowByteSize; - nbrRowsPerStrip = 1; - } else { - int nbr = (data.length + maxStripByteSize - 1) / maxStripByteSize; - nbrRowsPerStrip = nbrRows / nbr; - n = (nbrRows + nbrRowsPerStrip - 1) / nbrRowsPerStrip; - } - int stripByteSize = rowByteSize * nbrRowsPerStrip; + /* + * Calculate the nbr of required strips given the following requirements: + * - each strip should, if possible, not be greater than maxStripByteSize + * - each strip should contain 1 or more entire rows + * + * Format the strip fields arrays so that the image data is stored in one + * contiguous block. This block is stored after the IFD and after any tag + * info described in the IFD. + */ + int n, nbrRowsPerStrip; + if (rowByteSize > maxStripByteSize) { + /* Each strip contains 1 row */ + n = data.length / rowByteSize; + nbrRowsPerStrip = 1; + } else { + int nbr = (data.length + maxStripByteSize - 1) / maxStripByteSize; + nbrRowsPerStrip = nbrRows / nbr; + n = (nbrRows + nbrRowsPerStrip - 1) / nbrRowsPerStrip; + } + int stripByteSize = rowByteSize * nbrRowsPerStrip; - int[] offsets = new int[n]; - int[] counts = new int[n]; - /* - * Nbr of bytes between the end of the IFD directory and the start of - * the image data. Keep space for at least the offsets and counts - * data, each field being TYPE_LONG (4 bytes). If other tags require - * space between the IFD and the image block, use the extraBytes - * parameter. - * If there is only one strip, the offsets and counts data is stored - * directly in the IFD and we need not reserve space for it. - */ - int postIFDData = n == 1 ? 0 : n * 2 * 4; - int startOffset = offsetPostIFD + extraBytes + postIFDData; /* offset of image data */ + int[] offsets = new int[n]; + int[] counts = new int[n]; + /* + * Nbr of bytes between the end of the IFD directory and the start of + * the image data. Keep space for at least the offsets and counts + * data, each field being TYPE_LONG (4 bytes). If other tags require + * space between the IFD and the image block, use the extraBytes + * parameter. + * If there is only one strip, the offsets and counts data is stored + * directly in the IFD and we need not reserve space for it. + */ + int postIFDData = n == 1 ? 0 : n * 2 * 4; + int startOffset = offsetPostIFD + extraBytes + postIFDData; /* offset of image data */ - int offset = startOffset; - for (int i = 0; i < n; i++) { - /* - * Store all strips sequentially to allow us - * to copy all pixels in one contiguous area. - */ - offsets[i] = offset; - counts[i] = stripByteSize; - offset += stripByteSize; - } - /* The last strip may contain fewer rows */ - int mod = data.length % stripByteSize; - if (mod != 0) counts[counts.length - 1] = mod; + int offset = startOffset; + for (int i = 0; i < n; i++) { + /* + * Store all strips sequentially to allow us + * to copy all pixels in one contiguous area. + */ + offsets[i] = offset; + counts[i] = stripByteSize; + offset += stripByteSize; + } + /* The last strip may contain fewer rows */ + int mod = data.length % stripByteSize; + if (mod != 0) counts[counts.length - 1] = mod; - strips[0] = offsets; - strips[1] = counts; - return nbrRowsPerStrip; + strips[0] = offsets; + strips[1] = counts; + return nbrRowsPerStrip; } int[] formatColorMap(RGB[] rgbs) { - /* - * In a TIFF ColorMap, all red come first, followed by - * green and blue. All values must be converted from - * 8 bit to 16 bit. - */ - int[] colorMap = new int[rgbs.length * 3]; - int offsetGreen = rgbs.length; - int offsetBlue = rgbs.length * 2; - for (int i = 0; i < rgbs.length; i++) { - colorMap[i] = rgbs[i].red << 8 | rgbs[i].red; - colorMap[i + offsetGreen] = rgbs[i].green << 8 | rgbs[i].green; - colorMap[i + offsetBlue] = rgbs[i].blue << 8 | rgbs[i].blue; - } - return colorMap; + /* + * In a TIFF ColorMap, all red come first, followed by + * green and blue. All values must be converted from + * 8 bit to 16 bit. + */ + int[] colorMap = new int[rgbs.length * 3]; + int offsetGreen = rgbs.length; + int offsetBlue = rgbs.length * 2; + for (int i = 0; i < rgbs.length; i++) { + colorMap[i] = rgbs[i].red << 8 | rgbs[i].red; + colorMap[i + offsetGreen] = rgbs[i].green << 8 | rgbs[i].green; + colorMap[i + offsetBlue] = rgbs[i].blue << 8 | rgbs[i].blue; + } + return colorMap; } void parseEntries(byte[] buffer) { - for (int offset = 0; offset < buffer.length; offset += IFD_ENTRY_SIZE) { - int tag = toInt(buffer, offset, TYPE_SHORT); - int type = toInt(buffer, offset + 2, TYPE_SHORT); - int count = toInt(buffer, offset + 4, TYPE_LONG); - switch (tag) { - case TAG_ImageWidth: { - imageWidth = getEntryValue(type, buffer, offset); - break; - } - case TAG_ImageLength: { - imageLength = getEntryValue(type, buffer, offset); - break; - } - case TAG_BitsPerSample: { - if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); - bitsPerSample = new int[count]; - getEntryValue(type, buffer, offset, bitsPerSample); - break; - } - case TAG_Compression: { - compression = getEntryValue(type, buffer, offset); - break; - } - case TAG_PhotometricInterpretation: { - photometricInterpretation = getEntryValue(type, buffer, offset); - break; - } - case TAG_StripOffsets: { - if (type != TYPE_LONG && type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); - stripOffsets = new int[count]; - getEntryValue(type, buffer, offset, stripOffsets); - break; - } - case TAG_SamplesPerPixel: { - if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); - samplesPerPixel = getEntryValue(type, buffer, offset); - /* Only the basic 1 and 3 values are supported */ - if (samplesPerPixel != 1 && samplesPerPixel != 3) SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - break; - } - case TAG_RowsPerStrip: { - rowsPerStrip = getEntryValue(type, buffer, offset); - break; - } - case TAG_StripByteCounts: { - stripByteCounts = new int[count]; - getEntryValue(type, buffer, offset, stripByteCounts); - break; - } - case TAG_XResolution: { - /* Ignored */ - break; - } - case TAG_YResolution: { - /* Ignored */ - break; - } - case TAG_T4Options: { - if (type != TYPE_LONG) SWT.error(SWT.ERROR_INVALID_IMAGE); - t4Options = getEntryValue(type, buffer, offset); - if ((t4Options & 0x1) == 1) { - /* 2-dimensional coding is not supported */ - SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - } - break; - } - case TAG_ResolutionUnit: { - /* Ignored */ - break; - } - case TAG_ColorMap: { - if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); - /* Get the offset of the colorMap (use TYPE_LONG) */ - colorMapOffset = getEntryValue(TYPE_LONG, buffer, offset); - break; - } + for (int offset = 0; offset < buffer.length; offset += IFD_ENTRY_SIZE) { + int tag = toInt(buffer, offset, TYPE_SHORT); + int type = toInt(buffer, offset + 2, TYPE_SHORT); + int count = toInt(buffer, offset + 4, TYPE_LONG); + switch (tag) { + case TAG_ImageWidth: { + imageWidth = getEntryValue(type, buffer, offset); + break; + } + case TAG_ImageLength: { + imageLength = getEntryValue(type, buffer, offset); + break; + } + case TAG_BitsPerSample: { + if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); + bitsPerSample = new int[count]; + getEntryValue(type, buffer, offset, bitsPerSample); + break; + } + case TAG_Compression: { + compression = getEntryValue(type, buffer, offset); + break; + } + case TAG_PhotometricInterpretation: { + photometricInterpretation = getEntryValue(type, buffer, offset); + break; + } + case TAG_StripOffsets: { + if (type != TYPE_LONG && type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); + stripOffsets = new int[count]; + getEntryValue(type, buffer, offset, stripOffsets); + break; + } + case TAG_SamplesPerPixel: { + if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); + samplesPerPixel = getEntryValue(type, buffer, offset); + /* Only the basic 1 and 3 values are supported */ + if (samplesPerPixel != 1 && samplesPerPixel != 3) SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + break; + } + case TAG_RowsPerStrip: { + rowsPerStrip = getEntryValue(type, buffer, offset); + break; + } + case TAG_StripByteCounts: { + stripByteCounts = new int[count]; + getEntryValue(type, buffer, offset, stripByteCounts); + break; + } + case TAG_XResolution: { + /* Ignored */ + break; + } + case TAG_YResolution: { + /* Ignored */ + break; + } + case TAG_T4Options: { + if (type != TYPE_LONG) SWT.error(SWT.ERROR_INVALID_IMAGE); + t4Options = getEntryValue(type, buffer, offset); + if ((t4Options & 0x1) == 1) { + /* 2-dimensional coding is not supported */ + SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + } + break; + } + case TAG_ResolutionUnit: { + /* Ignored */ + break; + } + case TAG_ColorMap: { + if (type != TYPE_SHORT) SWT.error(SWT.ERROR_INVALID_IMAGE); + /* Get the offset of the colorMap (use TYPE_LONG) */ + colorMapOffset = getEntryValue(TYPE_LONG, buffer, offset); + break; + } default: - } - } + } + } } public ImageData read() { - /* Set TIFF default values */ - bitsPerSample = [1]; - colorMapOffset = NO_VALUE; - compression = 1; - imageLength = NO_VALUE; - imageWidth = NO_VALUE; - photometricInterpretation = NO_VALUE; - rowsPerStrip = Integer.MAX_VALUE; - samplesPerPixel = 1; - stripByteCounts = null; - stripOffsets = null; + /* Set TIFF default values */ + bitsPerSample = [1]; + colorMapOffset = NO_VALUE; + compression = 1; + imageLength = NO_VALUE; + imageWidth = NO_VALUE; + photometricInterpretation = NO_VALUE; + rowsPerStrip = Integer.MAX_VALUE; + samplesPerPixel = 1; + stripByteCounts = null; + stripOffsets = null; - byte[] buffer = new byte[2]; - file.read(buffer); - int numberEntries = toInt(buffer, 0, TYPE_SHORT); - buffer = new byte[IFD_ENTRY_SIZE * numberEntries]; - file.read(buffer); - parseEntries(buffer); + byte[] buffer = new byte[2]; + file.read(buffer); + int numberEntries = toInt(buffer, 0, TYPE_SHORT); + buffer = new byte[IFD_ENTRY_SIZE * numberEntries]; + file.read(buffer); + parseEntries(buffer); - PaletteData palette = null; - depth = 0; - switch (photometricInterpretation) { - case 0: - case 1: { - /* Bilevel or Grayscale image */ - palette = getGrayPalette(); - depth = bitsPerSample[0]; - break; - } - case 2: { - /* RGB image */ - if (colorMapOffset != NO_VALUE) SWT.error(SWT.ERROR_INVALID_IMAGE); - /* SamplesPerPixel 3 is the only value supported */ - palette = getRGBPalette(bitsPerSample[0], bitsPerSample[1], bitsPerSample[2]); - depth = bitsPerSample[0] + bitsPerSample[1] + bitsPerSample[2]; - break; - } - case 3: { - /* Palette Color image */ - if (colorMapOffset == NO_VALUE) SWT.error(SWT.ERROR_INVALID_IMAGE); - palette = getColorMap(); - depth = bitsPerSample[0]; - break; - } - default: { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - } + PaletteData palette = null; + depth = 0; + switch (photometricInterpretation) { + case 0: + case 1: { + /* Bilevel or Grayscale image */ + palette = getGrayPalette(); + depth = bitsPerSample[0]; + break; + } + case 2: { + /* RGB image */ + if (colorMapOffset != NO_VALUE) SWT.error(SWT.ERROR_INVALID_IMAGE); + /* SamplesPerPixel 3 is the only value supported */ + palette = getRGBPalette(bitsPerSample[0], bitsPerSample[1], bitsPerSample[2]); + depth = bitsPerSample[0] + bitsPerSample[1] + bitsPerSample[2]; + break; + } + case 3: { + /* Palette Color image */ + if (colorMapOffset == NO_VALUE) SWT.error(SWT.ERROR_INVALID_IMAGE); + palette = getColorMap(); + depth = bitsPerSample[0]; + break; + } + default: { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + } - ImageData image = ImageData.internal_new( - imageWidth, - imageLength, - depth, - palette, - 1, - null, - 0, - null, - null, - -1, - -1, - SWT.IMAGE_TIFF, - 0, - 0, - 0, - 0); - decodePixels(image); - return image; + ImageData image = ImageData.internal_new( + imageWidth, + imageLength, + depth, + palette, + 1, + null, + 0, + null, + null, + -1, + -1, + SWT.IMAGE_TIFF, + 0, + 0, + 0, + 0); + decodePixels(image); + return image; } int toInt(byte[] buffer, int i, int type) { - if (type == TYPE_LONG) { - return isLittleEndian ? - (buffer[i] & 0xFF) | ((buffer[i + 1] & 0xFF) << 8) | ((buffer[i + 2] & 0xFF) << 16) | ((buffer[i + 3] & 0xFF) << 24) : - (buffer[i + 3] & 0xFF) | ((buffer[i + 2] & 0xFF) << 8) | ((buffer[i + 1] & 0xFF) << 16) | ((buffer[i] & 0xFF) << 24); - } - if (type == TYPE_SHORT) { - return isLittleEndian ? - (buffer[i] & 0xFF) | ((buffer[i + 1] & 0xFF) << 8) : - (buffer[i + 1] & 0xFF) | ((buffer[i] & 0xFF) << 8); - } - /* Invalid type */ - SWT.error(SWT.ERROR_INVALID_IMAGE); - return -1; + if (type == TYPE_LONG) { + return isLittleEndian ? + (buffer[i] & 0xFF) | ((buffer[i + 1] & 0xFF) << 8) | ((buffer[i + 2] & 0xFF) << 16) | ((buffer[i + 3] & 0xFF) << 24) : + (buffer[i + 3] & 0xFF) | ((buffer[i + 2] & 0xFF) << 8) | ((buffer[i + 1] & 0xFF) << 16) | ((buffer[i] & 0xFF) << 24); + } + if (type == TYPE_SHORT) { + return isLittleEndian ? + (buffer[i] & 0xFF) | ((buffer[i + 1] & 0xFF) << 8) : + (buffer[i + 1] & 0xFF) | ((buffer[i] & 0xFF) << 8); + } + /* Invalid type */ + SWT.error(SWT.ERROR_INVALID_IMAGE); + return -1; } void write(int photometricInterpretation) { - bool isRGB = photometricInterpretation == 2; - bool isColorMap = photometricInterpretation == 3; - bool isBiLevel = photometricInterpretation == 0 || photometricInterpretation == 1; + bool isRGB = photometricInterpretation == 2; + bool isColorMap = photometricInterpretation == 3; + bool isBiLevel = photometricInterpretation == 0 || photometricInterpretation == 1; - int imageWidth = image.width; - int imageLength = image.height; - int rowByteSize = image.bytesPerLine; + int imageWidth = image.width; + int imageLength = image.height; + int rowByteSize = image.bytesPerLine; - int numberEntries = isBiLevel ? 9 : 11; - int lengthDirectory = 2 + 12 * numberEntries + 4; - /* Offset following the header and the directory */ - int nextOffset = 8 + lengthDirectory; + int numberEntries = isBiLevel ? 9 : 11; + int lengthDirectory = 2 + 12 * numberEntries + 4; + /* Offset following the header and the directory */ + int nextOffset = 8 + lengthDirectory; - /* Extra space used by XResolution and YResolution values */ - int extraBytes = 16; + /* Extra space used by XResolution and YResolution values */ + int extraBytes = 16; - int[] colorMap = null; - if (isColorMap) { - PaletteData palette = image.palette; - RGB[] rgbs = palette.getRGBs(); - colorMap = formatColorMap(rgbs); - /* The number of entries of the Color Map must match the bitsPerSample field */ - if (colorMap.length != 3 * 1 << image.depth) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - /* Extra space used by ColorMap values */ - extraBytes += colorMap.length * 2; - } - if (isRGB) { - /* Extra space used by BitsPerSample values */ - extraBytes += 6; - } - /* TIFF recommends storing the data in strips of no more than 8 Ko */ - byte[] data = image.data; - int[][] strips = new int[][](2); - int nbrRowsPerStrip = formatStrips(rowByteSize, imageLength, data, 8192, nextOffset, extraBytes, strips); - int[] stripOffsets = strips[0]; - int[] stripByteCounts = strips[1]; + int[] colorMap = null; + if (isColorMap) { + PaletteData palette = image.palette; + RGB[] rgbs = palette.getRGBs(); + colorMap = formatColorMap(rgbs); + /* The number of entries of the Color Map must match the bitsPerSample field */ + if (colorMap.length != 3 * 1 << image.depth) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + /* Extra space used by ColorMap values */ + extraBytes += colorMap.length * 2; + } + if (isRGB) { + /* Extra space used by BitsPerSample values */ + extraBytes += 6; + } + /* TIFF recommends storing the data in strips of no more than 8 Ko */ + byte[] data = image.data; + int[][] strips = new int[][](2); + int nbrRowsPerStrip = formatStrips(rowByteSize, imageLength, data, 8192, nextOffset, extraBytes, strips); + int[] stripOffsets = strips[0]; + int[] stripByteCounts = strips[1]; - int bitsPerSampleOffset = NO_VALUE; - if (isRGB) { - bitsPerSampleOffset = nextOffset; - nextOffset += 6; - } - int stripOffsetsOffset = NO_VALUE, stripByteCountsOffset = NO_VALUE; - int xResolutionOffset, yResolutionOffset, colorMapOffset = NO_VALUE; - int cnt = stripOffsets.length; - if (cnt > 1) { - stripOffsetsOffset = nextOffset; - nextOffset += 4 * cnt; - stripByteCountsOffset = nextOffset; - nextOffset += 4 * cnt; - } - xResolutionOffset = nextOffset; - nextOffset += 8; - yResolutionOffset = nextOffset; - nextOffset += 8; - if (isColorMap) { - colorMapOffset = nextOffset; - nextOffset += colorMap.length * 2; - } - /* TIFF header */ - writeHeader(); + int bitsPerSampleOffset = NO_VALUE; + if (isRGB) { + bitsPerSampleOffset = nextOffset; + nextOffset += 6; + } + int stripOffsetsOffset = NO_VALUE, stripByteCountsOffset = NO_VALUE; + int xResolutionOffset, yResolutionOffset, colorMapOffset = NO_VALUE; + int cnt = stripOffsets.length; + if (cnt > 1) { + stripOffsetsOffset = nextOffset; + nextOffset += 4 * cnt; + stripByteCountsOffset = nextOffset; + nextOffset += 4 * cnt; + } + xResolutionOffset = nextOffset; + nextOffset += 8; + yResolutionOffset = nextOffset; + nextOffset += 8; + if (isColorMap) { + colorMapOffset = nextOffset; + nextOffset += colorMap.length * 2; + } + /* TIFF header */ + writeHeader(); - /* Image File Directory */ - ostr.writeShort(numberEntries); - writeEntry(TAG_ImageWidth, TYPE_LONG, 1, imageWidth); - writeEntry(TAG_ImageLength, TYPE_LONG, 1, imageLength); - if (isColorMap) writeEntry(TAG_BitsPerSample, TYPE_SHORT, 1, image.depth); - if (isRGB) writeEntry(TAG_BitsPerSample, TYPE_SHORT, 3, bitsPerSampleOffset); - writeEntry(TAG_Compression, TYPE_SHORT, 1, COMPRESSION_NONE); - writeEntry(TAG_PhotometricInterpretation, TYPE_SHORT, 1, photometricInterpretation); - writeEntry(TAG_StripOffsets, TYPE_LONG, cnt, cnt > 1 ? stripOffsetsOffset : stripOffsets[0]); - if (isRGB) writeEntry(TAG_SamplesPerPixel, TYPE_SHORT, 1, 3); - writeEntry(TAG_RowsPerStrip, TYPE_LONG, 1, nbrRowsPerStrip); - writeEntry(TAG_StripByteCounts, TYPE_LONG, cnt, cnt > 1 ? stripByteCountsOffset : stripByteCounts[0]); - writeEntry(TAG_XResolution, TYPE_RATIONAL, 1, xResolutionOffset); - writeEntry(TAG_YResolution, TYPE_RATIONAL, 1, yResolutionOffset); - if (isColorMap) writeEntry(TAG_ColorMap, TYPE_SHORT, colorMap.length, colorMapOffset); - /* Offset of next IFD (0 for last IFD) */ - ostr.writeInt(0); + /* Image File Directory */ + ostr.writeShort(numberEntries); + writeEntry(TAG_ImageWidth, TYPE_LONG, 1, imageWidth); + writeEntry(TAG_ImageLength, TYPE_LONG, 1, imageLength); + if (isColorMap) writeEntry(TAG_BitsPerSample, TYPE_SHORT, 1, image.depth); + if (isRGB) writeEntry(TAG_BitsPerSample, TYPE_SHORT, 3, bitsPerSampleOffset); + writeEntry(TAG_Compression, TYPE_SHORT, 1, COMPRESSION_NONE); + writeEntry(TAG_PhotometricInterpretation, TYPE_SHORT, 1, photometricInterpretation); + writeEntry(TAG_StripOffsets, TYPE_LONG, cnt, cnt > 1 ? stripOffsetsOffset : stripOffsets[0]); + if (isRGB) writeEntry(TAG_SamplesPerPixel, TYPE_SHORT, 1, 3); + writeEntry(TAG_RowsPerStrip, TYPE_LONG, 1, nbrRowsPerStrip); + writeEntry(TAG_StripByteCounts, TYPE_LONG, cnt, cnt > 1 ? stripByteCountsOffset : stripByteCounts[0]); + writeEntry(TAG_XResolution, TYPE_RATIONAL, 1, xResolutionOffset); + writeEntry(TAG_YResolution, TYPE_RATIONAL, 1, yResolutionOffset); + if (isColorMap) writeEntry(TAG_ColorMap, TYPE_SHORT, colorMap.length, colorMapOffset); + /* Offset of next IFD (0 for last IFD) */ + ostr.writeInt(0); - /* Values longer than 4 bytes Section */ + /* Values longer than 4 bytes Section */ - /* BitsPerSample 8,8,8 */ - if (isRGB) for (int i = 0; i < 3; i++) ostr.writeShort(8); - if (cnt > 1) { - for (int i = 0; i < cnt; i++) ostr.writeInt(stripOffsets[i]); - for (int i = 0; i < cnt; i++) ostr.writeInt(stripByteCounts[i]); - } - /* XResolution and YResolution set to 300 dpi */ - for (int i = 0; i < 2; i++) { - ostr.writeInt(300); - ostr.writeInt(1); - } - /* ColorMap */ - if (isColorMap) for (int i = 0; i < colorMap.length; i++) ostr.writeShort(colorMap[i]); + /* BitsPerSample 8,8,8 */ + if (isRGB) for (int i = 0; i < 3; i++) ostr.writeShort(8); + if (cnt > 1) { + for (int i = 0; i < cnt; i++) ostr.writeInt(stripOffsets[i]); + for (int i = 0; i < cnt; i++) ostr.writeInt(stripByteCounts[i]); + } + /* XResolution and YResolution set to 300 dpi */ + for (int i = 0; i < 2; i++) { + ostr.writeInt(300); + ostr.writeInt(1); + } + /* ColorMap */ + if (isColorMap) for (int i = 0; i < colorMap.length; i++) ostr.writeShort(colorMap[i]); - /* Image Data */ - ostr.write(data); + /* Image Data */ + ostr.write(data); } void writeEntry(short tag, int type, int count, int value) { - ostr.writeShort(tag); - ostr.writeShort(type); - ostr.writeInt(count); - ostr.writeInt(value); + ostr.writeShort(tag); + ostr.writeShort(type); + ostr.writeInt(count); + ostr.writeInt(value); } void writeHeader() { - /* little endian */ - ostr.write(0x49); - ostr.write(0x49); + /* little endian */ + ostr.write(0x49); + ostr.write(0x49); - /* TIFF identifier */ - ostr.writeShort(42); - /* - * Offset of the first IFD is chosen to be 8. - * It is word aligned and immediately after this header. - */ - ostr.writeInt(8); + /* TIFF identifier */ + ostr.writeShort(42); + /* + * Offset of the first IFD is chosen to be 8. + * It is word aligned and immediately after this header. + */ + ostr.writeInt(8); } void writeToStream(LEDataOutputStream byteStream) { - ostr = byteStream; - int photometricInterpretation = -1; + ostr = byteStream; + int photometricInterpretation = -1; - /* Scanline pad must be 1 */ - if (image.scanlinePad != 1) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - switch (image.depth) { - case 1: { - /* Palette must be black and white or white and black */ - PaletteData palette = image.palette; - RGB[] rgbs = palette.colors; - if (palette.isDirect || rgbs == null || rgbs.length != 2) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - RGB rgb0 = rgbs[0]; - RGB rgb1 = rgbs[1]; - if (!(rgb0.red == rgb0.green && rgb0.green == rgb0.blue && - rgb1.red == rgb1.green && rgb1.green == rgb1.blue && - ((rgb0.red == 0x0 && rgb1.red == 0xFF) || (rgb0.red == 0xFF && rgb1.red == 0x0)))) { - SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - } - /* 0 means a color index of 0 is imaged as white */ - photometricInterpretation = image.palette.colors[0].red == 0xFF ? 0 : 1; - break; - } - case 4: - case 8: { - photometricInterpretation = 3; - break; - } - case 24: { - photometricInterpretation = 2; - break; - } - default: { - SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); - } - } - write(photometricInterpretation); + /* Scanline pad must be 1 */ + if (image.scanlinePad != 1) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + switch (image.depth) { + case 1: { + /* Palette must be black and white or white and black */ + PaletteData palette = image.palette; + RGB[] rgbs = palette.colors; + if (palette.isDirect || rgbs == null || rgbs.length != 2) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + RGB rgb0 = rgbs[0]; + RGB rgb1 = rgbs[1]; + if (!(rgb0.red == rgb0.green && rgb0.green == rgb0.blue && + rgb1.red == rgb1.green && rgb1.green == rgb1.blue && + ((rgb0.red == 0x0 && rgb1.red == 0xFF) || (rgb0.red == 0xFF && rgb1.red == 0x0)))) { + SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + } + /* 0 means a color index of 0 is imaged as white */ + photometricInterpretation = image.palette.colors[0].red == 0xFF ? 0 : 1; + break; + } + case 4: + case 8: { + photometricInterpretation = 3; + break; + } + case 24: { + photometricInterpretation = 2; + break; + } + default: { + SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); + } + } + write(photometricInterpretation); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/TIFFFileFormat.d --- a/dwt/internal/image/TIFFFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/TIFFFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -26,58 +26,58 @@ final class TIFFFileFormat : FileFormat { bool isFileFormat(LEDataInputStream stream) { - try { - byte[] header = new byte[4]; - stream.read(header); - stream.unread(header); - if (header[0] != header[1]) return false; - if (!(header[0] == 0x49 && header[2] == 42 && header[3] == 0) && - !(header[0] == 0x4d && header[2] == 0 && header[3] == 42)) { - return false; - } - return true; - } catch (TracedException e) { - return false; - } + try { + byte[] header = new byte[4]; + stream.read(header); + stream.unread(header); + if (header[0] != header[1]) return false; + if (!(header[0] == 0x49 && header[2] == 42 && header[3] == 0) && + !(header[0] == 0x4d && header[2] == 0 && header[3] == 42)) { + return false; + } + return true; + } catch (TracedException e) { + return false; + } } ImageData[] loadFromByteStream() { - byte[] header = new byte[8]; - bool isLittleEndian; - ImageData[] images = new ImageData[0]; - TIFFRandomFileAccess file = new TIFFRandomFileAccess(inputStream); - try { - file.read(header); - if (header[0] != header[1]) SWT.error(SWT.ERROR_INVALID_IMAGE); - if (!(header[0] == 0x49 && header[2] == 42 && header[3] == 0) && - !(header[0] == 0x4d && header[2] == 0 && header[3] == 42)) { - SWT.error(SWT.ERROR_INVALID_IMAGE); - } - isLittleEndian = header[0] == 0x49; - int offset = isLittleEndian ? - (header[4] & 0xFF) | ((header[5] & 0xFF) << 8) | ((header[6] & 0xFF) << 16) | ((header[7] & 0xFF) << 24) : - (header[7] & 0xFF) | ((header[6] & 0xFF) << 8) | ((header[5] & 0xFF) << 16) | ((header[4] & 0xFF) << 24); - file.seek(offset); - TIFFDirectory directory = new TIFFDirectory(file, isLittleEndian, loader); - ImageData image = directory.read(); - /* A baseline reader is only expected to read the first directory */ - images = [image]; - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return images; + byte[] header = new byte[8]; + bool isLittleEndian; + ImageData[] images = new ImageData[0]; + TIFFRandomFileAccess file = new TIFFRandomFileAccess(inputStream); + try { + file.read(header); + if (header[0] != header[1]) SWT.error(SWT.ERROR_INVALID_IMAGE); + if (!(header[0] == 0x49 && header[2] == 42 && header[3] == 0) && + !(header[0] == 0x4d && header[2] == 0 && header[3] == 42)) { + SWT.error(SWT.ERROR_INVALID_IMAGE); + } + isLittleEndian = header[0] == 0x49; + int offset = isLittleEndian ? + (header[4] & 0xFF) | ((header[5] & 0xFF) << 8) | ((header[6] & 0xFF) << 16) | ((header[7] & 0xFF) << 24) : + (header[7] & 0xFF) | ((header[6] & 0xFF) << 8) | ((header[5] & 0xFF) << 16) | ((header[4] & 0xFF) << 24); + file.seek(offset); + TIFFDirectory directory = new TIFFDirectory(file, isLittleEndian, loader); + ImageData image = directory.read(); + /* A baseline reader is only expected to read the first directory */ + images = [image]; + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return images; } void unloadIntoByteStream(ImageLoader loader) { - /* We do not currently support writing multi-page tiff, - * so we use the first image data in the loader's array. */ - ImageData image = loader.data[0]; - TIFFDirectory directory = new TIFFDirectory(image); - try { - directory.writeToStream(outputStream); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + /* We do not currently support writing multi-page tiff, + * so we use the first image data in the loader's array. */ + ImageData image = loader.data[0]; + TIFFDirectory directory = new TIFFDirectory(image); + try { + directory.writeToStream(outputStream); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/TIFFModifiedHuffmanCodec.d --- a/dwt/internal/image/TIFFModifiedHuffmanCodec.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/TIFFModifiedHuffmanCodec.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -20,198 +20,198 @@ * (TIFF compression type 3 option 1D) */ final class TIFFModifiedHuffmanCodec { - static final short[][][] BLACK_CODE = [ - /* 2 bits */ - [[ cast(short)2, 3], [ cast(short)3, 2]], - /* 3 bits */ - [[ cast(short)2, 1], [ cast(short)3, 4]], - /* 4 bits */ - [[ cast(short)2, 6], [ cast(short)3, 5]], - /* 5 bits */ - [[ cast(short)3, 7]], - /* 6 bits */ - [[ cast(short)4, 9], [ cast(short)5, 8]], - /* 7 bits */ - [[ cast(short)4, 10], [ cast(short)5, 11], [ cast(short)7, 12]], - /* 8 bits */ - [[ cast(short)4, 13], [ cast(short)7, 14]], - /* 9 bits */ - [[ cast(short)24, 15]], - /* 10 bits */ - [[ cast(short)8, 18], [ cast(short)15, 64], [ cast(short)23, 16], [ cast(short)24, 17], [ cast(short)55, 0]], - /* 11 bits */ - [/* EOL */[ cast(short)0, -1], [ cast(short)8, 1792], [ cast(short)23, 24], [ cast(short)24, 25], [ cast(short)40, 23], [ cast(short)55, 22], [ cast(short)103, 19], - [ cast(short)104, 20], [ cast(short)108, 21], [ cast(short)12, 1856], [ cast(short)13, 1920]], - /* 12 bits */ - [[ cast(short)18, 1984], [ cast(short)19, 2048], [ cast(short)20, 2112], [ cast(short)21, 2176], [ cast(short)22, 2240], [ cast(short)23, 2304], - [ cast(short)28, 2368], [ cast(short)29, 2432], [ cast(short)30, 2496], [ cast(short)31, 2560], [ cast(short)36, 52], [ cast(short)39, 55], [ cast(short)40, 56], - [ cast(short)43, 59], [ cast(short)44, 60], [ cast(short)51, 320], [ cast(short)52, 384], [ cast(short)53, 448], [ cast(short)55, 53], [ cast(short)56, 54], [ cast(short)82, 50], - [ cast(short)83, 51], [ cast(short)84, 44], [ cast(short)85, 45], [ cast(short)86, 46], [ cast(short)87, 47], [ cast(short)88, 57], [ cast(short)89, 58], [ cast(short)90, 61], - [ cast(short)91, 256], [ cast(short)100, 48], [ cast(short)101, 49], [ cast(short)102, 62], [ cast(short)103, 63], [ cast(short)104, 30], [ cast(short)105, 31], - [ cast(short)106, 32], [ cast(short)107, 33], [ cast(short)108, 40], [ cast(short)109, 41], [ cast(short)200, 128], [ cast(short)201, 192], [ cast(short)202, 26], - [ cast(short)203, 27], [ cast(short)204, 28], [ cast(short)205, 29], [ cast(short)210, 34], [ cast(short)211, 35], [ cast(short)212, 36], [ cast(short)213, 37], - [ cast(short)214, 38], [ cast(short)215, 39], [ cast(short)218, 42], [ cast(short)219, 43]], - /* 13 bits */ - [[ cast(short)74, 640], [ cast(short)75, 704], [ cast(short)76, 768], [ cast(short)77, 832], [ cast(short)82, 1280], [ cast(short)83, 1344], [ cast(short)84, 1408], - [ cast(short)85, 1472], [ cast(short)90, 1536], [ cast(short)91, 1600], [ cast(short)100, 1664], [ cast(short)101, 1728], [ cast(short)108, 512], - [ cast(short)109, 576], [ cast(short)114, 896], [ cast(short)115, 960], [ cast(short)116, 1024], [ cast(short)117, 1088], [ cast(short)118, 1152], - [ cast(short)119, 1216]] - ]; + static final short[][][] BLACK_CODE = [ + /* 2 bits */ + [[ cast(short)2, 3], [ cast(short)3, 2]], + /* 3 bits */ + [[ cast(short)2, 1], [ cast(short)3, 4]], + /* 4 bits */ + [[ cast(short)2, 6], [ cast(short)3, 5]], + /* 5 bits */ + [[ cast(short)3, 7]], + /* 6 bits */ + [[ cast(short)4, 9], [ cast(short)5, 8]], + /* 7 bits */ + [[ cast(short)4, 10], [ cast(short)5, 11], [ cast(short)7, 12]], + /* 8 bits */ + [[ cast(short)4, 13], [ cast(short)7, 14]], + /* 9 bits */ + [[ cast(short)24, 15]], + /* 10 bits */ + [[ cast(short)8, 18], [ cast(short)15, 64], [ cast(short)23, 16], [ cast(short)24, 17], [ cast(short)55, 0]], + /* 11 bits */ + [/* EOL */[ cast(short)0, -1], [ cast(short)8, 1792], [ cast(short)23, 24], [ cast(short)24, 25], [ cast(short)40, 23], [ cast(short)55, 22], [ cast(short)103, 19], + [ cast(short)104, 20], [ cast(short)108, 21], [ cast(short)12, 1856], [ cast(short)13, 1920]], + /* 12 bits */ + [[ cast(short)18, 1984], [ cast(short)19, 2048], [ cast(short)20, 2112], [ cast(short)21, 2176], [ cast(short)22, 2240], [ cast(short)23, 2304], + [ cast(short)28, 2368], [ cast(short)29, 2432], [ cast(short)30, 2496], [ cast(short)31, 2560], [ cast(short)36, 52], [ cast(short)39, 55], [ cast(short)40, 56], + [ cast(short)43, 59], [ cast(short)44, 60], [ cast(short)51, 320], [ cast(short)52, 384], [ cast(short)53, 448], [ cast(short)55, 53], [ cast(short)56, 54], [ cast(short)82, 50], + [ cast(short)83, 51], [ cast(short)84, 44], [ cast(short)85, 45], [ cast(short)86, 46], [ cast(short)87, 47], [ cast(short)88, 57], [ cast(short)89, 58], [ cast(short)90, 61], + [ cast(short)91, 256], [ cast(short)100, 48], [ cast(short)101, 49], [ cast(short)102, 62], [ cast(short)103, 63], [ cast(short)104, 30], [ cast(short)105, 31], + [ cast(short)106, 32], [ cast(short)107, 33], [ cast(short)108, 40], [ cast(short)109, 41], [ cast(short)200, 128], [ cast(short)201, 192], [ cast(short)202, 26], + [ cast(short)203, 27], [ cast(short)204, 28], [ cast(short)205, 29], [ cast(short)210, 34], [ cast(short)211, 35], [ cast(short)212, 36], [ cast(short)213, 37], + [ cast(short)214, 38], [ cast(short)215, 39], [ cast(short)218, 42], [ cast(short)219, 43]], + /* 13 bits */ + [[ cast(short)74, 640], [ cast(short)75, 704], [ cast(short)76, 768], [ cast(short)77, 832], [ cast(short)82, 1280], [ cast(short)83, 1344], [ cast(short)84, 1408], + [ cast(short)85, 1472], [ cast(short)90, 1536], [ cast(short)91, 1600], [ cast(short)100, 1664], [ cast(short)101, 1728], [ cast(short)108, 512], + [ cast(short)109, 576], [ cast(short)114, 896], [ cast(short)115, 960], [ cast(short)116, 1024], [ cast(short)117, 1088], [ cast(short)118, 1152], + [ cast(short)119, 1216]] + ]; - static final short[][][] WHITE_CODE = [ - /* 4 bits */ - [[ cast(short)7, 2], [ cast(short)8, 3], [ cast(short)11, 4], [ cast(short)12, 5], [ cast(short)14, 6], [ cast(short)15, 7]], - /* 5 bits */ - [[ cast(short)7, 10], [ cast(short)8, 11], [ cast(short)18, 128], [ cast(short)19, 8], [ cast(short)20, 9], [ cast(short)27, 64]], - /* 6 bits */ - [[ cast(short)3, 13], [ cast(short)7, 1], [ cast(short)8, 12], [ cast(short)23, 192], [ cast(short)24, 1664], [ cast(short)42, 16], [ cast(short)43, 17], [ cast(short)52, 14], - [ cast(short)53, 15]], - /* 7 bits */ - [[ cast(short)3, 22], [ cast(short)4, 23], [ cast(short)8, 20], [ cast(short)12, 19], [ cast(short)19, 26], [ cast(short)23, 21], [ cast(short)24, 28], [ cast(short)36, 27], - [ cast(short)39, 18], [ cast(short)40, 24], [ cast(short)43, 25], [ cast(short)55, 256]], - /* 8 bits */ - [[ cast(short)2, 29], [ cast(short)3, 30], [ cast(short)4, 45], [ cast(short)5, 46], [ cast(short)10, 47], [ cast(short)11, 48], [ cast(short)18, 33], [ cast(short)19, 34], - [ cast(short)20, 35], [ cast(short)21, 36], [ cast(short)22, 37], [ cast(short)23, 38], [ cast(short)26, 31], [ cast(short)27, 32], [ cast(short)36, 53], [ cast(short)37, 54], - [ cast(short)40, 39], [ cast(short)41, 40], [ cast(short)42, 41], [ cast(short)43, 42], [ cast(short)44, 43], [ cast(short)45, 44], [ cast(short)50, 61], [ cast(short)51, 62], - [ cast(short)52, 63], [ cast(short)53, 0], [ cast(short)54, 320], [ cast(short)55, 384], [ cast(short)74, 59], [ cast(short)75, 60], [ cast(short)82, 49], [ cast(short)83, 50], - [ cast(short)84, 51], [ cast(short)85, 52], [ cast(short)88, 55], [ cast(short)89, 56], [ cast(short)90, 57], [ cast(short)91, 58], [ cast(short)100, 448], - [ cast(short)101, 512], [ cast(short)103, 640], [ cast(short)104, 576]], - /* 9 bits */ - [[ cast(short)152, 1472], [ cast(short)153, 1536], [ cast(short)154, 1600], [ cast(short)155, 1728], [ cast(short)204, 704], [ cast(short)205, 768], - [ cast(short)210, 832], [ cast(short)211, 896], [ cast(short)212, 960], [ cast(short)213, 1024], [ cast(short)214, 1088], [ cast(short)215, 1152], - [ cast(short)216, 1216], [ cast(short)217, 1280], [ cast(short)218, 1344], [ cast(short)219, 1408]], - /* 10 bits */ - [], - /* 11 bits */ - [[ cast(short)8, 1792], [ cast(short)12, 1856], [ cast(short)13, 1920]], - /* 12 bits */ - [/* EOL */[ cast(short)1, -1], [ cast(short)18, 1984], [ cast(short)19, 2048], [ cast(short)20, 2112], [ cast(short)21, 2176], [ cast(short)22, 2240], [ cast(short)23, 2304], - [ cast(short)28, 2368], [ cast(short)29, 2432], [ cast(short)30, 2496], [ cast(short)31, 2560]] - ]; + static final short[][][] WHITE_CODE = [ + /* 4 bits */ + [[ cast(short)7, 2], [ cast(short)8, 3], [ cast(short)11, 4], [ cast(short)12, 5], [ cast(short)14, 6], [ cast(short)15, 7]], + /* 5 bits */ + [[ cast(short)7, 10], [ cast(short)8, 11], [ cast(short)18, 128], [ cast(short)19, 8], [ cast(short)20, 9], [ cast(short)27, 64]], + /* 6 bits */ + [[ cast(short)3, 13], [ cast(short)7, 1], [ cast(short)8, 12], [ cast(short)23, 192], [ cast(short)24, 1664], [ cast(short)42, 16], [ cast(short)43, 17], [ cast(short)52, 14], + [ cast(short)53, 15]], + /* 7 bits */ + [[ cast(short)3, 22], [ cast(short)4, 23], [ cast(short)8, 20], [ cast(short)12, 19], [ cast(short)19, 26], [ cast(short)23, 21], [ cast(short)24, 28], [ cast(short)36, 27], + [ cast(short)39, 18], [ cast(short)40, 24], [ cast(short)43, 25], [ cast(short)55, 256]], + /* 8 bits */ + [[ cast(short)2, 29], [ cast(short)3, 30], [ cast(short)4, 45], [ cast(short)5, 46], [ cast(short)10, 47], [ cast(short)11, 48], [ cast(short)18, 33], [ cast(short)19, 34], + [ cast(short)20, 35], [ cast(short)21, 36], [ cast(short)22, 37], [ cast(short)23, 38], [ cast(short)26, 31], [ cast(short)27, 32], [ cast(short)36, 53], [ cast(short)37, 54], + [ cast(short)40, 39], [ cast(short)41, 40], [ cast(short)42, 41], [ cast(short)43, 42], [ cast(short)44, 43], [ cast(short)45, 44], [ cast(short)50, 61], [ cast(short)51, 62], + [ cast(short)52, 63], [ cast(short)53, 0], [ cast(short)54, 320], [ cast(short)55, 384], [ cast(short)74, 59], [ cast(short)75, 60], [ cast(short)82, 49], [ cast(short)83, 50], + [ cast(short)84, 51], [ cast(short)85, 52], [ cast(short)88, 55], [ cast(short)89, 56], [ cast(short)90, 57], [ cast(short)91, 58], [ cast(short)100, 448], + [ cast(short)101, 512], [ cast(short)103, 640], [ cast(short)104, 576]], + /* 9 bits */ + [[ cast(short)152, 1472], [ cast(short)153, 1536], [ cast(short)154, 1600], [ cast(short)155, 1728], [ cast(short)204, 704], [ cast(short)205, 768], + [ cast(short)210, 832], [ cast(short)211, 896], [ cast(short)212, 960], [ cast(short)213, 1024], [ cast(short)214, 1088], [ cast(short)215, 1152], + [ cast(short)216, 1216], [ cast(short)217, 1280], [ cast(short)218, 1344], [ cast(short)219, 1408]], + /* 10 bits */ + [], + /* 11 bits */ + [[ cast(short)8, 1792], [ cast(short)12, 1856], [ cast(short)13, 1920]], + /* 12 bits */ + [/* EOL */[ cast(short)1, -1], [ cast(short)18, 1984], [ cast(short)19, 2048], [ cast(short)20, 2112], [ cast(short)21, 2176], [ cast(short)22, 2240], [ cast(short)23, 2304], + [ cast(short)28, 2368], [ cast(short)29, 2432], [ cast(short)30, 2496], [ cast(short)31, 2560]] + ]; - static final int BLACK_MIN_BITS = 2; - static final int WHITE_MIN_BITS = 4; + static final int BLACK_MIN_BITS = 2; + static final int WHITE_MIN_BITS = 4; - bool isWhite; - int whiteValue = 0; - int blackValue = 1; - byte[] src; - byte[] dest; - int byteOffsetSrc = 0; - int bitOffsetSrc = 0; - int byteOffsetDest = 0; - int bitOffsetDest = 0; - int code = 0; - int nbrBits = 0; - /* nbr of bytes per row */ - int rowSize; + bool isWhite; + int whiteValue = 0; + int blackValue = 1; + byte[] src; + byte[] dest; + int byteOffsetSrc = 0; + int bitOffsetSrc = 0; + int byteOffsetDest = 0; + int bitOffsetDest = 0; + int code = 0; + int nbrBits = 0; + /* nbr of bytes per row */ + int rowSize; public int decode(byte[] src, byte[] dest, int offsetDest, int rowSize, int nRows) { - this.src = src; - this.dest = dest; - this.rowSize = rowSize; - byteOffsetSrc = 0; - bitOffsetSrc = 0; - byteOffsetDest = offsetDest; - bitOffsetDest = 0; - int cnt = 0; - while (cnt < nRows && decodeRow()) { - cnt++; - /* byte aligned */ - if (bitOffsetDest > 0) { - byteOffsetDest++; - bitOffsetDest = 0; - } - } - return byteOffsetDest - offsetDest; + this.src = src; + this.dest = dest; + this.rowSize = rowSize; + byteOffsetSrc = 0; + bitOffsetSrc = 0; + byteOffsetDest = offsetDest; + bitOffsetDest = 0; + int cnt = 0; + while (cnt < nRows && decodeRow()) { + cnt++; + /* byte aligned */ + if (bitOffsetDest > 0) { + byteOffsetDest++; + bitOffsetDest = 0; + } + } + return byteOffsetDest - offsetDest; } bool decodeRow() { - isWhite = true; - int n = 0; - while (n < rowSize) { - int runLength = decodeRunLength(); - if (runLength < 0) return false; - n += runLength; - setNextBits(isWhite ? whiteValue : blackValue, runLength); - isWhite = !isWhite; - } - return true; + isWhite = true; + int n = 0; + while (n < rowSize) { + int runLength = decodeRunLength(); + if (runLength < 0) return false; + n += runLength; + setNextBits(isWhite ? whiteValue : blackValue, runLength); + isWhite = !isWhite; + } + return true; } int decodeRunLength() { - int runLength = 0; - int partialRun = 0; - short[][][] huffmanCode = isWhite ? WHITE_CODE : BLACK_CODE; - while (true) { - bool found = false; - nbrBits = isWhite ? WHITE_MIN_BITS : BLACK_MIN_BITS; - code = getNextBits(nbrBits); - for (int i = 0; i < huffmanCode.length; i++) { - for (int j = 0; j < huffmanCode[i].length; j++) { - if (huffmanCode[i][j][0] == code) { - found = true; - partialRun = huffmanCode[i][j][1]; - if (partialRun == -1) { - /* Stop when reaching final EOL on last byte */ - if (byteOffsetSrc == src.length - 1) return -1; - /* Group 3 starts each row with an EOL - ignore it */ - } else { - runLength += partialRun; - if (partialRun < 64) return runLength; - } - break; - } - } - if (found) break; - code = code << 1 | getNextBit(); - } - if (!found) SWT.error(SWT.ERROR_INVALID_IMAGE); - } + int runLength = 0; + int partialRun = 0; + short[][][] huffmanCode = isWhite ? WHITE_CODE : BLACK_CODE; + while (true) { + bool found = false; + nbrBits = isWhite ? WHITE_MIN_BITS : BLACK_MIN_BITS; + code = getNextBits(nbrBits); + for (int i = 0; i < huffmanCode.length; i++) { + for (int j = 0; j < huffmanCode[i].length; j++) { + if (huffmanCode[i][j][0] == code) { + found = true; + partialRun = huffmanCode[i][j][1]; + if (partialRun == -1) { + /* Stop when reaching final EOL on last byte */ + if (byteOffsetSrc == src.length - 1) return -1; + /* Group 3 starts each row with an EOL - ignore it */ + } else { + runLength += partialRun; + if (partialRun < 64) return runLength; + } + break; + } + } + if (found) break; + code = code << 1 | getNextBit(); + } + if (!found) SWT.error(SWT.ERROR_INVALID_IMAGE); + } } int getNextBit() { - int value = (src[byteOffsetSrc] >>> (7 - bitOffsetSrc)) & 0x1; - bitOffsetSrc++; - if (bitOffsetSrc > 7) { - byteOffsetSrc++; - bitOffsetSrc = 0; - } - return value; + int value = (src[byteOffsetSrc] >>> (7 - bitOffsetSrc)) & 0x1; + bitOffsetSrc++; + if (bitOffsetSrc > 7) { + byteOffsetSrc++; + bitOffsetSrc = 0; + } + return value; } int getNextBits(int cnt) { - int value = 0; - for (int i = 0; i < cnt; i++) { - value = value << 1 | getNextBit(); - } - return value; + int value = 0; + for (int i = 0; i < cnt; i++) { + value = value << 1 | getNextBit(); + } + return value; } void setNextBits(int value, int cnt) { - int n = cnt; - while (bitOffsetDest > 0 && bitOffsetDest <= 7 && n > 0) { - dest[byteOffsetDest] = value == 1 ? - cast(byte)(dest[byteOffsetDest] | (1 << (7 - bitOffsetDest))) : - cast(byte)(dest[byteOffsetDest] & ~(1 << (7 - bitOffsetDest))); - n--; - bitOffsetDest++; - } - if (bitOffsetDest == 8) { - byteOffsetDest++; - bitOffsetDest = 0; - } - while (n >= 8) { - dest[byteOffsetDest++] = cast(byte) (value == 1 ? 0xFF : 0); - n -= 8; - } - while (n > 0) { - dest[byteOffsetDest] = value == 1 ? - cast(byte)(dest[byteOffsetDest] | (1 << (7 - bitOffsetDest))) : - cast(byte)(dest[byteOffsetDest] & ~(1 << (7 - bitOffsetDest))); - n--; - bitOffsetDest++; - } + int n = cnt; + while (bitOffsetDest > 0 && bitOffsetDest <= 7 && n > 0) { + dest[byteOffsetDest] = value == 1 ? + cast(byte)(dest[byteOffsetDest] | (1 << (7 - bitOffsetDest))) : + cast(byte)(dest[byteOffsetDest] & ~(1 << (7 - bitOffsetDest))); + n--; + bitOffsetDest++; + } + if (bitOffsetDest == 8) { + byteOffsetDest++; + bitOffsetDest = 0; + } + while (n >= 8) { + dest[byteOffsetDest++] = cast(byte) (value == 1 ? 0xFF : 0); + n -= 8; + } + while (n > 0) { + dest[byteOffsetDest] = value == 1 ? + cast(byte)(dest[byteOffsetDest] | (1 << (7 - bitOffsetDest))) : + cast(byte)(dest[byteOffsetDest] & ~(1 << (7 - bitOffsetDest))); + n--; + bitOffsetDest++; + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/TIFFRandomFileAccess.d --- a/dwt/internal/image/TIFFRandomFileAccess.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/TIFFRandomFileAccess.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2003 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 @@ -17,83 +17,83 @@ final class TIFFRandomFileAccess { - LEDataInputStream inputStream; - int start, current, next; - byte[][] buffers; + LEDataInputStream inputStream; + int start, current, next; + byte[][] buffers; - static final int CHUNK_SIZE = 8192; - static final int LIST_SIZE = 128; + static final int CHUNK_SIZE = 8192; + static final int LIST_SIZE = 128; public this(LEDataInputStream stream) { - inputStream = stream; - start = current = next = inputStream.getPosition(); - buffers = new byte[][](LIST_SIZE); + inputStream = stream; + start = current = next = inputStream.getPosition(); + buffers = new byte[][](LIST_SIZE); } void seek(int pos) { - if (pos == current) return; - if (pos < start) throw new IOException( "pos < start" ); - current = pos; - if (current > next) { - int n = current - next; - /* store required bytes */ - int index = next / CHUNK_SIZE; - int offset = next % CHUNK_SIZE; - while (n > 0) { - if (index >= buffers.length) { - byte[][] oldBuffers = buffers; - buffers = new byte[][]( Math.max(index + 1, oldBuffers.length + LIST_SIZE) ); + if (pos == current) return; + if (pos < start) throw new IOException( "pos < start" ); + current = pos; + if (current > next) { + int n = current - next; + /* store required bytes */ + int index = next / CHUNK_SIZE; + int offset = next % CHUNK_SIZE; + while (n > 0) { + if (index >= buffers.length) { + byte[][] oldBuffers = buffers; + buffers = new byte[][]( Math.max(index + 1, oldBuffers.length + LIST_SIZE) ); System.arraycopy(oldBuffers, 0, buffers, 0, oldBuffers.length); - } - if (buffers[index] == null) buffers[index] = new byte[CHUNK_SIZE]; - int cnt = inputStream.read(buffers[index], offset, Math.min(n, CHUNK_SIZE - offset)); - n -= cnt; - next += cnt; - index++; - offset = 0; - } - } + } + if (buffers[index] == null) buffers[index] = new byte[CHUNK_SIZE]; + int cnt = inputStream.read(buffers[index], offset, Math.min(n, CHUNK_SIZE - offset)); + n -= cnt; + next += cnt; + index++; + offset = 0; + } + } } void read(byte b[]) { - int size = b.length; - int nCached = Math.min(size, next - current); - int nMissing = size - next + current; - int destNext = 0; - if (nCached > 0) { - /* Get cached bytes */ - int index = current / CHUNK_SIZE; - int offset = current % CHUNK_SIZE; - while (nCached > 0) { - int cnt = Math.min(nCached, CHUNK_SIZE - offset); + int size = b.length; + int nCached = Math.min(size, next - current); + int nMissing = size - next + current; + int destNext = 0; + if (nCached > 0) { + /* Get cached bytes */ + int index = current / CHUNK_SIZE; + int offset = current % CHUNK_SIZE; + while (nCached > 0) { + int cnt = Math.min(nCached, CHUNK_SIZE - offset); System.arraycopy(buffers[index], offset, b, destNext, cnt); - nCached -= cnt; - destNext += cnt; - index++; - offset = 0; - } - } - if (nMissing > 0) { - /* Read required bytes */ - int index = next / CHUNK_SIZE; - int offset = next % CHUNK_SIZE; - while (nMissing > 0) { - if (index >= buffers.length) { - byte[][] oldBuffers = buffers; - buffers = new byte[][](Math.max(index, oldBuffers.length + LIST_SIZE)); + nCached -= cnt; + destNext += cnt; + index++; + offset = 0; + } + } + if (nMissing > 0) { + /* Read required bytes */ + int index = next / CHUNK_SIZE; + int offset = next % CHUNK_SIZE; + while (nMissing > 0) { + if (index >= buffers.length) { + byte[][] oldBuffers = buffers; + buffers = new byte[][](Math.max(index, oldBuffers.length + LIST_SIZE)); System.arraycopy(oldBuffers, 0, buffers, 0, oldBuffers.length); - } - if (buffers[index] == null) buffers[index] = new byte[CHUNK_SIZE]; - int cnt = inputStream.read(buffers[index], offset, Math.min(nMissing, CHUNK_SIZE - offset)); + } + if (buffers[index] == null) buffers[index] = new byte[CHUNK_SIZE]; + int cnt = inputStream.read(buffers[index], offset, Math.min(nMissing, CHUNK_SIZE - offset)); System.arraycopy(buffers[index], offset, b, destNext, cnt); - nMissing -= cnt; - next += cnt; - destNext += cnt; - index++; - offset = 0; - } - } - current += size; + nMissing -= cnt; + next += cnt; + destNext += cnt; + index++; + offset = 0; + } + } + current += size; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/WinBMPFileFormat.d --- a/dwt/internal/image/WinBMPFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/WinBMPFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -21,9 +21,9 @@ final class WinBMPFileFormat : FileFormat { - static final int BMPFileHeaderSize = 14; - static final int BMPHeaderFixedSize = 40; - int importantColors; + static final int BMPFileHeaderSize = 14; + static final int BMPHeaderFixedSize = 40; + int importantColors; Point pelsPerMeter; public this(){ @@ -37,474 +37,474 @@ * Answer the size of the compressed data. */ int compress(int comp, byte[] src, int srcOffset, int numBytes, byte[] dest, bool last) { - if (comp == 1) { // BMP_RLE8_COMPRESSION - return compressRLE8Data(src, srcOffset, numBytes, dest, last); - } - if (comp == 2) { // BMP_RLE4_COMPRESSION - return compressRLE4Data(src, srcOffset, numBytes, dest, last); - } - SWT.error(SWT.ERROR_INVALID_IMAGE); - return 0; + if (comp == 1) { // BMP_RLE8_COMPRESSION + return compressRLE8Data(src, srcOffset, numBytes, dest, last); + } + if (comp == 2) { // BMP_RLE4_COMPRESSION + return compressRLE4Data(src, srcOffset, numBytes, dest, last); + } + SWT.error(SWT.ERROR_INVALID_IMAGE); + return 0; } int compressRLE4Data(byte[] src, int srcOffset, int numBytes, byte[] dest, bool last) { - int sp = srcOffset, end = srcOffset + numBytes, dp = 0; - int size = 0, left, i, n; - byte theByte; - while (sp < end) { - /* find two consecutive bytes that are the same in the next 128 */ - left = end - sp - 1; - if (left > 127) - left = 127; - for (n = 0; n < left; n++) { - if (src[sp + n] == src[sp + n + 1]) - break; - } - /* if there is only one more byte in the scan line, include it */ - if (n < 127 && n == left) - n++; - /* store the intervening data */ - switch (n) { - case 0: - break; - case 1: /* handled separately because 0,2 is a command */ - dest[dp] = 2; dp++; /* 1 byte == 2 pixels */ - dest[dp] = src[sp]; - dp++; sp++; - size += 2; - break; - default: - dest[dp] = 0; dp++; - dest[dp] = cast(byte)(n + n); dp++; /* n bytes = n*2 pixels */ - for (i = n; i > 0; i--) { - dest[dp] = src[sp]; - dp++; sp++; - } - size += 2 + n; - if ((n & 1) != 0) { /* pad to word */ - dest[dp] = 0; - dp++; - size++; - } - break; - } - /* find the length of the next run (up to 127) and store it */ - left = end - sp; - if (left > 0) { - if (left > 127) - left = 127; - theByte = src[sp]; - for (n = 1; n < left; n++) { - if (src[sp + n] != theByte) - break; - } - dest[dp] = cast(byte)(n + n); dp++; /* n bytes = n*2 pixels */ - dest[dp] = theByte; dp++; - sp += n; - size += 2; - } - } + int sp = srcOffset, end = srcOffset + numBytes, dp = 0; + int size = 0, left, i, n; + byte theByte; + while (sp < end) { + /* find two consecutive bytes that are the same in the next 128 */ + left = end - sp - 1; + if (left > 127) + left = 127; + for (n = 0; n < left; n++) { + if (src[sp + n] == src[sp + n + 1]) + break; + } + /* if there is only one more byte in the scan line, include it */ + if (n < 127 && n == left) + n++; + /* store the intervening data */ + switch (n) { + case 0: + break; + case 1: /* handled separately because 0,2 is a command */ + dest[dp] = 2; dp++; /* 1 byte == 2 pixels */ + dest[dp] = src[sp]; + dp++; sp++; + size += 2; + break; + default: + dest[dp] = 0; dp++; + dest[dp] = cast(byte)(n + n); dp++; /* n bytes = n*2 pixels */ + for (i = n; i > 0; i--) { + dest[dp] = src[sp]; + dp++; sp++; + } + size += 2 + n; + if ((n & 1) != 0) { /* pad to word */ + dest[dp] = 0; + dp++; + size++; + } + break; + } + /* find the length of the next run (up to 127) and store it */ + left = end - sp; + if (left > 0) { + if (left > 127) + left = 127; + theByte = src[sp]; + for (n = 1; n < left; n++) { + if (src[sp + n] != theByte) + break; + } + dest[dp] = cast(byte)(n + n); dp++; /* n bytes = n*2 pixels */ + dest[dp] = theByte; dp++; + sp += n; + size += 2; + } + } - /* store the end of line or end of bitmap codes */ - dest[dp] = 0; dp++; - if (last) { - dest[dp] = 1; dp++; - } else { - dest[dp] = 0; dp++; - } - size += 2; + /* store the end of line or end of bitmap codes */ + dest[dp] = 0; dp++; + if (last) { + dest[dp] = 1; dp++; + } else { + dest[dp] = 0; dp++; + } + size += 2; - return size; + return size; } int compressRLE8Data(byte[] src, int srcOffset, int numBytes, byte[] dest, bool last) { - int sp = srcOffset, end = srcOffset + numBytes, dp = 0; - int size = 0, left, i, n; - byte theByte; - while (sp < end) { - /* find two consecutive bytes that are the same in the next 256 */ - left = end - sp - 1; - if (left > 254) - left = 254; - for (n = 0; n < left; n++) { - if (src[sp + n] == src[sp + n + 1]) - break; - } - /* if there is only one more byte in the scan line, include it */ - if (n == left) - n++; - /* store the intervening data */ - switch (n) { - case 0: - break; - case 2: /* handled separately because 0,2 is a command */ - dest[dp] = 1; dp++; - dest[dp] = src[sp]; - dp++; sp++; - size += 2; - /* don't break, fall through */ - case 1: /* handled separately because 0,1 is a command */ - dest[dp] = 1; dp++; - dest[dp] = src[sp]; - dp++; sp++; - size += 2; - break; - default: - dest[dp] = 0; dp++; - dest[dp] = cast(byte)n; dp++; - for (i = n; i > 0; i--) { - dest[dp] = src[sp]; - dp++; sp++; - } - size += 2 + n; - if ((n & 1) != 0) { /* pad to word */ - dest[dp] = 0; - dp++; - size++; - } - break; - } - /* find the length of the next run (up to 255) and store it */ - left = end - sp; - if (left > 0) { - if (left > 255) - left = 255; - theByte = src[sp]; - for (n = 1; n < left; n++) { - if (src[sp + n] != theByte) - break; - } - dest[dp] = cast(byte)n; dp++; - dest[dp] = theByte; dp++; - sp += n; - size += 2; - } - } + int sp = srcOffset, end = srcOffset + numBytes, dp = 0; + int size = 0, left, i, n; + byte theByte; + while (sp < end) { + /* find two consecutive bytes that are the same in the next 256 */ + left = end - sp - 1; + if (left > 254) + left = 254; + for (n = 0; n < left; n++) { + if (src[sp + n] == src[sp + n + 1]) + break; + } + /* if there is only one more byte in the scan line, include it */ + if (n == left) + n++; + /* store the intervening data */ + switch (n) { + case 0: + break; + case 2: /* handled separately because 0,2 is a command */ + dest[dp] = 1; dp++; + dest[dp] = src[sp]; + dp++; sp++; + size += 2; + /* don't break, fall through */ + case 1: /* handled separately because 0,1 is a command */ + dest[dp] = 1; dp++; + dest[dp] = src[sp]; + dp++; sp++; + size += 2; + break; + default: + dest[dp] = 0; dp++; + dest[dp] = cast(byte)n; dp++; + for (i = n; i > 0; i--) { + dest[dp] = src[sp]; + dp++; sp++; + } + size += 2 + n; + if ((n & 1) != 0) { /* pad to word */ + dest[dp] = 0; + dp++; + size++; + } + break; + } + /* find the length of the next run (up to 255) and store it */ + left = end - sp; + if (left > 0) { + if (left > 255) + left = 255; + theByte = src[sp]; + for (n = 1; n < left; n++) { + if (src[sp + n] != theByte) + break; + } + dest[dp] = cast(byte)n; dp++; + dest[dp] = theByte; dp++; + sp += n; + size += 2; + } + } - /* store the end of line or end of bitmap codes */ - dest[dp] = 0; dp++; - if (last) { - dest[dp] = 1; dp++; - } else { - dest[dp] = 0; dp++; - } - size += 2; + /* store the end of line or end of bitmap codes */ + dest[dp] = 0; dp++; + if (last) { + dest[dp] = 1; dp++; + } else { + dest[dp] = 0; dp++; + } + size += 2; - return size; + return size; } void decompressData(byte[] src, byte[] dest, int stride, int cmp) { - if (cmp == 1) { // BMP_RLE8_COMPRESSION - if (decompressRLE8Data(src, src.length, stride, dest, dest.length) <= 0) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return; - } - if (cmp == 2) { // BMP_RLE4_COMPRESSION - if (decompressRLE4Data(src, src.length, stride, dest, dest.length) <= 0) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return; - } - SWT.error(SWT.ERROR_INVALID_IMAGE); + if (cmp == 1) { // BMP_RLE8_COMPRESSION + if (decompressRLE8Data(src, src.length, stride, dest, dest.length) <= 0) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return; + } + if (cmp == 2) { // BMP_RLE4_COMPRESSION + if (decompressRLE4Data(src, src.length, stride, dest, dest.length) <= 0) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return; + } + SWT.error(SWT.ERROR_INVALID_IMAGE); } int decompressRLE4Data(byte[] src, int numBytes, int stride, byte[] dest, int destSize) { - int sp = 0; - int se = numBytes; - int dp = 0; - int de = destSize; - int x = 0, y = 0; - while (sp < se) { - int len = src[sp] & 0xFF; - sp++; - if (len == 0) { - len = src[sp] & 0xFF; - sp++; - switch (len) { - case 0: /* end of line */ - y++; - x = 0; - dp = y * stride; - if (dp > de) - return -1; - break; - case 1: /* end of bitmap */ - return 1; - case 2: /* delta */ - x += src[sp] & 0xFF; - sp++; - y += src[sp] & 0xFF; - sp++; - dp = y * stride + x / 2; - if (dp > de) - return -1; - break; - default: /* absolute mode run */ - if ((len & 1) != 0) /* odd run lengths not currently supported */ - return -1; - x += len; - len = len / 2; - if (len > (se - sp)) - return -1; - if (len > (de - dp)) - return -1; - for (int i = 0; i < len; i++) { - dest[dp] = src[sp]; - dp++; - sp++; - } - if ((sp & 1) != 0) - sp++; /* word align sp? */ - break; - } - } else { - if ((len & 1) != 0) - return -1; - x += len; - len = len / 2; - byte theByte = src[sp]; - sp++; - if (len > (de - dp)) - return -1; - for (int i = 0; i < len; i++) { - dest[dp] = theByte; - dp++; - } - } - } - return 1; + int sp = 0; + int se = numBytes; + int dp = 0; + int de = destSize; + int x = 0, y = 0; + while (sp < se) { + int len = src[sp] & 0xFF; + sp++; + if (len == 0) { + len = src[sp] & 0xFF; + sp++; + switch (len) { + case 0: /* end of line */ + y++; + x = 0; + dp = y * stride; + if (dp > de) + return -1; + break; + case 1: /* end of bitmap */ + return 1; + case 2: /* delta */ + x += src[sp] & 0xFF; + sp++; + y += src[sp] & 0xFF; + sp++; + dp = y * stride + x / 2; + if (dp > de) + return -1; + break; + default: /* absolute mode run */ + if ((len & 1) != 0) /* odd run lengths not currently supported */ + return -1; + x += len; + len = len / 2; + if (len > (se - sp)) + return -1; + if (len > (de - dp)) + return -1; + for (int i = 0; i < len; i++) { + dest[dp] = src[sp]; + dp++; + sp++; + } + if ((sp & 1) != 0) + sp++; /* word align sp? */ + break; + } + } else { + if ((len & 1) != 0) + return -1; + x += len; + len = len / 2; + byte theByte = src[sp]; + sp++; + if (len > (de - dp)) + return -1; + for (int i = 0; i < len; i++) { + dest[dp] = theByte; + dp++; + } + } + } + return 1; } int decompressRLE8Data(byte[] src, int numBytes, int stride, byte[] dest, int destSize) { - int sp = 0; - int se = numBytes; - int dp = 0; - int de = destSize; - int x = 0, y = 0; - while (sp < se) { - int len = src[sp] & 0xFF; - sp++; - if (len == 0) { - len = src[sp] & 0xFF; - sp++; - switch (len) { - case 0: /* end of line */ - y++; - x = 0; - dp = y * stride; - if (dp > de) - return -1; - break; - case 1: /* end of bitmap */ - return 1; - case 2: /* delta */ - x += src[sp] & 0xFF; - sp++; - y += src[sp] & 0xFF; - sp++; - dp = y * stride + x; - if (dp > de) - return -1; - break; - default: /* absolute mode run */ - if (len > (se - sp)) - return -1; - if (len > (de - dp)) - return -1; - for (int i = 0; i < len; i++) { - dest[dp] = src[sp]; - dp++; - sp++; - } - if ((sp & 1) != 0) - sp++; /* word align sp? */ - x += len; - break; - } - } else { - byte theByte = src[sp]; - sp++; - if (len > (de - dp)) - return -1; - for (int i = 0; i < len; i++) { - dest[dp] = theByte; - dp++; - } - x += len; - } - } - return 1; + int sp = 0; + int se = numBytes; + int dp = 0; + int de = destSize; + int x = 0, y = 0; + while (sp < se) { + int len = src[sp] & 0xFF; + sp++; + if (len == 0) { + len = src[sp] & 0xFF; + sp++; + switch (len) { + case 0: /* end of line */ + y++; + x = 0; + dp = y * stride; + if (dp > de) + return -1; + break; + case 1: /* end of bitmap */ + return 1; + case 2: /* delta */ + x += src[sp] & 0xFF; + sp++; + y += src[sp] & 0xFF; + sp++; + dp = y * stride + x; + if (dp > de) + return -1; + break; + default: /* absolute mode run */ + if (len > (se - sp)) + return -1; + if (len > (de - dp)) + return -1; + for (int i = 0; i < len; i++) { + dest[dp] = src[sp]; + dp++; + sp++; + } + if ((sp & 1) != 0) + sp++; /* word align sp? */ + x += len; + break; + } + } else { + byte theByte = src[sp]; + sp++; + if (len > (de - dp)) + return -1; + for (int i = 0; i < len; i++) { + dest[dp] = theByte; + dp++; + } + x += len; + } + } + return 1; } bool isFileFormat(LEDataInputStream stream) { - try { - byte[] header = new byte[18]; - stream.read(header); - stream.unread(header); - int infoHeaderSize = (header[14] & 0xFF) | ((header[15] & 0xFF) << 8) | ((header[16] & 0xFF) << 16) | ((header[17] & 0xFF) << 24); - return header[0] == 0x42 && header[1] == 0x4D && infoHeaderSize >= BMPHeaderFixedSize; - } catch (TracedException e) { - return false; - } + try { + byte[] header = new byte[18]; + stream.read(header); + stream.unread(header); + int infoHeaderSize = (header[14] & 0xFF) | ((header[15] & 0xFF) << 8) | ((header[16] & 0xFF) << 16) | ((header[17] & 0xFF) << 24); + return header[0] == 0x42 && header[1] == 0x4D && infoHeaderSize >= BMPHeaderFixedSize; + } catch (TracedException e) { + return false; + } } byte[] loadData(byte[] infoHeader) { - int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); - int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); - int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); - int stride = (width * bitCount + 7) / 8; - stride = (stride + 3) / 4 * 4; // Round up to 4 byte multiple - byte[] data = loadData(infoHeader, stride); - flipScanLines(data, stride, height); - return data; + int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); + int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); + int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); + int stride = (width * bitCount + 7) / 8; + stride = (stride + 3) / 4 * 4; // Round up to 4 byte multiple + byte[] data = loadData(infoHeader, stride); + flipScanLines(data, stride, height); + return data; } byte[] loadData(byte[] infoHeader, int stride) { - int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); - if (height < 0) height = -height; - int dataSize = height * stride; - byte[] data = new byte[dataSize]; - int cmp = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24); - if (cmp == 0 || cmp == 3) { // BMP_NO_COMPRESSION - try { - if (inputStream.read(data) != dataSize) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } else { - int compressedSize = (infoHeader[20] & 0xFF) | ((infoHeader[21] & 0xFF) << 8) | ((infoHeader[22] & 0xFF) << 16) | ((infoHeader[23] & 0xFF) << 24); - byte[] compressed = new byte[compressedSize]; - try { - if (inputStream.read(compressed) != compressedSize) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - decompressData(compressed, data, stride, cmp); - } - return data; + int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); + if (height < 0) height = -height; + int dataSize = height * stride; + byte[] data = new byte[dataSize]; + int cmp = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24); + if (cmp == 0 || cmp == 3) { // BMP_NO_COMPRESSION + try { + if (inputStream.read(data) != dataSize) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } else { + int compressedSize = (infoHeader[20] & 0xFF) | ((infoHeader[21] & 0xFF) << 8) | ((infoHeader[22] & 0xFF) << 16) | ((infoHeader[23] & 0xFF) << 24); + byte[] compressed = new byte[compressedSize]; + try { + if (inputStream.read(compressed) != compressedSize) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + decompressData(compressed, data, stride, cmp); + } + return data; } int[] loadFileHeader() { - int[] header = new int[5]; - try { - header[0] = inputStream.readShort(); - header[1] = inputStream.readInt(); - header[2] = inputStream.readShort(); - header[3] = inputStream.readShort(); - header[4] = inputStream.readInt(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if (header[0] != 0x4D42) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return header; + int[] header = new int[5]; + try { + header[0] = inputStream.readShort(); + header[1] = inputStream.readInt(); + header[2] = inputStream.readShort(); + header[3] = inputStream.readShort(); + header[4] = inputStream.readInt(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if (header[0] != 0x4D42) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return header; } ImageData[] loadFromByteStream() { - int[] fileHeader = loadFileHeader(); - byte[] infoHeader = new byte[BMPHeaderFixedSize]; - try { - inputStream.read(infoHeader); - } catch (TracedException e) { - SWT.error(SWT.ERROR_IO, e); - } - int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); - int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); - if (height < 0) height = -height; - int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); - this.compression = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24); - PaletteData palette = loadPalette(infoHeader); - if (inputStream.getPosition() < fileHeader[4]) { - // Seek to the specified offset - try { - inputStream.skip(fileHeader[4] - inputStream.getPosition()); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - byte[] data = loadData(infoHeader); - this.importantColors = (infoHeader[36] & 0xFF) | ((infoHeader[37] & 0xFF) << 8) | ((infoHeader[38] & 0xFF) << 16) | ((infoHeader[39] & 0xFF) << 24); - int xPelsPerMeter = (infoHeader[24] & 0xFF) | ((infoHeader[25] & 0xFF) << 8) | ((infoHeader[26] & 0xFF) << 16) | ((infoHeader[27] & 0xFF) << 24); - int yPelsPerMeter = (infoHeader[28] & 0xFF) | ((infoHeader[29] & 0xFF) << 8) | ((infoHeader[30] & 0xFF) << 16) | ((infoHeader[31] & 0xFF) << 24); - this.pelsPerMeter = new Point(xPelsPerMeter, yPelsPerMeter); - int type = (this.compression == 1 /*BMP_RLE8_COMPRESSION*/) || (this.compression == 2 /*BMP_RLE4_COMPRESSION*/) ? SWT.IMAGE_BMP_RLE : SWT.IMAGE_BMP; - return [ - ImageData.internal_new( - width, - height, - bitCount, - palette, - 4, - data, - 0, - null, - null, - -1, - -1, - type, - 0, - 0, - 0, - 0) - ]; + int[] fileHeader = loadFileHeader(); + byte[] infoHeader = new byte[BMPHeaderFixedSize]; + try { + inputStream.read(infoHeader); + } catch (TracedException e) { + SWT.error(SWT.ERROR_IO, e); + } + int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); + int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); + if (height < 0) height = -height; + int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); + this.compression = (infoHeader[16] & 0xFF) | ((infoHeader[17] & 0xFF) << 8) | ((infoHeader[18] & 0xFF) << 16) | ((infoHeader[19] & 0xFF) << 24); + PaletteData palette = loadPalette(infoHeader); + if (inputStream.getPosition() < fileHeader[4]) { + // Seek to the specified offset + try { + inputStream.skip(fileHeader[4] - inputStream.getPosition()); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + byte[] data = loadData(infoHeader); + this.importantColors = (infoHeader[36] & 0xFF) | ((infoHeader[37] & 0xFF) << 8) | ((infoHeader[38] & 0xFF) << 16) | ((infoHeader[39] & 0xFF) << 24); + int xPelsPerMeter = (infoHeader[24] & 0xFF) | ((infoHeader[25] & 0xFF) << 8) | ((infoHeader[26] & 0xFF) << 16) | ((infoHeader[27] & 0xFF) << 24); + int yPelsPerMeter = (infoHeader[28] & 0xFF) | ((infoHeader[29] & 0xFF) << 8) | ((infoHeader[30] & 0xFF) << 16) | ((infoHeader[31] & 0xFF) << 24); + this.pelsPerMeter = new Point(xPelsPerMeter, yPelsPerMeter); + int type = (this.compression == 1 /*BMP_RLE8_COMPRESSION*/) || (this.compression == 2 /*BMP_RLE4_COMPRESSION*/) ? SWT.IMAGE_BMP_RLE : SWT.IMAGE_BMP; + return [ + ImageData.internal_new( + width, + height, + bitCount, + palette, + 4, + data, + 0, + null, + null, + -1, + -1, + type, + 0, + 0, + 0, + 0) + ]; } PaletteData loadPalette(byte[] infoHeader) { - int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); - if (depth <= 8) { - int numColors = (infoHeader[32] & 0xFF) | ((infoHeader[33] & 0xFF) << 8) | ((infoHeader[34] & 0xFF) << 16) | ((infoHeader[35] & 0xFF) << 24); - if (numColors == 0) { - numColors = 1 << depth; - } else { - if (numColors > 256) - numColors = 256; - } - byte[] buf = new byte[numColors * 4]; - try { - if (inputStream.read(buf) != buf.length) - SWT.error(SWT.ERROR_INVALID_IMAGE); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return paletteFromBytes(buf, numColors); - } - if (depth == 16) { - if (this.compression == 3) { - try { - return new PaletteData(inputStream.readInt(), inputStream.readInt(), inputStream.readInt()); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - return new PaletteData(0x7C00, 0x3E0, 0x1F); - } - if (depth == 24) return new PaletteData(0xFF, 0xFF00, 0xFF0000); - if (this.compression == 3) { - try { - return new PaletteData(inputStream.readInt(), inputStream.readInt(), inputStream.readInt()); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } - return new PaletteData(0xFF00, 0xFF0000, 0xFF000000); + int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); + if (depth <= 8) { + int numColors = (infoHeader[32] & 0xFF) | ((infoHeader[33] & 0xFF) << 8) | ((infoHeader[34] & 0xFF) << 16) | ((infoHeader[35] & 0xFF) << 24); + if (numColors == 0) { + numColors = 1 << depth; + } else { + if (numColors > 256) + numColors = 256; + } + byte[] buf = new byte[numColors * 4]; + try { + if (inputStream.read(buf) != buf.length) + SWT.error(SWT.ERROR_INVALID_IMAGE); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return paletteFromBytes(buf, numColors); + } + if (depth == 16) { + if (this.compression == 3) { + try { + return new PaletteData(inputStream.readInt(), inputStream.readInt(), inputStream.readInt()); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + return new PaletteData(0x7C00, 0x3E0, 0x1F); + } + if (depth == 24) return new PaletteData(0xFF, 0xFF00, 0xFF0000); + if (this.compression == 3) { + try { + return new PaletteData(inputStream.readInt(), inputStream.readInt(), inputStream.readInt()); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } + return new PaletteData(0xFF00, 0xFF0000, 0xFF000000); } PaletteData paletteFromBytes(byte[] bytes, int numColors) { - int bytesOffset = 0; - RGB[] colors = new RGB[numColors]; - for (int i = 0; i < numColors; i++) { - colors[i] = new RGB(bytes[bytesOffset + 2] & 0xFF, - bytes[bytesOffset + 1] & 0xFF, - bytes[bytesOffset] & 0xFF); - bytesOffset += 4; - } - return new PaletteData(colors); + int bytesOffset = 0; + RGB[] colors = new RGB[numColors]; + for (int i = 0; i < numColors; i++) { + colors[i] = new RGB(bytes[bytesOffset + 2] & 0xFF, + bytes[bytesOffset + 1] & 0xFF, + bytes[bytesOffset] & 0xFF); + bytesOffset += 4; + } + return new PaletteData(colors); } /** * Answer a byte array containing the BMP representation of * the given device independent palette. */ static byte[] paletteToBytes(PaletteData pal) { - int n = pal.colors == null ? 0 : (pal.colors.length < 256 ? pal.colors.length : 256); - byte[] bytes = new byte[n * 4]; - int offset = 0; - for (int i = 0; i < n; i++) { - RGB col = pal.colors[i]; - bytes[offset] = cast(byte)col.blue; - bytes[offset + 1] = cast(byte)col.green; - bytes[offset + 2] = cast(byte)col.red; - offset += 4; - } - return bytes; + int n = pal.colors == null ? 0 : (pal.colors.length < 256 ? pal.colors.length : 256); + byte[] bytes = new byte[n * 4]; + int offset = 0; + for (int i = 0; i < n; i++) { + RGB col = pal.colors[i]; + bytes[offset] = cast(byte)col.blue; + bytes[offset + 1] = cast(byte)col.green; + bytes[offset + 2] = cast(byte)col.red; + offset += 4; + } + return bytes; } /** * Unload the given image's data into the given byte stream @@ -512,37 +512,37 @@ * Answer the number of bytes written. */ int unloadData(ImageData image, OutputStream ostr, int comp) { - int totalSize = 0; - try { - if (comp == 0) - return unloadDataNoCompression(image, ostr); - int bpl = (image.width * image.depth + 7) / 8; - int bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes - int imageBpl = image.bytesPerLine; - // Compression can actually take twice as much space, in worst case - byte[] buf = new byte[bmpBpl * 2]; - int srcOffset = imageBpl * (image.height - 1); // Start at last line - byte[] data = image.data; - totalSize = 0; - byte[] buf2 = new byte[32768]; - int buf2Offset = 0; - for (int y = image.height - 1; y >= 0; y--) { - int lineSize = compress(comp, data, srcOffset, bpl, buf, y == 0); - if (buf2Offset + lineSize > buf2.length) { - ostr.write(buf2, 0, buf2Offset); - buf2Offset = 0; - } + int totalSize = 0; + try { + if (comp == 0) + return unloadDataNoCompression(image, ostr); + int bpl = (image.width * image.depth + 7) / 8; + int bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes + int imageBpl = image.bytesPerLine; + // Compression can actually take twice as much space, in worst case + byte[] buf = new byte[bmpBpl * 2]; + int srcOffset = imageBpl * (image.height - 1); // Start at last line + byte[] data = image.data; + totalSize = 0; + byte[] buf2 = new byte[32768]; + int buf2Offset = 0; + for (int y = image.height - 1; y >= 0; y--) { + int lineSize = compress(comp, data, srcOffset, bpl, buf, y == 0); + if (buf2Offset + lineSize > buf2.length) { + ostr.write(buf2, 0, buf2Offset); + buf2Offset = 0; + } System.arraycopy(buf, 0, buf2, buf2Offset, lineSize); - buf2Offset += lineSize; - totalSize += lineSize; - srcOffset -= imageBpl; - } - if (buf2Offset > 0) - ostr.write(buf2, 0, buf2Offset); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return totalSize; + buf2Offset += lineSize; + totalSize += lineSize; + srcOffset -= imageBpl; + } + if (buf2Offset > 0) + ostr.write(buf2, 0, buf2Offset); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return totalSize; } /** * Prepare the given image's data for unloading into a byte stream @@ -550,150 +550,150 @@ * Answer the number of bytes written. */ int unloadDataNoCompression(ImageData image, OutputStream ostr) { - int bmpBpl = 0; - try { - int bpl = (image.width * image.depth + 7) / 8; - bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes - int linesPerBuf = 32678 / bmpBpl; - byte[] buf = new byte[linesPerBuf * bmpBpl]; - byte[] data = image.data; - int imageBpl = image.bytesPerLine; - int dataIndex = imageBpl * (image.height - 1); // Start at last line - if (image.depth == 16) { - for (int y = 0; y < image.height; y += linesPerBuf) { - int count = image.height - y; - if (linesPerBuf < count) count = linesPerBuf; - int bufOffset = 0; - for (int i = 0; i < count; i++) { - for (int wIndex = 0; wIndex < bpl; wIndex += 2) { - buf[bufOffset + wIndex + 1] = data[dataIndex + wIndex + 1]; - buf[bufOffset + wIndex] = data[dataIndex + wIndex]; - } - bufOffset += bmpBpl; - dataIndex -= imageBpl; - } - ostr.write(buf, 0, bufOffset); - } - } else { - for (int y = 0; y < image.height; y += linesPerBuf) { - int tmp = image.height - y; - int count = tmp < linesPerBuf ? tmp : linesPerBuf; - int bufOffset = 0; - for (int i = 0; i < count; i++) { + int bmpBpl = 0; + try { + int bpl = (image.width * image.depth + 7) / 8; + bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes + int linesPerBuf = 32678 / bmpBpl; + byte[] buf = new byte[linesPerBuf * bmpBpl]; + byte[] data = image.data; + int imageBpl = image.bytesPerLine; + int dataIndex = imageBpl * (image.height - 1); // Start at last line + if (image.depth == 16) { + for (int y = 0; y < image.height; y += linesPerBuf) { + int count = image.height - y; + if (linesPerBuf < count) count = linesPerBuf; + int bufOffset = 0; + for (int i = 0; i < count; i++) { + for (int wIndex = 0; wIndex < bpl; wIndex += 2) { + buf[bufOffset + wIndex + 1] = data[dataIndex + wIndex + 1]; + buf[bufOffset + wIndex] = data[dataIndex + wIndex]; + } + bufOffset += bmpBpl; + dataIndex -= imageBpl; + } + ostr.write(buf, 0, bufOffset); + } + } else { + for (int y = 0; y < image.height; y += linesPerBuf) { + int tmp = image.height - y; + int count = tmp < linesPerBuf ? tmp : linesPerBuf; + int bufOffset = 0; + for (int i = 0; i < count; i++) { System.arraycopy(data, dataIndex, buf, bufOffset, bpl); - bufOffset += bmpBpl; - dataIndex -= imageBpl; - } - ostr.write(buf, 0, bufOffset); - } - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return bmpBpl * image.height; + bufOffset += bmpBpl; + dataIndex -= imageBpl; + } + ostr.write(buf, 0, bufOffset); + } + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return bmpBpl * image.height; } /** * Unload a DeviceIndependentImage using Windows .BMP format into the given * byte stream. */ void unloadIntoByteStream(ImageLoader loader) { - ImageData image = loader.data[0]; - byte[] rgbs; - int numCols; - if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8) || - (image.depth == 16) || (image.depth == 24) || (image.depth == 32))) - SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); - int comp = this.compression; - if (!((comp == 0) || ((comp == 1) && (image.depth == 8)) || - ((comp == 2) && (image.depth == 4)))) - SWT.error(SWT.ERROR_INVALID_IMAGE); - PaletteData pal = image.palette; - if ((image.depth == 16) || (image.depth == 24) || (image.depth == 32)) { - if (!pal.isDirect) - SWT.error(SWT.ERROR_INVALID_IMAGE); - numCols = 0; - rgbs = null; - } else { - if (pal.isDirect) - SWT.error(SWT.ERROR_INVALID_IMAGE); - numCols = pal.colors.length; - rgbs = paletteToBytes(pal); - } - // Fill in file header, except for bfsize, which is done later. - int headersSize = BMPFileHeaderSize + BMPHeaderFixedSize; - int[] fileHeader = new int[5]; - fileHeader[0] = 0x4D42; // Signature - fileHeader[1] = 0; // File size - filled in later - fileHeader[2] = 0; // Reserved 1 - fileHeader[3] = 0; // Reserved 2 - fileHeader[4] = headersSize; // Offset to data - if (rgbs != null) { - fileHeader[4] += rgbs.length; - } + ImageData image = loader.data[0]; + byte[] rgbs; + int numCols; + if (!((image.depth == 1) || (image.depth == 4) || (image.depth == 8) || + (image.depth == 16) || (image.depth == 24) || (image.depth == 32))) + SWT.error(SWT.ERROR_UNSUPPORTED_DEPTH); + int comp = this.compression; + if (!((comp == 0) || ((comp == 1) && (image.depth == 8)) || + ((comp == 2) && (image.depth == 4)))) + SWT.error(SWT.ERROR_INVALID_IMAGE); + PaletteData pal = image.palette; + if ((image.depth == 16) || (image.depth == 24) || (image.depth == 32)) { + if (!pal.isDirect) + SWT.error(SWT.ERROR_INVALID_IMAGE); + numCols = 0; + rgbs = null; + } else { + if (pal.isDirect) + SWT.error(SWT.ERROR_INVALID_IMAGE); + numCols = pal.colors.length; + rgbs = paletteToBytes(pal); + } + // Fill in file header, except for bfsize, which is done later. + int headersSize = BMPFileHeaderSize + BMPHeaderFixedSize; + int[] fileHeader = new int[5]; + fileHeader[0] = 0x4D42; // Signature + fileHeader[1] = 0; // File size - filled in later + fileHeader[2] = 0; // Reserved 1 + fileHeader[3] = 0; // Reserved 2 + fileHeader[4] = headersSize; // Offset to data + if (rgbs != null) { + fileHeader[4] += rgbs.length; + } - // Prepare data. This is done first so we don't have to try to rewind - // the stream and fill in the details later. - ByteArrayOutputStream ostr = new ByteArrayOutputStream(); - unloadData(image, ostr, comp); - byte[] data = ostr.toByteArray(); + // Prepare data. This is done first so we don't have to try to rewind + // the stream and fill in the details later. + ByteArrayOutputStream ostr = new ByteArrayOutputStream(); + unloadData(image, ostr, comp); + byte[] data = ostr.toByteArray(); - // Calculate file size - fileHeader[1] = fileHeader[4] + data.length; + // Calculate file size + fileHeader[1] = fileHeader[4] + data.length; - // Write the headers - try { - outputStream.writeShort(fileHeader[0]); - outputStream.writeInt(fileHeader[1]); - outputStream.writeShort(fileHeader[2]); - outputStream.writeShort(fileHeader[3]); - outputStream.writeInt(fileHeader[4]); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - try { - outputStream.writeInt(BMPHeaderFixedSize); - outputStream.writeInt(image.width); - outputStream.writeInt(image.height); - outputStream.writeShort(1); - outputStream.writeShort(cast(short)image.depth); - outputStream.writeInt(comp); - outputStream.writeInt(data.length); - outputStream.writeInt(pelsPerMeter.x); - outputStream.writeInt(pelsPerMeter.y); - outputStream.writeInt(numCols); - outputStream.writeInt(importantColors); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + // Write the headers + try { + outputStream.writeShort(fileHeader[0]); + outputStream.writeInt(fileHeader[1]); + outputStream.writeShort(fileHeader[2]); + outputStream.writeShort(fileHeader[3]); + outputStream.writeInt(fileHeader[4]); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + try { + outputStream.writeInt(BMPHeaderFixedSize); + outputStream.writeInt(image.width); + outputStream.writeInt(image.height); + outputStream.writeShort(1); + outputStream.writeShort(cast(short)image.depth); + outputStream.writeInt(comp); + outputStream.writeInt(data.length); + outputStream.writeInt(pelsPerMeter.x); + outputStream.writeInt(pelsPerMeter.y); + outputStream.writeInt(numCols); + outputStream.writeInt(importantColors); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } - // Unload palette - if (numCols > 0) { - try { - outputStream.write(rgbs); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - } + // Unload palette + if (numCols > 0) { + try { + outputStream.write(rgbs); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + } - // Unload the data - try { - outputStream.write(data); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + // Unload the data + try { + outputStream.write(data); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } void flipScanLines(byte[] data, int stride, int height) { - int i1 = 0; - int i2 = (height - 1) * stride; - for (int i = 0; i < height / 2; i++) { - for (int index = 0; index < stride; index++) { - byte b = data[index + i1]; - data[index + i1] = data[index + i2]; - data[index + i2] = b; - } - i1 += stride; - i2 -= stride; - } + int i1 = 0; + int i2 = (height - 1) * stride; + for (int i = 0; i < height / 2; i++) { + for (int index = 0; index < stride; index++) { + byte b = data[index + i1]; + data[index + i1] = data[index + i2]; + data[index + i2] = b; + } + i1 += stride; + i2 -= stride; + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/internal/image/WinICOFileFormat.d --- a/dwt/internal/image/WinICOFileFormat.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/internal/image/WinICOFileFormat.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -20,309 +20,309 @@ final class WinICOFileFormat : FileFormat { byte[] bitInvertData(byte[] data, int startIndex, int endIndex) { - // Destructively bit invert data in the given byte array. - for (int i = startIndex; i < endIndex; i++) { - data[i] = cast(byte)(255 - data[i - startIndex]); - } - return data; + // Destructively bit invert data in the given byte array. + for (int i = startIndex; i < endIndex; i++) { + data[i] = cast(byte)(255 - data[i - startIndex]); + } + return data; } static final byte[] convertPad(byte[] data, int width, int height, int depth, int pad, int newPad) { - if (pad == newPad) return data; - int stride = (width * depth + 7) / 8; - int bpl = (stride + (pad - 1)) / pad * pad; - int newBpl = (stride + (newPad - 1)) / newPad * newPad; - byte[] newData = new byte[height * newBpl]; - int srcIndex = 0, destIndex = 0; - for (int y = 0; y < height; y++) { + if (pad == newPad) return data; + int stride = (width * depth + 7) / 8; + int bpl = (stride + (pad - 1)) / pad * pad; + int newBpl = (stride + (newPad - 1)) / newPad * newPad; + byte[] newData = new byte[height * newBpl]; + int srcIndex = 0, destIndex = 0; + for (int y = 0; y < height; y++) { System.arraycopy(data, srcIndex, newData, destIndex, newBpl); - srcIndex += bpl; - destIndex += newBpl; - } - return newData; + srcIndex += bpl; + destIndex += newBpl; + } + return newData; } /** * Answer the size in bytes of the file representation of the given * icon */ int iconSize(ImageData i) { - int shapeDataStride = (i.width * i.depth + 31) / 32 * 4; - int maskDataStride = (i.width + 31) / 32 * 4; - int dataSize = (shapeDataStride + maskDataStride) * i.height; - int paletteSize = i.palette.colors != null ? i.palette.colors.length * 4 : 0; - return WinBMPFileFormat.BMPHeaderFixedSize + paletteSize + dataSize; + int shapeDataStride = (i.width * i.depth + 31) / 32 * 4; + int maskDataStride = (i.width + 31) / 32 * 4; + int dataSize = (shapeDataStride + maskDataStride) * i.height; + int paletteSize = i.palette.colors != null ? i.palette.colors.length * 4 : 0; + return WinBMPFileFormat.BMPHeaderFixedSize + paletteSize + dataSize; } bool isFileFormat(LEDataInputStream stream) { - try { - byte[] header = new byte[4]; - stream.read(header); - stream.unread(header); - return header[0] == 0 && header[1] == 0 && header[2] == 1 && header[3] == 0; - } catch (Exception e) { - return false; - } + try { + byte[] header = new byte[4]; + stream.read(header); + stream.unread(header); + return header[0] == 0 && header[1] == 0 && header[2] == 1 && header[3] == 0; + } catch (Exception e) { + return false; + } } bool isValidIcon(ImageData i) { - switch (i.depth) { - case 1: - case 4: - case 8: - if (i.palette.isDirect) return false; - int size = i.palette.colors.length; - return size == 2 || size == 16 || size == 32 || size == 256; - case 24: - case 32: - return i.palette.isDirect; + switch (i.depth) { + case 1: + case 4: + case 8: + if (i.palette.isDirect) return false; + int size = i.palette.colors.length; + return size == 2 || size == 16 || size == 32 || size == 256; + case 24: + case 32: + return i.palette.isDirect; default: - } - return false; + } + return false; } int loadFileHeader(LEDataInputStream byteStream) { - int[] fileHeader = new int[3]; - try { - fileHeader[0] = byteStream.readShort(); - fileHeader[1] = byteStream.readShort(); - fileHeader[2] = byteStream.readShort(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if ((fileHeader[0] != 0) || (fileHeader[1] != 1)) - SWT.error(SWT.ERROR_INVALID_IMAGE); - int numIcons = fileHeader[2]; - if (numIcons <= 0) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return numIcons; + int[] fileHeader = new int[3]; + try { + fileHeader[0] = byteStream.readShort(); + fileHeader[1] = byteStream.readShort(); + fileHeader[2] = byteStream.readShort(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if ((fileHeader[0] != 0) || (fileHeader[1] != 1)) + SWT.error(SWT.ERROR_INVALID_IMAGE); + int numIcons = fileHeader[2]; + if (numIcons <= 0) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return numIcons; } int loadFileHeader(LEDataInputStream byteStream, bool hasHeader) { - int[] fileHeader = new int[3]; - try { - if (hasHeader) { - fileHeader[0] = byteStream.readShort(); - fileHeader[1] = byteStream.readShort(); - } else { - fileHeader[0] = 0; - fileHeader[1] = 1; - } - fileHeader[2] = byteStream.readShort(); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if ((fileHeader[0] != 0) || (fileHeader[1] != 1)) - SWT.error(SWT.ERROR_INVALID_IMAGE); - int numIcons = fileHeader[2]; - if (numIcons <= 0) - SWT.error(SWT.ERROR_INVALID_IMAGE); - return numIcons; + int[] fileHeader = new int[3]; + try { + if (hasHeader) { + fileHeader[0] = byteStream.readShort(); + fileHeader[1] = byteStream.readShort(); + } else { + fileHeader[0] = 0; + fileHeader[1] = 1; + } + fileHeader[2] = byteStream.readShort(); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if ((fileHeader[0] != 0) || (fileHeader[1] != 1)) + SWT.error(SWT.ERROR_INVALID_IMAGE); + int numIcons = fileHeader[2]; + if (numIcons <= 0) + SWT.error(SWT.ERROR_INVALID_IMAGE); + return numIcons; } ImageData[] loadFromByteStream() { - int numIcons = loadFileHeader(inputStream); - int[][] headers = loadIconHeaders(numIcons); - ImageData[] icons = new ImageData[headers.length]; - for (int i = 0; i < icons.length; i++) { - icons[i] = loadIcon(headers[i]); - } - return icons; + int numIcons = loadFileHeader(inputStream); + int[][] headers = loadIconHeaders(numIcons); + ImageData[] icons = new ImageData[headers.length]; + for (int i = 0; i < icons.length; i++) { + icons[i] = loadIcon(headers[i]); + } + return icons; } /** * Load one icon from the byte stream. */ ImageData loadIcon(int[] iconHeader) { - byte[] infoHeader = loadInfoHeader(iconHeader); - WinBMPFileFormat bmpFormat = new WinBMPFileFormat(); - bmpFormat.inputStream = inputStream; - PaletteData palette = bmpFormat.loadPalette(infoHeader); - byte[] shapeData = bmpFormat.loadData(infoHeader); - int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); - int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); - if (height < 0) height = -height; - int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); - infoHeader[14] = 1; - infoHeader[15] = 0; - byte[] maskData = bmpFormat.loadData(infoHeader); - maskData = convertPad(maskData, width, height, 1, 4, 2); - bitInvertData(maskData, 0, maskData.length); - return ImageData.internal_new( - width, - height, - depth, - palette, - 4, - shapeData, - 2, - maskData, - null, - -1, - -1, - SWT.IMAGE_ICO, - 0, - 0, - 0, - 0); + byte[] infoHeader = loadInfoHeader(iconHeader); + WinBMPFileFormat bmpFormat = new WinBMPFileFormat(); + bmpFormat.inputStream = inputStream; + PaletteData palette = bmpFormat.loadPalette(infoHeader); + byte[] shapeData = bmpFormat.loadData(infoHeader); + int width = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); + int height = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); + if (height < 0) height = -height; + int depth = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); + infoHeader[14] = 1; + infoHeader[15] = 0; + byte[] maskData = bmpFormat.loadData(infoHeader); + maskData = convertPad(maskData, width, height, 1, 4, 2); + bitInvertData(maskData, 0, maskData.length); + return ImageData.internal_new( + width, + height, + depth, + palette, + 4, + shapeData, + 2, + maskData, + null, + -1, + -1, + SWT.IMAGE_ICO, + 0, + 0, + 0, + 0); } int[][] loadIconHeaders(int numIcons) { - int[][] headers = new int[][]( numIcons, 7 ); - try { - for (int i = 0; i < numIcons; i++) { - headers[i][0] = inputStream.read(); - headers[i][1] = inputStream.read(); - headers[i][2] = inputStream.readShort(); - headers[i][3] = inputStream.readShort(); - headers[i][4] = inputStream.readShort(); - headers[i][5] = inputStream.readInt(); - headers[i][6] = inputStream.readInt(); - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - return headers; + int[][] headers = new int[][]( numIcons, 7 ); + try { + for (int i = 0; i < numIcons; i++) { + headers[i][0] = inputStream.read(); + headers[i][1] = inputStream.read(); + headers[i][2] = inputStream.readShort(); + headers[i][3] = inputStream.readShort(); + headers[i][4] = inputStream.readShort(); + headers[i][5] = inputStream.readInt(); + headers[i][6] = inputStream.readInt(); + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + return headers; } byte[] loadInfoHeader(int[] iconHeader) { - int width = iconHeader[0]; - int height = iconHeader[1]; - int numColors = iconHeader[2]; // the number of colors is in the low byte, but the high byte must be 0 - if (numColors == 0) numColors = 256; // this is specified: '00' represents '256' (0x100) colors - if ((numColors != 2) && (numColors != 8) && (numColors != 16) && - (numColors != 32) && (numColors != 256)) - SWT.error(SWT.ERROR_INVALID_IMAGE); - if (inputStream.getPosition() < iconHeader[6]) { - // Seek to the specified offset - try { - inputStream.skip(iconHeader[6] - inputStream.getPosition()); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - return null; - } - } - byte[] infoHeader = new byte[WinBMPFileFormat.BMPHeaderFixedSize]; - try { - inputStream.read(infoHeader); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - if (((infoHeader[12] & 0xFF) | ((infoHeader[13] & 0xFF) << 8)) != 1) - SWT.error(SWT.ERROR_INVALID_IMAGE); - int infoWidth = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); - int infoHeight = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); - int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); - if (height == infoHeight && bitCount == 1) height /= 2; - if (!((width == infoWidth) && (height * 2 == infoHeight) && - (bitCount == 1 || bitCount == 4 || bitCount == 8 || bitCount == 24 || bitCount == 32))) - SWT.error(SWT.ERROR_INVALID_IMAGE); - infoHeader[8] = cast(byte)(height & 0xFF); - infoHeader[9] = cast(byte)((height >> 8) & 0xFF); - infoHeader[10] = cast(byte)((height >> 16) & 0xFF); - infoHeader[11] = cast(byte)((height >> 24) & 0xFF); - return infoHeader; + int width = iconHeader[0]; + int height = iconHeader[1]; + int numColors = iconHeader[2]; // the number of colors is in the low byte, but the high byte must be 0 + if (numColors == 0) numColors = 256; // this is specified: '00' represents '256' (0x100) colors + if ((numColors != 2) && (numColors != 8) && (numColors != 16) && + (numColors != 32) && (numColors != 256)) + SWT.error(SWT.ERROR_INVALID_IMAGE); + if (inputStream.getPosition() < iconHeader[6]) { + // Seek to the specified offset + try { + inputStream.skip(iconHeader[6] - inputStream.getPosition()); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + return null; + } + } + byte[] infoHeader = new byte[WinBMPFileFormat.BMPHeaderFixedSize]; + try { + inputStream.read(infoHeader); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + if (((infoHeader[12] & 0xFF) | ((infoHeader[13] & 0xFF) << 8)) != 1) + SWT.error(SWT.ERROR_INVALID_IMAGE); + int infoWidth = (infoHeader[4] & 0xFF) | ((infoHeader[5] & 0xFF) << 8) | ((infoHeader[6] & 0xFF) << 16) | ((infoHeader[7] & 0xFF) << 24); + int infoHeight = (infoHeader[8] & 0xFF) | ((infoHeader[9] & 0xFF) << 8) | ((infoHeader[10] & 0xFF) << 16) | ((infoHeader[11] & 0xFF) << 24); + int bitCount = (infoHeader[14] & 0xFF) | ((infoHeader[15] & 0xFF) << 8); + if (height == infoHeight && bitCount == 1) height /= 2; + if (!((width == infoWidth) && (height * 2 == infoHeight) && + (bitCount == 1 || bitCount == 4 || bitCount == 8 || bitCount == 24 || bitCount == 32))) + SWT.error(SWT.ERROR_INVALID_IMAGE); + infoHeader[8] = cast(byte)(height & 0xFF); + infoHeader[9] = cast(byte)((height >> 8) & 0xFF); + infoHeader[10] = cast(byte)((height >> 16) & 0xFF); + infoHeader[11] = cast(byte)((height >> 24) & 0xFF); + return infoHeader; } /** * Unload a single icon */ void unloadIcon(ImageData icon) { - int sizeImage = (((icon.width * icon.depth + 31) / 32 * 4) + - ((icon.width + 31) / 32 * 4)) * icon.height; - try { - outputStream.writeInt(WinBMPFileFormat.BMPHeaderFixedSize); - outputStream.writeInt(icon.width); - outputStream.writeInt(icon.height * 2); - outputStream.writeShort(1); - outputStream.writeShort(cast(short)icon.depth); - outputStream.writeInt(0); - outputStream.writeInt(sizeImage); - outputStream.writeInt(0); - outputStream.writeInt(0); - outputStream.writeInt(icon.palette.colors != null ? icon.palette.colors.length : 0); - outputStream.writeInt(0); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + int sizeImage = (((icon.width * icon.depth + 31) / 32 * 4) + + ((icon.width + 31) / 32 * 4)) * icon.height; + try { + outputStream.writeInt(WinBMPFileFormat.BMPHeaderFixedSize); + outputStream.writeInt(icon.width); + outputStream.writeInt(icon.height * 2); + outputStream.writeShort(1); + outputStream.writeShort(cast(short)icon.depth); + outputStream.writeInt(0); + outputStream.writeInt(sizeImage); + outputStream.writeInt(0); + outputStream.writeInt(0); + outputStream.writeInt(icon.palette.colors != null ? icon.palette.colors.length : 0); + outputStream.writeInt(0); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } - byte[] rgbs = WinBMPFileFormat.paletteToBytes(icon.palette); - try { - outputStream.write(rgbs); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - unloadShapeData(icon); - unloadMaskData(icon); + byte[] rgbs = WinBMPFileFormat.paletteToBytes(icon.palette); + try { + outputStream.write(rgbs); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + unloadShapeData(icon); + unloadMaskData(icon); } /** * Unload the icon header for the given icon, calculating the offset. */ void unloadIconHeader(ImageData i) { - int headerSize = 16; - int offset = headerSize + 6; - int iconSize = iconSize(i); - try { - outputStream.write(i.width); - outputStream.write(i.height); - outputStream.writeShort(i.palette.colors != null ? i.palette.colors.length : 0); - outputStream.writeShort(0); - outputStream.writeShort(0); - outputStream.writeInt(iconSize); - outputStream.writeInt(offset); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + int headerSize = 16; + int offset = headerSize + 6; + int iconSize = iconSize(i); + try { + outputStream.write(i.width); + outputStream.write(i.height); + outputStream.writeShort(i.palette.colors != null ? i.palette.colors.length : 0); + outputStream.writeShort(0); + outputStream.writeShort(0); + outputStream.writeInt(iconSize); + outputStream.writeInt(offset); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } void unloadIntoByteStream(ImageLoader loader) { - /* We do not currently support writing multi-image ico, - * so we use the first image data in the loader's array. */ - ImageData image = loader.data[0]; - if (!isValidIcon(image)) - SWT.error(SWT.ERROR_INVALID_IMAGE); - try { - outputStream.writeShort(0); - outputStream.writeShort(1); - outputStream.writeShort(1); - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } - unloadIconHeader(image); - unloadIcon(image); + /* We do not currently support writing multi-image ico, + * so we use the first image data in the loader's array. */ + ImageData image = loader.data[0]; + if (!isValidIcon(image)) + SWT.error(SWT.ERROR_INVALID_IMAGE); + try { + outputStream.writeShort(0); + outputStream.writeShort(1); + outputStream.writeShort(1); + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } + unloadIconHeader(image); + unloadIcon(image); } /** * Unload the mask data for an icon. The data is flipped vertically * and inverted. */ void unloadMaskData(ImageData icon) { - ImageData mask = icon.getTransparencyMask(); - int bpl = (icon.width + 7) / 8; - int pad = mask.scanlinePad; - int srcBpl = (bpl + pad - 1) / pad * pad; - int destBpl = (bpl + 3) / 4 * 4; - byte[] buf = new byte[destBpl]; - int offset = (icon.height - 1) * srcBpl; - byte[] data = mask.data; - try { - for (int i = 0; i < icon.height; i++) { + ImageData mask = icon.getTransparencyMask(); + int bpl = (icon.width + 7) / 8; + int pad = mask.scanlinePad; + int srcBpl = (bpl + pad - 1) / pad * pad; + int destBpl = (bpl + 3) / 4 * 4; + byte[] buf = new byte[destBpl]; + int offset = (icon.height - 1) * srcBpl; + byte[] data = mask.data; + try { + for (int i = 0; i < icon.height; i++) { System.arraycopy(data, offset, buf, 0, bpl); - bitInvertData(buf, 0, bpl); - outputStream.write(buf, 0, destBpl); - offset -= srcBpl; - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + bitInvertData(buf, 0, bpl); + outputStream.write(buf, 0, destBpl); + offset -= srcBpl; + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } /** * Unload the shape data for an icon. The data is flipped vertically. */ void unloadShapeData(ImageData icon) { - int bpl = (icon.width * icon.depth + 7) / 8; - int pad = icon.scanlinePad; - int srcBpl = (bpl + pad - 1) / pad * pad; - int destBpl = (bpl + 3) / 4 * 4; - byte[] buf = new byte[destBpl]; - int offset = (icon.height - 1) * srcBpl; - byte[] data = icon.data; - try { - for (int i = 0; i < icon.height; i++) { + int bpl = (icon.width * icon.depth + 7) / 8; + int pad = icon.scanlinePad; + int srcBpl = (bpl + pad - 1) / pad * pad; + int destBpl = (bpl + 3) / 4 * 4; + byte[] buf = new byte[destBpl]; + int offset = (icon.height - 1) * srcBpl; + byte[] data = icon.data; + try { + for (int i = 0; i < icon.height; i++) { System.arraycopy(data, offset, buf, 0, bpl); - outputStream.write(buf, 0, destBpl); - offset -= srcBpl; - } - } catch (IOException e) { - SWT.error(SWT.ERROR_IO, e); - } + outputStream.write(buf, 0, destBpl); + offset -= srcBpl; + } + } catch (IOException e) { + SWT.error(SWT.ERROR_IO, e); + } } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/FillData.d --- a/dwt/layout/FillData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/FillData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 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 @@ -16,30 +16,30 @@ class FillData { - int defaultWidth = -1, defaultHeight = -1; - int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; + int defaultWidth = -1, defaultHeight = -1; + int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; Point computeSize (Control control, int wHint, int hHint, bool flushCache_) { - if (flushCache_) flushCache(); - if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { - if (defaultWidth is -1 || defaultHeight is -1) { - Point size = control.computeSize (wHint, hHint, flushCache_); - defaultWidth = size.x; - defaultHeight = size.y; - } - return new Point(defaultWidth, defaultHeight); - } - if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { - Point size = control.computeSize (wHint, hHint, flushCache_); - currentWhint = wHint; - currentHhint = hHint; - currentWidth = size.x; - currentHeight = size.y; - } - return new Point(currentWidth, currentHeight); + if (flushCache_) flushCache(); + if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { + if (defaultWidth is -1 || defaultHeight is -1) { + Point size = control.computeSize (wHint, hHint, flushCache_); + defaultWidth = size.x; + defaultHeight = size.y; + } + return new Point(defaultWidth, defaultHeight); + } + if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { + Point size = control.computeSize (wHint, hHint, flushCache_); + currentWhint = wHint; + currentHhint = hHint; + currentWidth = size.x; + currentHeight = size.y; + } + return new Point(currentWidth, currentHeight); } void flushCache () { - defaultWidth = defaultHeight = -1; - currentWidth = currentHeight = -1; + defaultWidth = defaultHeight = -1; + currentWidth = currentHeight = -1; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/FillLayout.d --- a/dwt/layout/FillLayout.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/FillLayout.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -42,55 +42,55 @@ * Composite. Note that in a FillLayout, * children are always the same size, and they fill all available space. *
    - * 		FillLayout fillLayout = new FillLayout();
    - * 		fillLayout.type = SWT.VERTICAL;
    - * 		shell.setLayout(fillLayout);
    + *      FillLayout fillLayout = new FillLayout();
    + *      fillLayout.type = SWT.VERTICAL;
    + *      shell.setLayout(fillLayout);
      * 
    *

    */ public final class FillLayout : Layout { - /** - * type specifies how controls will be positioned - * within the layout. - * - * The default value is HORIZONTAL. - * - * Possible values are:
      - *
    • HORIZONTAL: Position the controls horizontally from left to right
    • - *
    • VERTICAL: Position the controls vertically from top to bottom
    • - *
    - */ - public int type = SWT.HORIZONTAL; + /** + * type specifies how controls will be positioned + * within the layout. + * + * The default value is HORIZONTAL. + * + * Possible values are:
      + *
    • HORIZONTAL: Position the controls horizontally from left to right
    • + *
    • VERTICAL: Position the controls vertically from top to bottom
    • + *
    + */ + public int type = SWT.HORIZONTAL; - /** - * marginWidth specifies the number of pixels of horizontal margin - * that will be placed along the left and right edges of the layout. - * - * The default value is 0. - * - * @since 3.0 - */ - public int marginWidth = 0; + /** + * marginWidth specifies the number of pixels of horizontal margin + * that will be placed along the left and right edges of the layout. + * + * The default value is 0. + * + * @since 3.0 + */ + public int marginWidth = 0; - /** - * marginHeight specifies the number of pixels of vertical margin - * that will be placed along the top and bottom edges of the layout. - * - * The default value is 0. - * - * @since 3.0 - */ - public int marginHeight = 0; + /** + * marginHeight specifies the number of pixels of vertical margin + * that will be placed along the top and bottom edges of the layout. + * + * The default value is 0. + * + * @since 3.0 + */ + public int marginHeight = 0; - /** - * spacing specifies the number of pixels between the edge of one cell - * and the edge of its neighbouring cell. - * - * The default value is 0. - * - * @since 3.0 - */ - public int spacing = 0; + /** + * spacing specifies the number of pixels between the edge of one cell + * and the edge of its neighbouring cell. + * + * The default value is 0. + * + * @since 3.0 + */ + public int spacing = 0; /** * Constructs a new instance of this class. @@ -106,122 +106,122 @@ * @since 2.0 */ public this (int type) { - this.type = type; + this.type = type; } protected Point computeSize (Composite composite, int wHint, int hHint, bool flushCache) { - Control [] children = composite.getChildren (); - int count = children.length; - int maxWidth = 0, maxHeight = 0; - for (int i=0; i 0) { - if (type is SWT.HORIZONTAL && wHint !is SWT.DEFAULT) { - w = Math.max (0, (wHint - (count - 1) * spacing) / count); - } - if (type is SWT.VERTICAL && hHint !is SWT.DEFAULT) { - h = Math.max (0, (hHint - (count - 1) * spacing) / count); - } - } - Point size = computeChildSize (child, w, h, flushCache); - maxWidth = Math.max (maxWidth, size.x); - maxHeight = Math.max (maxHeight, size.y); - } - int width = 0, height = 0; - if (type is SWT.HORIZONTAL) { - width = count * maxWidth; - if (count !is 0) width += (count - 1) * spacing; - height = maxHeight; - } else { - width = maxWidth; - height = count * maxHeight; - if (count !is 0) height += (count - 1) * spacing; - } - width += marginWidth * 2; - height += marginHeight * 2; - if (wHint !is SWT.DEFAULT) width = wHint; - if (hHint !is SWT.DEFAULT) height = hHint; - return new Point (width, height); + Control [] children = composite.getChildren (); + int count = children.length; + int maxWidth = 0, maxHeight = 0; + for (int i=0; i 0) { + if (type is SWT.HORIZONTAL && wHint !is SWT.DEFAULT) { + w = Math.max (0, (wHint - (count - 1) * spacing) / count); + } + if (type is SWT.VERTICAL && hHint !is SWT.DEFAULT) { + h = Math.max (0, (hHint - (count - 1) * spacing) / count); + } + } + Point size = computeChildSize (child, w, h, flushCache); + maxWidth = Math.max (maxWidth, size.x); + maxHeight = Math.max (maxHeight, size.y); + } + int width = 0, height = 0; + if (type is SWT.HORIZONTAL) { + width = count * maxWidth; + if (count !is 0) width += (count - 1) * spacing; + height = maxHeight; + } else { + width = maxWidth; + height = count * maxHeight; + if (count !is 0) height += (count - 1) * spacing; + } + width += marginWidth * 2; + height += marginHeight * 2; + if (wHint !is SWT.DEFAULT) width = wHint; + if (hHint !is SWT.DEFAULT) height = hHint; + return new Point (width, height); } Point computeChildSize (Control control, int wHint, int hHint, bool flushCache) { - FillData data = cast(FillData)control.getLayoutData (); - if (data is null) { - data = new FillData (); - control.setLayoutData (data); - } - Point size = null; - if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { - size = data.computeSize (control, wHint, hHint, flushCache); - } else { - // TEMPORARY CODE - int trimX, trimY; - if ( auto sa = cast(Scrollable)control ) { - Rectangle rect = sa.computeTrim (0, 0, 0, 0); - trimX = rect.width; - trimY = rect.height; - } else { - trimX = trimY = control.getBorderWidth () * 2; - } - int w = wHint is SWT.DEFAULT ? wHint : Math.max (0, wHint - trimX); - int h = hHint is SWT.DEFAULT ? hHint : Math.max (0, hHint - trimY); - size = data.computeSize (control, w, h, flushCache); - } - return size; + FillData data = cast(FillData)control.getLayoutData (); + if (data is null) { + data = new FillData (); + control.setLayoutData (data); + } + Point size = null; + if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { + size = data.computeSize (control, wHint, hHint, flushCache); + } else { + // TEMPORARY CODE + int trimX, trimY; + if ( auto sa = cast(Scrollable)control ) { + Rectangle rect = sa.computeTrim (0, 0, 0, 0); + trimX = rect.width; + trimY = rect.height; + } else { + trimX = trimY = control.getBorderWidth () * 2; + } + int w = wHint is SWT.DEFAULT ? wHint : Math.max (0, wHint - trimX); + int h = hHint is SWT.DEFAULT ? hHint : Math.max (0, hHint - trimY); + size = data.computeSize (control, w, h, flushCache); + } + return size; } protected bool flushCache (Control control) { - Object data = control.getLayoutData(); - if (data !is null) (cast(FillData)data).flushCache(); - return true; + Object data = control.getLayoutData(); + if (data !is null) (cast(FillData)data).flushCache(); + return true; } char[] getName () { - char[] string = this.classinfo.name; - int index = locatePrior( string, '.'); - if (index is string.length ) return string; - return string[ index + 1 .. string.length ]; + char[] string = this.classinfo.name; + int index = locatePrior( string, '.'); + if (index is string.length ) return string; + return string[ index + 1 .. string.length ]; } protected void layout (Composite composite, bool flushCache) { - Rectangle rect = composite.getClientArea (); - Control [] children = composite.getChildren (); - int count = children.length; - if (count is 0) return; - int width = rect.width - marginWidth * 2; - int height = rect.height - marginHeight * 2; - if (type is SWT.HORIZONTAL) { - width -= (count - 1) * spacing; - int x = rect.x + marginWidth, extra = width % count; - int y = rect.y + marginHeight, cellWidth = width / count; - for (int i=0; iFormData for a control. * For example: *
    - * 		FormData data = new FormData();
    - * 		data.top = new FormAttachment(0,5);
    - * 		data.bottom = new FormAttachment(100,-5);
    - * 		data.left = new FormAttachment(0,5);
    - * 		data.right = new FormAttachment(100,-5);
    - * 		button.setLayoutData(data);
    + *      FormData data = new FormData();
    + *      data.top = new FormAttachment(0,5);
    + *      data.bottom = new FormAttachment(100,-5);
    + *      data.left = new FormAttachment(0,5);
    + *      data.right = new FormAttachment(100,-5);
    + *      button.setLayoutData(data);
      * 
    *

    *

    @@ -42,7 +42,7 @@ * is set to 100. The "b" term in the equation represents an offset, in * pixels, from the attachment position. For example: *

    - * 		FormAttachment attach = new FormAttachment (20, -5);
    + *      FormAttachment attach = new FormAttachment (20, -5);
      * 
    * specifies that the side to which the FormAttachment * object belongs will lie at 20% of the parent composite, minus 5 pixels. @@ -51,7 +51,7 @@ * Control sides can also be attached to another control. * For example: *
    - * 		FormAttachment attach = new FormAttachment (button, 10);
    + *      FormAttachment attach = new FormAttachment (button, 10);
      * 
    * specifies that the side to which the FormAttachment * object belongs will lie in the same position as the adjacent side of @@ -59,15 +59,15 @@ * also be attached to the opposite side of the specified control. * For example: *
    - * 		FormData data = new FormData ();
    - * 		data.left = new FormAttachment (button, 0, SWT.LEFT);
    + *      FormData data = new FormData ();
    + *      data.left = new FormAttachment (button, 0, SWT.LEFT);
      * 
    * specifies that the left side of the control will lie in the same position * as the left side of the button control. The control can also * be attached in a position that will center the control on the specified * control. For example: *
    - * 		data.left = new FormAttachment (button, 0, SWT.CENTER);
    + *      data.left = new FormAttachment (button, 0, SWT.CENTER);
      * 
    * specifies that the left side of the control will be positioned so that it is * centered between the left and right sides of the button control. @@ -80,58 +80,58 @@ * @since 2.0 */ public final class FormAttachment { - /** - * numerator specifies the numerator of the "a" term in the - * equation, y = ax + b, which defines the attachment. - */ - public int numerator; + /** + * numerator specifies the numerator of the "a" term in the + * equation, y = ax + b, which defines the attachment. + */ + public int numerator; - /** - * denominator specifies the denominator of the "a" term in the - * equation, y = ax + b, which defines the attachment. - * - * The default value is 100. - */ - public int denominator = 100; + /** + * denominator specifies the denominator of the "a" term in the + * equation, y = ax + b, which defines the attachment. + * + * The default value is 100. + */ + public int denominator = 100; - /** - * offset specifies the offset, in pixels, of the control side - * from the attachment position. - * If the offset is positive, then the control side is offset - * to the right of or below the attachment position. If it is - * negative, then the control side is offset to the left of or - * above the attachment position. - * - * This is equivalent to the "b" term in the equation y = ax + b. - * The default value is 0. - */ - public int offset; + /** + * offset specifies the offset, in pixels, of the control side + * from the attachment position. + * If the offset is positive, then the control side is offset + * to the right of or below the attachment position. If it is + * negative, then the control side is offset to the left of or + * above the attachment position. + * + * This is equivalent to the "b" term in the equation y = ax + b. + * The default value is 0. + */ + public int offset; - /** - * control specifies the control to which the control side is - * attached. - */ - public Control control; + /** + * control specifies the control to which the control side is + * attached. + */ + public Control control; - /** - * alignment specifies the alignment of the control side that is - * attached to a control. - *

    - * For top and bottom attachments, TOP, BOTTOM and CENTER are used. For left - * and right attachments, LEFT, RIGHT and CENTER are used. If any other case - * occurs, the default will be used instead. - *

    - * - *
    Possible values are:
      - *
    • TOP: Attach the side to the top side of the specified control.
    • - *
    • BOTTOM : Attach the side to the bottom side of the specified control.
    • - *
    • LEFT: Attach the side to the left side of the specified control.
    • - *
    • RIGHT: Attach the side to the right side of the specified control.
    • - *
    • CENTER: Attach the side at a position which will center the control on the specified control.
    • - *
    • DEFAULT: Attach the side to the adjacent side of the specified control.
    • - *
    - */ - public int alignment; + /** + * alignment specifies the alignment of the control side that is + * attached to a control. + *

    + * For top and bottom attachments, TOP, BOTTOM and CENTER are used. For left + * and right attachments, LEFT, RIGHT and CENTER are used. If any other case + * occurs, the default will be used instead. + *

    + * + *
    Possible values are:
      + *
    • TOP: Attach the side to the top side of the specified control.
    • + *
    • BOTTOM : Attach the side to the bottom side of the specified control.
    • + *
    • LEFT: Attach the side to the left side of the specified control.
    • + *
    • RIGHT: Attach the side to the right side of the specified control.
    • + *
    • CENTER: Attach the side at a position which will center the control on the specified control.
    • + *
    • DEFAULT: Attach the side to the adjacent side of the specified control.
    • + *
    + */ + public int alignment; /** * Constructs a new instance of this class. @@ -156,7 +156,7 @@ * @since 3.0 */ public this (int numerator) { - this (numerator, 100, 0); + this (numerator, 100, 0); } /** @@ -169,7 +169,7 @@ * @param offset the offset of the side from the position */ public this (int numerator, int offset) { - this (numerator, 100, offset); + this (numerator, 100, offset); } /** @@ -183,10 +183,10 @@ * @param offset the offset of the side from the position */ public this (int numerator, int denominator, int offset) { - if (denominator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); - this.numerator = numerator; - this.denominator = denominator; - this.offset = offset; + if (denominator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); + this.numerator = numerator; + this.denominator = denominator; + this.offset = offset; } /** @@ -199,7 +199,7 @@ * @param control the control the side is attached to */ public this (Control control) { - this (control, 0, SWT.DEFAULT); + this (control, 0, SWT.DEFAULT); } /** @@ -212,7 +212,7 @@ * @param offset the offset of the side from the control */ public this (Control control, int offset) { - this (control, offset, SWT.DEFAULT); + this (control, offset, SWT.DEFAULT); } /** @@ -224,70 +224,70 @@ * @param alignment the alignment of the side to the control it is attached to */ public this (Control control, int offset, int alignment) { - this.control = control; - this.offset = offset; - this.alignment = alignment; + this.control = control; + this.offset = offset; + this.alignment = alignment; } FormAttachment divide (int value) { - return new FormAttachment (numerator, denominator * value, offset / value); + return new FormAttachment (numerator, denominator * value, offset / value); } int gcd (int m, int n) { - int temp; - m = Math.abs (m); - n = Math.abs (n); - if (m < n) { - temp = m; - m = n; - n = temp; - } - while (n != 0){ - temp = m; - m = n; - n = temp % n; - } - return m; + int temp; + m = Math.abs (m); + n = Math.abs (n); + if (m < n) { + temp = m; + m = n; + n = temp; + } + while (n != 0){ + temp = m; + m = n; + n = temp % n; + } + return m; } FormAttachment minus (FormAttachment attachment) { - FormAttachment solution = new FormAttachment (); - solution.numerator = numerator * attachment.denominator - denominator * attachment.numerator; - solution.denominator = denominator * attachment.denominator; - int gcd = gcd (solution.denominator, solution.numerator); - solution.numerator = solution.numerator / gcd; - solution.denominator = solution.denominator / gcd; - solution.offset = offset - attachment.offset; - return solution; + FormAttachment solution = new FormAttachment (); + solution.numerator = numerator * attachment.denominator - denominator * attachment.numerator; + solution.denominator = denominator * attachment.denominator; + int gcd = gcd (solution.denominator, solution.numerator); + solution.numerator = solution.numerator / gcd; + solution.denominator = solution.denominator / gcd; + solution.offset = offset - attachment.offset; + return solution; } FormAttachment minus (int value) { - return new FormAttachment (numerator, denominator, offset - value); + return new FormAttachment (numerator, denominator, offset - value); } FormAttachment plus (FormAttachment attachment) { - FormAttachment solution = new FormAttachment (); - solution.numerator = numerator * attachment.denominator + denominator * attachment.numerator; - solution.denominator = denominator * attachment.denominator; - int gcd = gcd (solution.denominator, solution.numerator); - solution.numerator = solution.numerator / gcd; - solution.denominator = solution.denominator / gcd; - solution.offset = offset + attachment.offset; - return solution; + FormAttachment solution = new FormAttachment (); + solution.numerator = numerator * attachment.denominator + denominator * attachment.numerator; + solution.denominator = denominator * attachment.denominator; + int gcd = gcd (solution.denominator, solution.numerator); + solution.numerator = solution.numerator / gcd; + solution.denominator = solution.denominator / gcd; + solution.offset = offset + attachment.offset; + return solution; } FormAttachment plus (int value) { - return new FormAttachment (numerator, denominator, offset + value); + return new FormAttachment (numerator, denominator, offset + value); } int solveX (int value) { - if (denominator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); - return ((numerator * value) / denominator) + offset; + if (denominator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); + return ((numerator * value) / denominator) + offset; } int solveY (int value) { - if (numerator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); - return (value - offset) * denominator / numerator; + if (numerator == 0) SWT.error (SWT.ERROR_CANNOT_BE_ZERO); + return (value - offset) * denominator / numerator; } /** @@ -297,8 +297,8 @@ * @return a string representation of the FormAttachment */ public char[] toString () { - char[] string = control != null ? control.toString () : Format( "{}/{}", numerator, denominator ); - return Format("{{y = ({})x + {}}", string, ( offset >= 0 ? Format(")x + {}", offset ) : Format( ")x - {}", -offset))); + char[] string = control != null ? control.toString () : Format( "{}/{}", numerator, denominator ); + return Format("{{y = ({})x + {}}", string, ( offset >= 0 ? Format(")x + {}", offset ) : Format( ")x - {}", -offset))); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/FormData.d --- a/dwt/layout/FormData.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/FormData.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -28,10 +28,10 @@ * setLayoutData () method. To define attachments for the * FormData, set the fields directly, like this: *
    - * 		FormData data = new FormData();
    - * 		data.left = new FormAttachment(0,5);
    - * 		data.right = new FormAttachment(100,-5);
    - * 		button.setLayoutData(formData);
    + *      FormData data = new FormData();
    + *      data.left = new FormAttachment(0,5);
    + *      data.right = new FormAttachment(100,-5);
    + *      button.setLayoutData(formData);
      * 
    *

    *

    @@ -48,51 +48,51 @@ * @since 2.0 */ public final class FormData { - /** - * width specifies the preferred width in pixels. This value - * is the wHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see Control#computeSize(int, int, bool) - */ - public int width = SWT.DEFAULT; - /** - * height specifies the preferred height in pixels. This value - * is the hHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see Control#computeSize(int, int, bool) - */ - public int height = SWT.DEFAULT; - /** - * left specifies the attachment of the left side of - * the control. - */ - public FormAttachment left; - /** - * right specifies the attachment of the right side of - * the control. - */ - public FormAttachment right; - /** - * top specifies the attachment of the top of the control. - */ - public FormAttachment top; - /** - * bottom specifies the attachment of the bottom of the - * control. - */ - public FormAttachment bottom; + /** + * width specifies the preferred width in pixels. This value + * is the wHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see Control#computeSize(int, int, bool) + */ + public int width = SWT.DEFAULT; + /** + * height specifies the preferred height in pixels. This value + * is the hHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see Control#computeSize(int, int, bool) + */ + public int height = SWT.DEFAULT; + /** + * left specifies the attachment of the left side of + * the control. + */ + public FormAttachment left; + /** + * right specifies the attachment of the right side of + * the control. + */ + public FormAttachment right; + /** + * top specifies the attachment of the top of the control. + */ + public FormAttachment top; + /** + * bottom specifies the attachment of the bottom of the + * control. + */ + public FormAttachment bottom; - int cacheWidth = -1, cacheHeight = -1; - int defaultWhint, defaultHhint, defaultWidth = -1, defaultHeight = -1; - int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; - FormAttachment cacheLeft, cacheRight, cacheTop, cacheBottom; - bool isVisited, needed; + int cacheWidth = -1, cacheHeight = -1; + int defaultWhint, defaultHhint, defaultWidth = -1, defaultHeight = -1; + int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; + FormAttachment cacheLeft, cacheRight, cacheTop, cacheBottom; + bool isVisited, needed; /** * Constructs a new instance of FormData using @@ -110,131 +110,131 @@ * @param height a minimum height for the control */ public this (int width, int height) { - this.width = width; - this.height = height; + this.width = width; + this.height = height; } void computeSize (Control control, int wHint, int hHint, bool flushCache_) { - if (cacheWidth !is -1 && cacheHeight !is -1) return; - if (wHint is this.width && hHint is this.height) { - if (defaultWidth is -1 || defaultHeight is -1 || wHint !is defaultWhint || hHint !is defaultHhint) { - Point size = control.computeSize (wHint, hHint, flushCache_); - defaultWhint = wHint; - defaultHhint = hHint; - defaultWidth = size.x; - defaultHeight = size.y; - } - cacheWidth = defaultWidth; - cacheHeight = defaultHeight; - return; - } - if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { - Point size = control.computeSize (wHint, hHint, flushCache_); - currentWhint = wHint; - currentHhint = hHint; - currentWidth = size.x; - currentHeight = size.y; - } - cacheWidth = currentWidth; - cacheHeight = currentHeight; + if (cacheWidth !is -1 && cacheHeight !is -1) return; + if (wHint is this.width && hHint is this.height) { + if (defaultWidth is -1 || defaultHeight is -1 || wHint !is defaultWhint || hHint !is defaultHhint) { + Point size = control.computeSize (wHint, hHint, flushCache_); + defaultWhint = wHint; + defaultHhint = hHint; + defaultWidth = size.x; + defaultHeight = size.y; + } + cacheWidth = defaultWidth; + cacheHeight = defaultHeight; + return; + } + if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { + Point size = control.computeSize (wHint, hHint, flushCache_); + currentWhint = wHint; + currentHhint = hHint; + currentWidth = size.x; + currentHeight = size.y; + } + cacheWidth = currentWidth; + cacheHeight = currentHeight; } void flushCache () { - cacheWidth = cacheHeight = -1; - defaultHeight = defaultWidth = -1; - currentHeight = currentWidth = -1; + cacheWidth = cacheHeight = -1; + defaultHeight = defaultWidth = -1; + currentHeight = currentWidth = -1; } int getWidth (Control control, bool flushCache) { - needed = true; - computeSize (control, width, height, flushCache); - return cacheWidth; + needed = true; + computeSize (control, width, height, flushCache); + return cacheWidth; } int getHeight (Control control, bool flushCache) { - computeSize (control, width, height, flushCache); - return cacheHeight; + computeSize (control, width, height, flushCache); + return cacheHeight; } FormAttachment getBottomAttachment (Control control, int spacing, bool flushCache) { - if (cacheBottom !is null) return cacheBottom; - if (isVisited) return cacheBottom = new FormAttachment (0, getHeight (control, flushCache)); - if (bottom is null) { - if (top is null) return cacheBottom = new FormAttachment (0, getHeight (control, flushCache)); - return cacheBottom = getTopAttachment (control, spacing, flushCache).plus (getHeight (control, flushCache)); - } - Control bottomControl = bottom.control; - if (bottomControl !is null) { - if (bottomControl.isDisposed ()) { - bottom.control = bottomControl = null; - } else { - if (bottomControl.getParent () !is control.getParent ()) { - bottomControl = null; - } - } - } - if (bottomControl is null) return cacheBottom = bottom; - isVisited = true; - FormData bottomData = cast(FormData) bottomControl.getLayoutData (); - FormAttachment bottomAttachment = bottomData.getBottomAttachment (bottomControl, spacing, flushCache); - switch (bottom.alignment) { - case SWT.BOTTOM: - cacheBottom = bottomAttachment.plus (bottom.offset); - break; - case SWT.CENTER: { - FormAttachment topAttachment = bottomData.getTopAttachment (bottomControl, spacing, flushCache); - FormAttachment bottomHeight = bottomAttachment.minus (topAttachment); - cacheBottom = bottomAttachment.minus (bottomHeight.minus (getHeight (control, flushCache)).divide (2)); - break; - } - default: { - FormAttachment topAttachment = bottomData.getTopAttachment (bottomControl, spacing, flushCache); - cacheBottom = topAttachment.plus (bottom.offset - spacing); - break; - } - } - isVisited = false; - return cacheBottom; + if (cacheBottom !is null) return cacheBottom; + if (isVisited) return cacheBottom = new FormAttachment (0, getHeight (control, flushCache)); + if (bottom is null) { + if (top is null) return cacheBottom = new FormAttachment (0, getHeight (control, flushCache)); + return cacheBottom = getTopAttachment (control, spacing, flushCache).plus (getHeight (control, flushCache)); + } + Control bottomControl = bottom.control; + if (bottomControl !is null) { + if (bottomControl.isDisposed ()) { + bottom.control = bottomControl = null; + } else { + if (bottomControl.getParent () !is control.getParent ()) { + bottomControl = null; + } + } + } + if (bottomControl is null) return cacheBottom = bottom; + isVisited = true; + FormData bottomData = cast(FormData) bottomControl.getLayoutData (); + FormAttachment bottomAttachment = bottomData.getBottomAttachment (bottomControl, spacing, flushCache); + switch (bottom.alignment) { + case SWT.BOTTOM: + cacheBottom = bottomAttachment.plus (bottom.offset); + break; + case SWT.CENTER: { + FormAttachment topAttachment = bottomData.getTopAttachment (bottomControl, spacing, flushCache); + FormAttachment bottomHeight = bottomAttachment.minus (topAttachment); + cacheBottom = bottomAttachment.minus (bottomHeight.minus (getHeight (control, flushCache)).divide (2)); + break; + } + default: { + FormAttachment topAttachment = bottomData.getTopAttachment (bottomControl, spacing, flushCache); + cacheBottom = topAttachment.plus (bottom.offset - spacing); + break; + } + } + isVisited = false; + return cacheBottom; } FormAttachment getLeftAttachment (Control control, int spacing, bool flushCache) { - if (cacheLeft !is null) return cacheLeft; - if (isVisited) return cacheLeft = new FormAttachment (0, 0); - if (left is null) { - if (right is null) return cacheLeft = new FormAttachment (0, 0); - return cacheLeft = getRightAttachment (control, spacing, flushCache).minus (getWidth (control, flushCache)); - } - Control leftControl = left.control; - if (leftControl !is null) { - if (leftControl.isDisposed ()) { - left.control = leftControl = null; - } else { - if (leftControl.getParent () !is control.getParent ()) { - leftControl = null; - } - } - } - if (leftControl is null) return cacheLeft = left; - isVisited = true; - FormData leftData = cast(FormData) leftControl.getLayoutData (); - FormAttachment leftAttachment = leftData.getLeftAttachment (leftControl, spacing, flushCache); - switch (left.alignment) { - case SWT.LEFT: - cacheLeft = leftAttachment.plus (left.offset); - break; - case SWT.CENTER: { - FormAttachment rightAttachment = leftData.getRightAttachment (leftControl, spacing, flushCache); - FormAttachment leftWidth = rightAttachment.minus (leftAttachment); - cacheLeft = leftAttachment.plus (leftWidth.minus (getWidth (control, flushCache)).divide (2)); - break; - } - default: { - FormAttachment rightAttachment = leftData.getRightAttachment (leftControl, spacing, flushCache); - cacheLeft = rightAttachment.plus (left.offset + spacing); - } - } - isVisited = false; - return cacheLeft; + if (cacheLeft !is null) return cacheLeft; + if (isVisited) return cacheLeft = new FormAttachment (0, 0); + if (left is null) { + if (right is null) return cacheLeft = new FormAttachment (0, 0); + return cacheLeft = getRightAttachment (control, spacing, flushCache).minus (getWidth (control, flushCache)); + } + Control leftControl = left.control; + if (leftControl !is null) { + if (leftControl.isDisposed ()) { + left.control = leftControl = null; + } else { + if (leftControl.getParent () !is control.getParent ()) { + leftControl = null; + } + } + } + if (leftControl is null) return cacheLeft = left; + isVisited = true; + FormData leftData = cast(FormData) leftControl.getLayoutData (); + FormAttachment leftAttachment = leftData.getLeftAttachment (leftControl, spacing, flushCache); + switch (left.alignment) { + case SWT.LEFT: + cacheLeft = leftAttachment.plus (left.offset); + break; + case SWT.CENTER: { + FormAttachment rightAttachment = leftData.getRightAttachment (leftControl, spacing, flushCache); + FormAttachment leftWidth = rightAttachment.minus (leftAttachment); + cacheLeft = leftAttachment.plus (leftWidth.minus (getWidth (control, flushCache)).divide (2)); + break; + } + default: { + FormAttachment rightAttachment = leftData.getRightAttachment (leftControl, spacing, flushCache); + cacheLeft = rightAttachment.plus (left.offset + spacing); + } + } + isVisited = false; + return cacheLeft; } char[] getName () { @@ -245,85 +245,85 @@ } FormAttachment getRightAttachment (Control control, int spacing, bool flushCache) { - if (cacheRight !is null) return cacheRight; - if (isVisited) return cacheRight = new FormAttachment (0, getWidth (control, flushCache)); - if (right is null) { - if (left is null) return cacheRight = new FormAttachment (0, getWidth (control, flushCache)); - return cacheRight = getLeftAttachment (control, spacing, flushCache).plus (getWidth (control, flushCache)); - } - Control rightControl = right.control; - if (rightControl !is null) { - if (rightControl.isDisposed ()) { - right.control = rightControl = null; - } else { - if (rightControl.getParent () !is control.getParent ()) { - rightControl = null; - } - } - } - if (rightControl is null) return cacheRight = right; - isVisited = true; - FormData rightData = cast(FormData) rightControl.getLayoutData (); - FormAttachment rightAttachment = rightData.getRightAttachment (rightControl, spacing, flushCache); - switch (right.alignment) { - case SWT.RIGHT: - cacheRight = rightAttachment.plus (right.offset); - break; - case SWT.CENTER: { - FormAttachment leftAttachment = rightData.getLeftAttachment (rightControl, spacing, flushCache); - FormAttachment rightWidth = rightAttachment.minus (leftAttachment); - cacheRight = rightAttachment.minus (rightWidth.minus (getWidth (control, flushCache)).divide (2)); - break; - } - default: { - FormAttachment leftAttachment = rightData.getLeftAttachment (rightControl, spacing, flushCache); - cacheRight = leftAttachment.plus (right.offset - spacing); - break; - } - } - isVisited = false; - return cacheRight; + if (cacheRight !is null) return cacheRight; + if (isVisited) return cacheRight = new FormAttachment (0, getWidth (control, flushCache)); + if (right is null) { + if (left is null) return cacheRight = new FormAttachment (0, getWidth (control, flushCache)); + return cacheRight = getLeftAttachment (control, spacing, flushCache).plus (getWidth (control, flushCache)); + } + Control rightControl = right.control; + if (rightControl !is null) { + if (rightControl.isDisposed ()) { + right.control = rightControl = null; + } else { + if (rightControl.getParent () !is control.getParent ()) { + rightControl = null; + } + } + } + if (rightControl is null) return cacheRight = right; + isVisited = true; + FormData rightData = cast(FormData) rightControl.getLayoutData (); + FormAttachment rightAttachment = rightData.getRightAttachment (rightControl, spacing, flushCache); + switch (right.alignment) { + case SWT.RIGHT: + cacheRight = rightAttachment.plus (right.offset); + break; + case SWT.CENTER: { + FormAttachment leftAttachment = rightData.getLeftAttachment (rightControl, spacing, flushCache); + FormAttachment rightWidth = rightAttachment.minus (leftAttachment); + cacheRight = rightAttachment.minus (rightWidth.minus (getWidth (control, flushCache)).divide (2)); + break; + } + default: { + FormAttachment leftAttachment = rightData.getLeftAttachment (rightControl, spacing, flushCache); + cacheRight = leftAttachment.plus (right.offset - spacing); + break; + } + } + isVisited = false; + return cacheRight; } FormAttachment getTopAttachment (Control control, int spacing, bool flushCache) { - if (cacheTop !is null) return cacheTop; - if (isVisited) return cacheTop = new FormAttachment (0, 0); - if (top is null) { - if (bottom is null) return cacheTop = new FormAttachment (0, 0); - return cacheTop = getBottomAttachment (control, spacing, flushCache).minus (getHeight (control, flushCache)); - } - Control topControl = top.control; - if (topControl !is null) { - if (topControl.isDisposed ()) { - top.control = topControl = null; - } else { - if (topControl.getParent () !is control.getParent ()) { - topControl = null; - } - } - } - if (topControl is null) return cacheTop = top; - isVisited = true; - FormData topData = cast(FormData) topControl.getLayoutData (); - FormAttachment topAttachment = topData.getTopAttachment (topControl, spacing, flushCache); - switch (top.alignment) { - case SWT.TOP: - cacheTop = topAttachment.plus (top.offset); - break; - case SWT.CENTER: { - FormAttachment bottomAttachment = topData.getBottomAttachment (topControl, spacing, flushCache); - FormAttachment topHeight = bottomAttachment.minus (topAttachment); - cacheTop = topAttachment.plus (topHeight.minus (getHeight (control, flushCache)).divide (2)); - break; - } - default: { - FormAttachment bottomAttachment = topData.getBottomAttachment (topControl, spacing, flushCache); - cacheTop = bottomAttachment.plus (top.offset + spacing); - break; - } - } - isVisited = false; - return cacheTop; + if (cacheTop !is null) return cacheTop; + if (isVisited) return cacheTop = new FormAttachment (0, 0); + if (top is null) { + if (bottom is null) return cacheTop = new FormAttachment (0, 0); + return cacheTop = getBottomAttachment (control, spacing, flushCache).minus (getHeight (control, flushCache)); + } + Control topControl = top.control; + if (topControl !is null) { + if (topControl.isDisposed ()) { + top.control = topControl = null; + } else { + if (topControl.getParent () !is control.getParent ()) { + topControl = null; + } + } + } + if (topControl is null) return cacheTop = top; + isVisited = true; + FormData topData = cast(FormData) topControl.getLayoutData (); + FormAttachment topAttachment = topData.getTopAttachment (topControl, spacing, flushCache); + switch (top.alignment) { + case SWT.TOP: + cacheTop = topAttachment.plus (top.offset); + break; + case SWT.CENTER: { + FormAttachment bottomAttachment = topData.getBottomAttachment (topControl, spacing, flushCache); + FormAttachment topHeight = bottomAttachment.minus (topAttachment); + cacheTop = topAttachment.plus (topHeight.minus (getHeight (control, flushCache)).divide (2)); + break; + } + default: { + FormAttachment bottomAttachment = topData.getBottomAttachment (topControl, spacing, flushCache); + cacheTop = bottomAttachment.plus (top.offset + spacing); + break; + } + } + isVisited = false; + return cacheTop; } /** @@ -333,16 +333,16 @@ * @return a string representation of the FormData object */ public char[] toString () { - char[] string = getName()~" {"; - if (width !is SWT.DEFAULT) string ~= "width="~to!(char[])(width)~" "; - if (height !is SWT.DEFAULT) string ~= "height="~to!(char[])(height)~" "; - if (left !is null) string ~= "left="~to!(char[])(left)~" "; - if (right !is null) string ~= "right="~to!(char[])(right)~" "; - if (top !is null) string ~= "top="~to!(char[])(top)~" "; - if (bottom !is null) string ~= "bottom="~to!(char[])(bottom)~" "; - string = trim( string ); - string ~= "}"; - return string; + char[] string = getName()~" {"; + if (width !is SWT.DEFAULT) string ~= "width="~to!(char[])(width)~" "; + if (height !is SWT.DEFAULT) string ~= "height="~to!(char[])(height)~" "; + if (left !is null) string ~= "left="~to!(char[])(left)~" "; + if (right !is null) string ~= "right="~to!(char[])(right)~" "; + if (top !is null) string ~= "top="~to!(char[])(top)~" "; + if (bottom !is null) string ~= "bottom="~to!(char[])(bottom)~" "; + string = trim( string ); + string ~= "}"; + return string; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/FormLayout.d --- a/dwt/layout/FormLayout.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/FormLayout.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -33,12 +33,12 @@ * The following example code creates a FormLayout and then sets * it into a Shell: *

    - * 		Display display = new Display ();
    - *		Shell shell = new Shell(display);
    - *		FormLayout layout = new FormLayout();
    - *		layout.marginWidth = 3;
    - *		layout.marginHeight = 3;
    - *		shell.setLayout(layout);
    + *      Display display = new Display ();
    + *      Shell shell = new Shell(display);
    + *      FormLayout layout = new FormLayout();
    + *      layout.marginWidth = 3;
    + *      layout.marginHeight = 3;
    + *      shell.setLayout(layout);
      * 
    *

    *

    @@ -49,15 +49,15 @@ * edge of button1 and the top and right edges of the * composite: *

    - *		FormData data1 = new FormData();
    - *		data1.left = new FormAttachment(0, 0);
    - *		data1.top = new FormAttachment(0, 0);
    - *		button1.setLayoutData(data1);
    - *		FormData data2 = new FormData();
    - *		data2.left = new FormAttachment(button1);
    - *		data2.top = new FormAttachment(0, 0);
    - *		data2.right = new FormAttachment(100, 0);
    - *		button2.setLayoutData(data2);
    + *      FormData data1 = new FormData();
    + *      data1.left = new FormAttachment(0, 0);
    + *      data1.top = new FormAttachment(0, 0);
    + *      button1.setLayoutData(data1);
    + *      FormData data2 = new FormData();
    + *      data2.left = new FormAttachment(button1);
    + *      data2.top = new FormAttachment(0, 0);
    + *      data2.right = new FormAttachment(100, 0);
    + *      button2.setLayoutData(data2);
      * 
    *

    *

    @@ -74,10 +74,10 @@ * The following code positions button1 and button2 * but relies on default attachments: *

    - *		FormData data2 = new FormData();
    - *		data2.left = new FormAttachment(button1);
    - *		data2.right = new FormAttachment(100, 0);
    - *		button2.setLayoutData(data2);
    + *      FormData data2 = new FormData();
    + *      data2.left = new FormAttachment(button1);
    + *      data2.right = new FormAttachment(100, 0);
    + *      button2.setLayoutData(data2);
      * 
    *

    *

    @@ -96,72 +96,72 @@ */ public final class FormLayout : Layout { - /** - * marginWidth specifies the number of pixels of horizontal margin - * that will be placed along the left and right edges of the layout. - * - * The default value is 0. - */ - public int marginWidth = 0; + /** + * marginWidth specifies the number of pixels of horizontal margin + * that will be placed along the left and right edges of the layout. + * + * The default value is 0. + */ + public int marginWidth = 0; - /** - * marginHeight specifies the number of pixels of vertical margin - * that will be placed along the top and bottom edges of the layout. - * - * The default value is 0. - */ - public int marginHeight = 0; + /** + * marginHeight specifies the number of pixels of vertical margin + * that will be placed along the top and bottom edges of the layout. + * + * The default value is 0. + */ + public int marginHeight = 0; - /** - * marginLeft specifies the number of pixels of horizontal margin - * that will be placed along the left edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginLeft = 0; + /** + * marginLeft specifies the number of pixels of horizontal margin + * that will be placed along the left edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginLeft = 0; - /** - * marginTop specifies the number of pixels of vertical margin - * that will be placed along the top edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginTop = 0; + /** + * marginTop specifies the number of pixels of vertical margin + * that will be placed along the top edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginTop = 0; - /** - * marginRight specifies the number of pixels of horizontal margin - * that will be placed along the right edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginRight = 0; + /** + * marginRight specifies the number of pixels of horizontal margin + * that will be placed along the right edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginRight = 0; - /** - * marginBottom specifies the number of pixels of vertical margin - * that will be placed along the bottom edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginBottom = 0; + /** + * marginBottom specifies the number of pixels of vertical margin + * that will be placed along the bottom edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginBottom = 0; - /** - * spacing specifies the number of pixels between the edge of one control - * and the edge of its neighbouring control. - * - * The default value is 0. - * - * @since 3.0 - */ - public int spacing = 0; + /** + * spacing specifies the number of pixels between the edge of one control + * and the edge of its neighbouring control. + * + * The default value is 0. + * + * @since 3.0 + */ + public int spacing = 0; /** * Constructs a new instance of this class. @@ -176,17 +176,17 @@ * Given that the equations for top (T) and bottom (B) * of the control in terms of the height of the form (X) * are: - * T = AX + B - * B = CX + D + * T = AX + B + * B = CX + D * * The equation for the height of the control (H) * is bottom (B) minus top (T) or (H = B - T) or: * - * H = (CX + D) - (AX + B) + * H = (CX + D) - (AX + B) * * Solving for (X), the height of the form, we get: * - * X = (H + B - D) / (C - A) + * X = (H + B - D) / (C - A) * * When (A = C), (C - A = 0) and the equation has no * solution for X. This is a special case meaning that @@ -196,73 +196,73 @@ * * Case 1: A = C, A = 0, C = 0 * - * Let X = D, the distance from the top of the form - * to the bottom edge of the control. In this case, - * the control was attached to the top of the form - * and the form needs to be large enough to show the - * bottom edge of the control. + * Let X = D, the distance from the top of the form + * to the bottom edge of the control. In this case, + * the control was attached to the top of the form + * and the form needs to be large enough to show the + * bottom edge of the control. * * Case 2: A = C, A = 1, C = 1 * - * Let X = -B, the distance from the bottom of the - * form to the top edge of the control. In this case, - * the control was attached to the bottom of the form - * and the only way that the control would be visible - * is if the offset is negative. If the offset is - * positive, there is no possible height for the form - * that will show the control as it will always be - * below the bottom edge of the form. + * Let X = -B, the distance from the bottom of the + * form to the top edge of the control. In this case, + * the control was attached to the bottom of the form + * and the only way that the control would be visible + * is if the offset is negative. If the offset is + * positive, there is no possible height for the form + * that will show the control as it will always be + * below the bottom edge of the form. * * Case 3: A = C, A !is 0, C !is 0 and A !is 1, C !is 0 * - * Let X = D / (1 - C), the distance from the top of the - * form to the bottom edge of the control. In this case, - * since C is not 0 or 1, it must be a fraction, U / V. - * The offset D is the distance from CX to the bottom edge - * of the control. This represents a fraction of the form - * (1 - C)X. Since the height of a fraction of the form is - * known, the height of the entire form can be found by setting - * (1 - C)X = D. We solve this equation for X in terms of U - * and V, giving us X = (U * D) / (U - V). Similarly, if the - * offset D is negative, the control is positioned above CX. - * The offset -B is the distance from the top edge of the control - * to CX. We can find the height of the entire form by setting - * CX = -B. Solving in terms of U and V gives us X = (-B * V) / U. + * Let X = D / (1 - C), the distance from the top of the + * form to the bottom edge of the control. In this case, + * since C is not 0 or 1, it must be a fraction, U / V. + * The offset D is the distance from CX to the bottom edge + * of the control. This represents a fraction of the form + * (1 - C)X. Since the height of a fraction of the form is + * known, the height of the entire form can be found by setting + * (1 - C)X = D. We solve this equation for X in terms of U + * and V, giving us X = (U * D) / (U - V). Similarly, if the + * offset D is negative, the control is positioned above CX. + * The offset -B is the distance from the top edge of the control + * to CX. We can find the height of the entire form by setting + * CX = -B. Solving in terms of U and V gives us X = (-B * V) / U. */ int computeHeight (Control control, FormData data, bool flushCache) { - FormAttachment top = data.getTopAttachment (control, spacing, flushCache); - FormAttachment bottom = data.getBottomAttachment (control, spacing, flushCache); - FormAttachment height = bottom.minus (top); - if (height.numerator is 0) { - if (bottom.numerator is 0) return bottom.offset; - if (bottom.numerator is bottom.denominator) return -top.offset; - if (bottom.offset <= 0) { - return -top.offset * top.denominator / bottom.numerator; - } - int divider = bottom.denominator - bottom.numerator; - return bottom.denominator * bottom.offset / divider; - } - return height.solveY (data.getHeight (control, flushCache)); + FormAttachment top = data.getTopAttachment (control, spacing, flushCache); + FormAttachment bottom = data.getBottomAttachment (control, spacing, flushCache); + FormAttachment height = bottom.minus (top); + if (height.numerator is 0) { + if (bottom.numerator is 0) return bottom.offset; + if (bottom.numerator is bottom.denominator) return -top.offset; + if (bottom.offset <= 0) { + return -top.offset * top.denominator / bottom.numerator; + } + int divider = bottom.denominator - bottom.numerator; + return bottom.denominator * bottom.offset / divider; + } + return height.solveY (data.getHeight (control, flushCache)); } protected Point computeSize (Composite composite, int wHint, int hHint, bool flushCache) { - Point size = layout (composite, false, 0, 0, wHint, hHint, flushCache); - if (wHint !is SWT.DEFAULT) size.x = wHint; - if (hHint !is SWT.DEFAULT) size.y = hHint; - return size; + Point size = layout (composite, false, 0, 0, wHint, hHint, flushCache); + if (wHint !is SWT.DEFAULT) size.x = wHint; + if (hHint !is SWT.DEFAULT) size.y = hHint; + return size; } protected bool flushCache (Control control) { - Object data = control.getLayoutData (); - if (data !is null) (cast(FormData) data).flushCache (); - return true; + Object data = control.getLayoutData (); + if (data !is null) (cast(FormData) data).flushCache (); + return true; } char[] getName () { - char[] string = this.classinfo.name; - int index = locatePrior( string, '.'); - if (index is string.length ) return string; - return string[ index + 1 .. string.length ]; + char[] string = this.classinfo.name; + int index = locatePrior( string, '.'); + if (index is string.length ) return string; + return string[ index + 1 .. string.length ]; } /* @@ -270,105 +270,105 @@ * respect to the preferred height of the control. */ int computeWidth (Control control, FormData data, bool flushCache) { - FormAttachment left = data.getLeftAttachment (control, spacing, flushCache); - FormAttachment right = data.getRightAttachment (control, spacing, flushCache); - FormAttachment width = right.minus (left); - if (width.numerator is 0) { - if (right.numerator is 0) return right.offset; - if (right.numerator is right.denominator) return -left.offset; - if (right.offset <= 0) { - return -left.offset * left.denominator / left.numerator; - } - int divider = right.denominator - right.numerator; - return right.denominator * right.offset / divider; - } - return width.solveY (data.getWidth (control, flushCache)); + FormAttachment left = data.getLeftAttachment (control, spacing, flushCache); + FormAttachment right = data.getRightAttachment (control, spacing, flushCache); + FormAttachment width = right.minus (left); + if (width.numerator is 0) { + if (right.numerator is 0) return right.offset; + if (right.numerator is right.denominator) return -left.offset; + if (right.offset <= 0) { + return -left.offset * left.denominator / left.numerator; + } + int divider = right.denominator - right.numerator; + return right.denominator * right.offset / divider; + } + return width.solveY (data.getWidth (control, flushCache)); } protected void layout (Composite composite, bool flushCache) { - Rectangle rect = composite.getClientArea (); - int x = rect.x + marginLeft + marginWidth; - int y = rect.y + marginTop + marginHeight; - int width = Math.max (0, rect.width - marginLeft - 2 * marginWidth - marginRight); - int height = Math.max (0, rect.height - marginTop - 2 * marginHeight - marginBottom); - layout (composite, true, x, y, width, height, flushCache); + Rectangle rect = composite.getClientArea (); + int x = rect.x + marginLeft + marginWidth; + int y = rect.y + marginTop + marginHeight; + int width = Math.max (0, rect.width - marginLeft - 2 * marginWidth - marginRight); + int height = Math.max (0, rect.height - marginTop - 2 * marginHeight - marginBottom); + layout (composite, true, x, y, width, height, flushCache); } Point layout (Composite composite, bool move, int x, int y, int width, int height, bool flushCache) { - Control [] children = composite.getChildren (); - for (int i=0; iGridData object with certain * fields set. The first is to set the fields directly, like this: *

    - * 		GridData gridData = new GridData();
    - * 		gridData.horizontalAlignment = GridData.FILL;
    - * 		gridData.grabExcessHorizontalSpace = true;
    - * 		button1.setLayoutData(gridData);
    + *      GridData gridData = new GridData();
    + *      gridData.horizontalAlignment = GridData.FILL;
    + *      gridData.grabExcessHorizontalSpace = true;
    + *      button1.setLayoutData(gridData);
      * 
    * The second is to take advantage of convenience style bits defined * by GridData: @@ -48,351 +48,351 @@ * @see Control#setLayoutData */ public final class GridData { - /** - * verticalAlignment specifies how controls will be positioned - * vertically within a cell. - * - * The default value is CENTER. - * - * Possible values are:
      - *
    • SWT.BEGINNING (or SWT.TOP): Position the control at the top of the cell
    • - *
    • SWT.CENTER: Position the control in the vertical center of the cell
    • - *
    • SWT.END (or SWT.BOTTOM): Position the control at the bottom of the cell
    • - *
    • SWT.FILL: Resize the control to fill the cell vertically
    • - *
    - */ - public int verticalAlignment = CENTER; + /** + * verticalAlignment specifies how controls will be positioned + * vertically within a cell. + * + * The default value is CENTER. + * + * Possible values are:
      + *
    • SWT.BEGINNING (or SWT.TOP): Position the control at the top of the cell
    • + *
    • SWT.CENTER: Position the control in the vertical center of the cell
    • + *
    • SWT.END (or SWT.BOTTOM): Position the control at the bottom of the cell
    • + *
    • SWT.FILL: Resize the control to fill the cell vertically
    • + *
    + */ + public int verticalAlignment = CENTER; - /** - * horizontalAlignment specifies how controls will be positioned - * horizontally within a cell. - * - * The default value is BEGINNING. - * - * Possible values are:
      - *
    • SWT.BEGINNING (or SWT.LEFT): Position the control at the left of the cell
    • - *
    • SWT.CENTER: Position the control in the horizontal center of the cell
    • - *
    • SWT.END (or SWT.RIGHT): Position the control at the right of the cell
    • - *
    • SWT.FILL: Resize the control to fill the cell horizontally
    • - *
    - */ - public int horizontalAlignment = BEGINNING; + /** + * horizontalAlignment specifies how controls will be positioned + * horizontally within a cell. + * + * The default value is BEGINNING. + * + * Possible values are:
      + *
    • SWT.BEGINNING (or SWT.LEFT): Position the control at the left of the cell
    • + *
    • SWT.CENTER: Position the control in the horizontal center of the cell
    • + *
    • SWT.END (or SWT.RIGHT): Position the control at the right of the cell
    • + *
    • SWT.FILL: Resize the control to fill the cell horizontally
    • + *
    + */ + public int horizontalAlignment = BEGINNING; - /** - * widthHint specifies the preferred width in pixels. This value - * is the wHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see Control#computeSize(int, int, bool) - */ - public int widthHint = SWT.DEFAULT; + /** + * widthHint specifies the preferred width in pixels. This value + * is the wHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see Control#computeSize(int, int, bool) + */ + public int widthHint = SWT.DEFAULT; - /** - * heightHint specifies the preferred height in pixels. This value - * is the hHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see Control#computeSize(int, int, bool) - */ - public int heightHint = SWT.DEFAULT; + /** + * heightHint specifies the preferred height in pixels. This value + * is the hHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see Control#computeSize(int, int, bool) + */ + public int heightHint = SWT.DEFAULT; - /** - * horizontalIndent specifies the number of pixels of indentation - * that will be placed along the left side of the cell. - * - * The default value is 0. - */ - public int horizontalIndent = 0; + /** + * horizontalIndent specifies the number of pixels of indentation + * that will be placed along the left side of the cell. + * + * The default value is 0. + */ + public int horizontalIndent = 0; - /** - * verticalIndent specifies the number of pixels of indentation - * that will be placed along the top side of the cell. - * - * The default value is 0. - * - * @since 3.1 - */ - public int verticalIndent = 0; + /** + * verticalIndent specifies the number of pixels of indentation + * that will be placed along the top side of the cell. + * + * The default value is 0. + * + * @since 3.1 + */ + public int verticalIndent = 0; - /** - * horizontalSpan specifies the number of column cells that the control - * will take up. - * - * The default value is 1. - */ - public int horizontalSpan = 1; + /** + * horizontalSpan specifies the number of column cells that the control + * will take up. + * + * The default value is 1. + */ + public int horizontalSpan = 1; - /** - * verticalSpan specifies the number of row cells that the control - * will take up. - * - * The default value is 1. - */ - public int verticalSpan = 1; + /** + * verticalSpan specifies the number of row cells that the control + * will take up. + * + * The default value is 1. + */ + public int verticalSpan = 1; - /** - *

    grabExcessHorizontalSpace specifies whether the width of the cell - * changes depending on the size of the parent Composite. If - * grabExcessHorizontalSpace is true, the following rules - * apply to the width of the cell:

    - *
      - *
    • If extra horizontal space is available in the parent, the cell will - * grow to be wider than its preferred width. The new width - * will be "preferred width + delta" where delta is the extra - * horizontal space divided by the number of grabbing columns.
    • - *
    • If there is not enough horizontal space available in the parent, the - * cell will shrink until it reaches its minimum width as specified by - * GridData.minimumWidth. The new width will be the maximum of - * "minimumWidth" and "preferred width - delta", where delta is - * the amount of space missing divided by the number of grabbing columns.
    • - *
    • If the parent is packed, the cell will be its preferred width - * as specified by GridData.widthHint.
    • - *
    • If the control spans multiple columns and there are no other grabbing - * controls in any of the spanned columns, the last column in the span will - * grab the extra space. If there is at least one other grabbing control - * in the span, the grabbing will be spread over the columns already - * marked as grabExcessHorizontalSpace.
    • - *
    - * - *

    The default value is false.

    - * - * @see GridData#minimumWidth - * @see GridData#widthHint - */ - public bool grabExcessHorizontalSpace = false; + /** + *

    grabExcessHorizontalSpace specifies whether the width of the cell + * changes depending on the size of the parent Composite. If + * grabExcessHorizontalSpace is true, the following rules + * apply to the width of the cell:

    + *
      + *
    • If extra horizontal space is available in the parent, the cell will + * grow to be wider than its preferred width. The new width + * will be "preferred width + delta" where delta is the extra + * horizontal space divided by the number of grabbing columns.
    • + *
    • If there is not enough horizontal space available in the parent, the + * cell will shrink until it reaches its minimum width as specified by + * GridData.minimumWidth. The new width will be the maximum of + * "minimumWidth" and "preferred width - delta", where delta is + * the amount of space missing divided by the number of grabbing columns.
    • + *
    • If the parent is packed, the cell will be its preferred width + * as specified by GridData.widthHint.
    • + *
    • If the control spans multiple columns and there are no other grabbing + * controls in any of the spanned columns, the last column in the span will + * grab the extra space. If there is at least one other grabbing control + * in the span, the grabbing will be spread over the columns already + * marked as grabExcessHorizontalSpace.
    • + *
    + * + *

    The default value is false.

    + * + * @see GridData#minimumWidth + * @see GridData#widthHint + */ + public bool grabExcessHorizontalSpace = false; - /** - *

    grabExcessVerticalSpace specifies whether the height of the cell - * changes depending on the size of the parent Composite. If - * grabExcessVerticalSpace is true, the following rules - * apply to the height of the cell:

    - *
      - *
    • If extra vertical space is available in the parent, the cell will - * grow to be taller than its preferred height. The new height - * will be "preferred height + delta" where delta is the extra - * vertical space divided by the number of grabbing rows.
    • - *
    • If there is not enough vertical space available in the parent, the - * cell will shrink until it reaches its minimum height as specified by - * GridData.minimumHeight. The new height will be the maximum of - * "minimumHeight" and "preferred height - delta", where delta is - * the amount of space missing divided by the number of grabbing rows.
    • - *
    • If the parent is packed, the cell will be its preferred height - * as specified by GridData.heightHint.
    • - *
    • If the control spans multiple rows and there are no other grabbing - * controls in any of the spanned rows, the last row in the span will - * grab the extra space. If there is at least one other grabbing control - * in the span, the grabbing will be spread over the rows already - * marked as grabExcessVerticalSpace.
    • - *
    - * - *

    The default value is false.

    - * - * @see GridData#minimumHeight - * @see GridData#heightHint - */ - public bool grabExcessVerticalSpace = false; + /** + *

    grabExcessVerticalSpace specifies whether the height of the cell + * changes depending on the size of the parent Composite. If + * grabExcessVerticalSpace is true, the following rules + * apply to the height of the cell:

    + *
      + *
    • If extra vertical space is available in the parent, the cell will + * grow to be taller than its preferred height. The new height + * will be "preferred height + delta" where delta is the extra + * vertical space divided by the number of grabbing rows.
    • + *
    • If there is not enough vertical space available in the parent, the + * cell will shrink until it reaches its minimum height as specified by + * GridData.minimumHeight. The new height will be the maximum of + * "minimumHeight" and "preferred height - delta", where delta is + * the amount of space missing divided by the number of grabbing rows.
    • + *
    • If the parent is packed, the cell will be its preferred height + * as specified by GridData.heightHint.
    • + *
    • If the control spans multiple rows and there are no other grabbing + * controls in any of the spanned rows, the last row in the span will + * grab the extra space. If there is at least one other grabbing control + * in the span, the grabbing will be spread over the rows already + * marked as grabExcessVerticalSpace.
    • + *
    + * + *

    The default value is false.

    + * + * @see GridData#minimumHeight + * @see GridData#heightHint + */ + public bool grabExcessVerticalSpace = false; - /** - * minimumWidth specifies the minimum width in pixels. This value - * applies only if grabExcessHorizontalSpace is true. A value of - * SWT.DEFAULT means that the minimum width will be the result - * of Control.computeSize(int, int, bool) where wHint is - * determined by GridData.widthHint. - * - * The default value is 0. - * - * @since 3.1 - * @see Control#computeSize(int, int, bool) - * @see GridData#widthHint - */ - public int minimumWidth = 0; + /** + * minimumWidth specifies the minimum width in pixels. This value + * applies only if grabExcessHorizontalSpace is true. A value of + * SWT.DEFAULT means that the minimum width will be the result + * of Control.computeSize(int, int, bool) where wHint is + * determined by GridData.widthHint. + * + * The default value is 0. + * + * @since 3.1 + * @see Control#computeSize(int, int, bool) + * @see GridData#widthHint + */ + public int minimumWidth = 0; - /** - * minimumHeight specifies the minimum height in pixels. This value - * applies only if grabExcessVerticalSpace is true. A value of - * SWT.DEFAULT means that the minimum height will be the result - * of Control.computeSize(int, int, bool) where hHint is - * determined by GridData.heightHint. - * - * The default value is 0. - * - * @since 3.1 - * @see Control#computeSize(int, int, bool) - * @see GridData#heightHint - */ - public int minimumHeight = 0; + /** + * minimumHeight specifies the minimum height in pixels. This value + * applies only if grabExcessVerticalSpace is true. A value of + * SWT.DEFAULT means that the minimum height will be the result + * of Control.computeSize(int, int, bool) where hHint is + * determined by GridData.heightHint. + * + * The default value is 0. + * + * @since 3.1 + * @see Control#computeSize(int, int, bool) + * @see GridData#heightHint + */ + public int minimumHeight = 0; - /** - * exclude informs the layout to ignore this control when sizing - * and positioning controls. If this value is true, - * the size and position of the control will not be managed by the - * layout. If this value is false, the size and - * position of the control will be computed and assigned. - * - * The default value is false. - * - * @since 3.1 - */ - public bool exclude = false; + /** + * exclude informs the layout to ignore this control when sizing + * and positioning controls. If this value is true, + * the size and position of the control will not be managed by the + * layout. If this value is false, the size and + * position of the control will be computed and assigned. + * + * The default value is false. + * + * @since 3.1 + */ + public bool exclude = false; - /** - * Value for horizontalAlignment or verticalAlignment. - * Position the control at the top or left of the cell. - * Not recommended. Use SWT.BEGINNING, SWT.TOP or SWT.LEFT instead. - */ - public static const int BEGINNING = SWT.BEGINNING; + /** + * Value for horizontalAlignment or verticalAlignment. + * Position the control at the top or left of the cell. + * Not recommended. Use SWT.BEGINNING, SWT.TOP or SWT.LEFT instead. + */ + public static const int BEGINNING = SWT.BEGINNING; - /** - * Value for horizontalAlignment or verticalAlignment. - * Position the control in the vertical or horizontal center of the cell - * Not recommended. Use SWT.CENTER instead. - */ - public static const int CENTER = 2; + /** + * Value for horizontalAlignment or verticalAlignment. + * Position the control in the vertical or horizontal center of the cell + * Not recommended. Use SWT.CENTER instead. + */ + public static const int CENTER = 2; - /** - * Value for horizontalAlignment or verticalAlignment. - * Position the control at the bottom or right of the cell - * Not recommended. Use SWT.END, SWT.BOTTOM or SWT.RIGHT instead. - */ - public static const int END = 3; + /** + * Value for horizontalAlignment or verticalAlignment. + * Position the control at the bottom or right of the cell + * Not recommended. Use SWT.END, SWT.BOTTOM or SWT.RIGHT instead. + */ + public static const int END = 3; - /** - * Value for horizontalAlignment or verticalAlignment. - * Resize the control to fill the cell horizontally or vertically. - * Not recommended. Use SWT.FILL instead. - */ - public static const int FILL = SWT.FILL; + /** + * Value for horizontalAlignment or verticalAlignment. + * Resize the control to fill the cell horizontally or vertically. + * Not recommended. Use SWT.FILL instead. + */ + public static const int FILL = SWT.FILL; - /** - * Style bit for new GridData(int). - * Position the control at the top of the cell. - * Not recommended. Use - * new GridData(int, SWT.BEGINNING, bool, bool) - * instead. - */ - public static const int VERTICAL_ALIGN_BEGINNING = 1 << 1; + /** + * Style bit for new GridData(int). + * Position the control at the top of the cell. + * Not recommended. Use + * new GridData(int, SWT.BEGINNING, bool, bool) + * instead. + */ + public static const int VERTICAL_ALIGN_BEGINNING = 1 << 1; - /** - * Style bit for new GridData(int) to position the - * control in the vertical center of the cell. - * Not recommended. Use - * new GridData(int, SWT.CENTER, bool, bool) - * instead. - */ - public static const int VERTICAL_ALIGN_CENTER = 1 << 2; + /** + * Style bit for new GridData(int) to position the + * control in the vertical center of the cell. + * Not recommended. Use + * new GridData(int, SWT.CENTER, bool, bool) + * instead. + */ + public static const int VERTICAL_ALIGN_CENTER = 1 << 2; - /** - * Style bit for new GridData(int) to position the - * control at the bottom of the cell. - * Not recommended. Use - * new GridData(int, SWT.END, bool, bool) - * instead. - */ - public static const int VERTICAL_ALIGN_END = 1 << 3; + /** + * Style bit for new GridData(int) to position the + * control at the bottom of the cell. + * Not recommended. Use + * new GridData(int, SWT.END, bool, bool) + * instead. + */ + public static const int VERTICAL_ALIGN_END = 1 << 3; - /** - * Style bit for new GridData(int) to resize the - * control to fill the cell vertically. - * Not recommended. Use - * new GridData(int, SWT.FILL, bool, bool) - * instead - */ - public static const int VERTICAL_ALIGN_FILL = 1 << 4; + /** + * Style bit for new GridData(int) to resize the + * control to fill the cell vertically. + * Not recommended. Use + * new GridData(int, SWT.FILL, bool, bool) + * instead + */ + public static const int VERTICAL_ALIGN_FILL = 1 << 4; - /** - * Style bit for new GridData(int) to position the - * control at the left of the cell. - * Not recommended. Use - * new GridData(SWT.BEGINNING, int, bool, bool) - * instead. - */ - public static const int HORIZONTAL_ALIGN_BEGINNING = 1 << 5; + /** + * Style bit for new GridData(int) to position the + * control at the left of the cell. + * Not recommended. Use + * new GridData(SWT.BEGINNING, int, bool, bool) + * instead. + */ + public static const int HORIZONTAL_ALIGN_BEGINNING = 1 << 5; - /** - * Style bit for new GridData(int) to position the - * control in the horizontal center of the cell. - * Not recommended. Use - * new GridData(SWT.CENTER, int, bool, bool) - * instead. - */ - public static const int HORIZONTAL_ALIGN_CENTER = 1 << 6; + /** + * Style bit for new GridData(int) to position the + * control in the horizontal center of the cell. + * Not recommended. Use + * new GridData(SWT.CENTER, int, bool, bool) + * instead. + */ + public static const int HORIZONTAL_ALIGN_CENTER = 1 << 6; - /** - * Style bit for new GridData(int) to position the - * control at the right of the cell. - * Not recommended. Use - * new GridData(SWT.END, int, bool, bool) - * instead. - */ - public static const int HORIZONTAL_ALIGN_END = 1 << 7; + /** + * Style bit for new GridData(int) to position the + * control at the right of the cell. + * Not recommended. Use + * new GridData(SWT.END, int, bool, bool) + * instead. + */ + public static const int HORIZONTAL_ALIGN_END = 1 << 7; - /** - * Style bit for new GridData(int) to resize the - * control to fill the cell horizontally. - * Not recommended. Use - * new GridData(SWT.FILL, int, bool, bool) - * instead. - */ - public static const int HORIZONTAL_ALIGN_FILL = 1 << 8; + /** + * Style bit for new GridData(int) to resize the + * control to fill the cell horizontally. + * Not recommended. Use + * new GridData(SWT.FILL, int, bool, bool) + * instead. + */ + public static const int HORIZONTAL_ALIGN_FILL = 1 << 8; - /** - * Style bit for new GridData(int) to resize the - * control to fit the remaining horizontal space. - * Not recommended. Use - * new GridData(int, int, true, bool) - * instead. - */ - public static const int GRAB_HORIZONTAL = 1 << 9; + /** + * Style bit for new GridData(int) to resize the + * control to fit the remaining horizontal space. + * Not recommended. Use + * new GridData(int, int, true, bool) + * instead. + */ + public static const int GRAB_HORIZONTAL = 1 << 9; - /** - * Style bit for new GridData(int) to resize the - * control to fit the remaining vertical space. - * Not recommended. Use - * new GridData(int, int, bool, true) - * instead. - */ - public static const int GRAB_VERTICAL = 1 << 10; + /** + * Style bit for new GridData(int) to resize the + * control to fit the remaining vertical space. + * Not recommended. Use + * new GridData(int, int, bool, true) + * instead. + */ + public static const int GRAB_VERTICAL = 1 << 10; - /** - * Style bit for new GridData(int) to resize the - * control to fill the cell vertically and to fit the remaining - * vertical space. - * FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL - * Not recommended. Use - * new GridData(int, SWT.FILL, bool, true) - * instead. - */ - public static const int FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL; + /** + * Style bit for new GridData(int) to resize the + * control to fill the cell vertically and to fit the remaining + * vertical space. + * FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL + * Not recommended. Use + * new GridData(int, SWT.FILL, bool, true) + * instead. + */ + public static const int FILL_VERTICAL = VERTICAL_ALIGN_FILL | GRAB_VERTICAL; - /** - * Style bit for new GridData(int) to resize the - * control to fill the cell horizontally and to fit the remaining - * horizontal space. - * FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL - * Not recommended. Use - * new GridData(SWT.FILL, int, true, bool) - * instead. - */ - public static const int FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL; + /** + * Style bit for new GridData(int) to resize the + * control to fill the cell horizontally and to fit the remaining + * horizontal space. + * FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL + * Not recommended. Use + * new GridData(SWT.FILL, int, true, bool) + * instead. + */ + public static const int FILL_HORIZONTAL = HORIZONTAL_ALIGN_FILL | GRAB_HORIZONTAL; - /** - * Style bit for new GridData(int) to resize the - * control to fill the cell horizontally and vertically and - * to fit the remaining horizontal and vertical space. - * FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL - * Not recommended. Use - * new GridData(SWT.FILL, SWT.FILL, true, true) - * instead. - */ - public static const int FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL; + /** + * Style bit for new GridData(int) to resize the + * control to fill the cell horizontally and vertically and + * to fit the remaining horizontal and vertical space. + * FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL + * Not recommended. Use + * new GridData(SWT.FILL, SWT.FILL, true, true) + * instead. + */ + public static const int FILL_BOTH = FILL_VERTICAL | FILL_HORIZONTAL; - int cacheWidth = -1, cacheHeight = -1; - int defaultWhint, defaultHhint, defaultWidth = -1, defaultHeight = -1; - int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; + int cacheWidth = -1, cacheHeight = -1; + int defaultWhint, defaultHhint, defaultWidth = -1, defaultHeight = -1; + int currentWhint, currentHhint, currentWidth = -1, currentHeight = -1; /** * Constructs a new instance of GridData using @@ -408,16 +408,16 @@ * @param style the GridData style */ public this (int style) { - if ((style & VERTICAL_ALIGN_BEGINNING) !is 0) verticalAlignment = BEGINNING; - if ((style & VERTICAL_ALIGN_CENTER) !is 0) verticalAlignment = CENTER; - if ((style & VERTICAL_ALIGN_FILL) !is 0) verticalAlignment = FILL; - if ((style & VERTICAL_ALIGN_END) !is 0) verticalAlignment = END; - if ((style & HORIZONTAL_ALIGN_BEGINNING) !is 0) horizontalAlignment = BEGINNING; - if ((style & HORIZONTAL_ALIGN_CENTER) !is 0) horizontalAlignment = CENTER; - if ((style & HORIZONTAL_ALIGN_FILL) !is 0) horizontalAlignment = FILL; - if ((style & HORIZONTAL_ALIGN_END) !is 0) horizontalAlignment = END; - grabExcessHorizontalSpace = (style & GRAB_HORIZONTAL) !is 0; - grabExcessVerticalSpace = (style & GRAB_VERTICAL) !is 0; + if ((style & VERTICAL_ALIGN_BEGINNING) !is 0) verticalAlignment = BEGINNING; + if ((style & VERTICAL_ALIGN_CENTER) !is 0) verticalAlignment = CENTER; + if ((style & VERTICAL_ALIGN_FILL) !is 0) verticalAlignment = FILL; + if ((style & VERTICAL_ALIGN_END) !is 0) verticalAlignment = END; + if ((style & HORIZONTAL_ALIGN_BEGINNING) !is 0) horizontalAlignment = BEGINNING; + if ((style & HORIZONTAL_ALIGN_CENTER) !is 0) horizontalAlignment = CENTER; + if ((style & HORIZONTAL_ALIGN_FILL) !is 0) horizontalAlignment = FILL; + if ((style & HORIZONTAL_ALIGN_END) !is 0) horizontalAlignment = END; + grabExcessHorizontalSpace = (style & GRAB_HORIZONTAL) !is 0; + grabExcessVerticalSpace = (style & GRAB_VERTICAL) !is 0; } /** @@ -431,7 +431,7 @@ * @since 3.0 */ public this (int horizontalAlignment, int verticalAlignment, bool grabExcessHorizontalSpace, bool grabExcessVerticalSpace) { - this (horizontalAlignment, verticalAlignment, grabExcessHorizontalSpace, grabExcessVerticalSpace, 1, 1); + this (horizontalAlignment, verticalAlignment, grabExcessHorizontalSpace, grabExcessVerticalSpace, 1, 1); } /** @@ -448,11 +448,11 @@ */ public this (int horizontalAlignment, int verticalAlignment, bool grabExcessHorizontalSpace, bool grabExcessVerticalSpace, int horizontalSpan, int verticalSpan) { this.horizontalAlignment = horizontalAlignment; - this.verticalAlignment = verticalAlignment; - this.grabExcessHorizontalSpace = grabExcessHorizontalSpace; - this.grabExcessVerticalSpace = grabExcessVerticalSpace; - this.horizontalSpan = horizontalSpan; - this.verticalSpan = verticalSpan; + this.verticalAlignment = verticalAlignment; + this.grabExcessHorizontalSpace = grabExcessHorizontalSpace; + this.grabExcessVerticalSpace = grabExcessVerticalSpace; + this.horizontalSpan = horizontalSpan; + this.verticalSpan = verticalSpan; } /** @@ -466,39 +466,39 @@ * @since 3.0 */ public this (int width, int height) { - this.widthHint = width; - this.heightHint = height; + this.widthHint = width; + this.heightHint = height; } void computeSize (Control control, int wHint, int hHint, bool flushCache) { - if (cacheWidth !is -1 && cacheHeight !is -1) return; - if (wHint is this.widthHint && hHint is this.heightHint) { - if (defaultWidth is -1 || defaultHeight is -1 || wHint !is defaultWhint || hHint !is defaultHhint) { - Point size = control.computeSize (wHint, hHint, flushCache); - defaultWhint = wHint; - defaultHhint = hHint; - defaultWidth = size.x; - defaultHeight = size.y; - } - cacheWidth = defaultWidth; - cacheHeight = defaultHeight; - return; - } - if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { - Point size = control.computeSize (wHint, hHint, flushCache); - currentWhint = wHint; - currentHhint = hHint; - currentWidth = size.x; - currentHeight = size.y; - } - cacheWidth = currentWidth; - cacheHeight = currentHeight; + if (cacheWidth !is -1 && cacheHeight !is -1) return; + if (wHint is this.widthHint && hHint is this.heightHint) { + if (defaultWidth is -1 || defaultHeight is -1 || wHint !is defaultWhint || hHint !is defaultHhint) { + Point size = control.computeSize (wHint, hHint, flushCache); + defaultWhint = wHint; + defaultHhint = hHint; + defaultWidth = size.x; + defaultHeight = size.y; + } + cacheWidth = defaultWidth; + cacheHeight = defaultHeight; + return; + } + if (currentWidth is -1 || currentHeight is -1 || wHint !is currentWhint || hHint !is currentHhint) { + Point size = control.computeSize (wHint, hHint, flushCache); + currentWhint = wHint; + currentHhint = hHint; + currentWidth = size.x; + currentHeight = size.y; + } + cacheWidth = currentWidth; + cacheHeight = currentHeight; } void flushCache () { - cacheWidth = cacheHeight = -1; - defaultWidth = defaultHeight = -1; - currentWidth = currentHeight = -1; + cacheWidth = cacheHeight = -1; + defaultWidth = defaultHeight = -1; + currentWidth = currentHeight = -1; } char[] getName () { @@ -515,46 +515,46 @@ * @return a string representation of the GridData object */ public char[] toString () { - char[] hAlign = ""; - switch (horizontalAlignment) { - case SWT.FILL: hAlign = "SWT.FILL"; break; - case SWT.BEGINNING: hAlign = "SWT.BEGINNING"; break; - case SWT.LEFT: hAlign = "SWT.LEFT"; break; - case SWT.END: hAlign = "SWT.END"; break; - case END: hAlign = "GridData.END"; break; - case SWT.RIGHT: hAlign = "SWT.RIGHT"; break; - case SWT.CENTER: hAlign = "SWT.CENTER"; break; - case CENTER: hAlign = "GridData.CENTER"; break; - default: hAlign = "Undefined "~to!(char[])(horizontalAlignment); break; - } - char[] vAlign = ""; - switch (verticalAlignment) { - case SWT.FILL: vAlign = "SWT.FILL"; break; - case SWT.BEGINNING: vAlign = "SWT.BEGINNING"; break; - case SWT.TOP: vAlign = "SWT.TOP"; break; - case SWT.END: vAlign = "SWT.END"; break; - case END: vAlign = "GridData.END"; break; - case SWT.BOTTOM: vAlign = "SWT.BOTTOM"; break; - case SWT.CENTER: vAlign = "SWT.CENTER"; break; - case CENTER: vAlign = "GridData.CENTER"; break; - default: vAlign = "Undefined "~to!(char[])(verticalAlignment); break; - } - char[] string = getName()~" {"; - string ~= "horizontalAlignment="~to!(char[])(hAlign)~" "; - if (horizontalIndent !is 0) string ~= "horizontalIndent="~to!(char[])(horizontalIndent)~" "; - if (horizontalSpan !is 1) string ~= "horizontalSpan="~to!(char[])(horizontalSpan)~" "; - if (grabExcessHorizontalSpace) string ~= "grabExcessHorizontalSpace="~to!(char[])(grabExcessHorizontalSpace)~" "; - if (widthHint !is SWT.DEFAULT) string ~= "widthHint="~to!(char[])(widthHint)~" "; - if (minimumWidth !is 0) string ~= "minimumWidth="~to!(char[])(minimumWidth)~" "; - string ~= "verticalAlignment="~vAlign~" "; - if (verticalIndent !is 0) string ~= "verticalIndent="~to!(char[])(verticalIndent)~" "; - if (verticalSpan !is 1) string ~= "verticalSpan="~to!(char[])(verticalSpan)~" "; - if (grabExcessVerticalSpace) string ~= "grabExcessVerticalSpace="~to!(char[])(grabExcessVerticalSpace)~" "; - if (heightHint !is SWT.DEFAULT) string ~= "heightHint="~to!(char[])(heightHint)~" "; - if (minimumHeight !is 0) string ~= "minimumHeight="~to!(char[])(minimumHeight)~" "; - if (exclude) string ~= "exclude="~to!(char[])(exclude)~" "; - string = string.trim(); - string ~= "}"; - return string; + char[] hAlign = ""; + switch (horizontalAlignment) { + case SWT.FILL: hAlign = "SWT.FILL"; break; + case SWT.BEGINNING: hAlign = "SWT.BEGINNING"; break; + case SWT.LEFT: hAlign = "SWT.LEFT"; break; + case SWT.END: hAlign = "SWT.END"; break; + case END: hAlign = "GridData.END"; break; + case SWT.RIGHT: hAlign = "SWT.RIGHT"; break; + case SWT.CENTER: hAlign = "SWT.CENTER"; break; + case CENTER: hAlign = "GridData.CENTER"; break; + default: hAlign = "Undefined "~to!(char[])(horizontalAlignment); break; + } + char[] vAlign = ""; + switch (verticalAlignment) { + case SWT.FILL: vAlign = "SWT.FILL"; break; + case SWT.BEGINNING: vAlign = "SWT.BEGINNING"; break; + case SWT.TOP: vAlign = "SWT.TOP"; break; + case SWT.END: vAlign = "SWT.END"; break; + case END: vAlign = "GridData.END"; break; + case SWT.BOTTOM: vAlign = "SWT.BOTTOM"; break; + case SWT.CENTER: vAlign = "SWT.CENTER"; break; + case CENTER: vAlign = "GridData.CENTER"; break; + default: vAlign = "Undefined "~to!(char[])(verticalAlignment); break; + } + char[] string = getName()~" {"; + string ~= "horizontalAlignment="~to!(char[])(hAlign)~" "; + if (horizontalIndent !is 0) string ~= "horizontalIndent="~to!(char[])(horizontalIndent)~" "; + if (horizontalSpan !is 1) string ~= "horizontalSpan="~to!(char[])(horizontalSpan)~" "; + if (grabExcessHorizontalSpace) string ~= "grabExcessHorizontalSpace="~to!(char[])(grabExcessHorizontalSpace)~" "; + if (widthHint !is SWT.DEFAULT) string ~= "widthHint="~to!(char[])(widthHint)~" "; + if (minimumWidth !is 0) string ~= "minimumWidth="~to!(char[])(minimumWidth)~" "; + string ~= "verticalAlignment="~vAlign~" "; + if (verticalIndent !is 0) string ~= "verticalIndent="~to!(char[])(verticalIndent)~" "; + if (verticalSpan !is 1) string ~= "verticalSpan="~to!(char[])(verticalSpan)~" "; + if (grabExcessVerticalSpace) string ~= "grabExcessVerticalSpace="~to!(char[])(grabExcessVerticalSpace)~" "; + if (heightHint !is SWT.DEFAULT) string ~= "heightHint="~to!(char[])(heightHint)~" "; + if (minimumHeight !is 0) string ~= "minimumHeight="~to!(char[])(minimumHeight)~" "; + if (exclude) string ~= "exclude="~to!(char[])(exclude)~" "; + string = string.trim(); + string ~= "}"; + return string; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/GridLayout.d --- a/dwt/layout/GridLayout.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/GridLayout.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -40,11 +40,11 @@ * The following code creates a shell managed by a GridLayout * with 3 columns: *
    - * 		Display display = new Display();
    - * 		Shell shell = new Shell(display);
    - * 		GridLayout gridLayout = new GridLayout();
    - * 		gridLayout.numColumns = 3;
    - * 		shell.setLayout(gridLayout);
    + *      Display display = new Display();
    + *      Shell shell = new Shell(display);
    + *      GridLayout gridLayout = new GridLayout();
    + *      gridLayout.numColumns = 3;
    + *      shell.setLayout(gridLayout);
      * 
    * The numColumns field is the most important field in a * GridLayout. Widgets are laid out in columns from left @@ -56,95 +56,95 @@ */ public final class GridLayout : Layout { - /** - * numColumns specifies the number of cell columns in the layout. - * If numColumns has a value less than 1, the layout will not - * set the size and position of any controls. - * - * The default value is 1. - */ - public int numColumns = 1; + /** + * numColumns specifies the number of cell columns in the layout. + * If numColumns has a value less than 1, the layout will not + * set the size and position of any controls. + * + * The default value is 1. + */ + public int numColumns = 1; - /** - * makeColumnsEqualWidth specifies whether all columns in the layout - * will be forced to have the same width. - * - * The default value is false. - */ - public bool makeColumnsEqualWidth = false; + /** + * makeColumnsEqualWidth specifies whether all columns in the layout + * will be forced to have the same width. + * + * The default value is false. + */ + public bool makeColumnsEqualWidth = false; - /** - * marginWidth specifies the number of pixels of horizontal margin - * that will be placed along the left and right edges of the layout. - * - * The default value is 5. - */ - public int marginWidth = 5; + /** + * marginWidth specifies the number of pixels of horizontal margin + * that will be placed along the left and right edges of the layout. + * + * The default value is 5. + */ + public int marginWidth = 5; - /** - * marginHeight specifies the number of pixels of vertical margin - * that will be placed along the top and bottom edges of the layout. - * - * The default value is 5. - */ - public int marginHeight = 5; + /** + * marginHeight specifies the number of pixels of vertical margin + * that will be placed along the top and bottom edges of the layout. + * + * The default value is 5. + */ + public int marginHeight = 5; - /** - * marginLeft specifies the number of pixels of horizontal margin - * that will be placed along the left edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginLeft = 0; + /** + * marginLeft specifies the number of pixels of horizontal margin + * that will be placed along the left edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginLeft = 0; - /** - * marginTop specifies the number of pixels of vertical margin - * that will be placed along the top edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginTop = 0; + /** + * marginTop specifies the number of pixels of vertical margin + * that will be placed along the top edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginTop = 0; - /** - * marginRight specifies the number of pixels of horizontal margin - * that will be placed along the right edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginRight = 0; + /** + * marginRight specifies the number of pixels of horizontal margin + * that will be placed along the right edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginRight = 0; - /** - * marginBottom specifies the number of pixels of vertical margin - * that will be placed along the bottom edge of the layout. - * - * The default value is 0. - * - * @since 3.1 - */ - public int marginBottom = 0; + /** + * marginBottom specifies the number of pixels of vertical margin + * that will be placed along the bottom edge of the layout. + * + * The default value is 0. + * + * @since 3.1 + */ + public int marginBottom = 0; - /** - * horizontalSpacing specifies the number of pixels between the right - * edge of one cell and the left edge of its neighbouring cell to - * the right. - * - * The default value is 5. - */ - public int horizontalSpacing = 5; + /** + * horizontalSpacing specifies the number of pixels between the right + * edge of one cell and the left edge of its neighbouring cell to + * the right. + * + * The default value is 5. + */ + public int horizontalSpacing = 5; - /** - * verticalSpacing specifies the number of pixels between the bottom - * edge of one cell and the top edge of its neighbouring cell underneath. - * - * The default value is 5. - */ - public int verticalSpacing = 5; + /** + * verticalSpacing specifies the number of pixels between the bottom + * edge of one cell and the top edge of its neighbouring cell underneath. + * + * The default value is 5. + */ + public int verticalSpacing = 5; /** * Constructs a new instance of this class. @@ -164,565 +164,565 @@ * @since 2.0 */ public this (int numColumns, bool makeColumnsEqualWidth) { - this.numColumns = numColumns; - this.makeColumnsEqualWidth = makeColumnsEqualWidth; + this.numColumns = numColumns; + this.makeColumnsEqualWidth = makeColumnsEqualWidth; } protected Point computeSize (Composite composite, int wHint, int hHint, bool flushCache_) { - Point size = layout (composite, false, 0, 0, wHint, hHint, flushCache_); - if (wHint !is SWT.DEFAULT) size.x = wHint; - if (hHint !is SWT.DEFAULT) size.y = hHint; - return size; + Point size = layout (composite, false, 0, 0, wHint, hHint, flushCache_); + if (wHint !is SWT.DEFAULT) size.x = wHint; + if (hHint !is SWT.DEFAULT) size.y = hHint; + return size; } protected bool flushCache (Control control) { - Object data = control.getLayoutData (); - if (data !is null) (cast(GridData) data).flushCache (); - return true; + Object data = control.getLayoutData (); + if (data !is null) (cast(GridData) data).flushCache (); + return true; } GridData getData (Control [][] grid, int row, int column, int rowCount, int columnCount, bool first) { - Control control = grid [row] [column]; - if (control !is null) { - GridData data = cast(GridData) control.getLayoutData (); - int hSpan = Math.max (1, Math.min (data.horizontalSpan, columnCount)); - int vSpan = Math.max (1, data.verticalSpan); - int i = first ? row + vSpan - 1 : row - vSpan + 1; - int j = first ? column + hSpan - 1 : column - hSpan + 1; - if (0 <= i && i < rowCount) { - if (0 <= j && j < columnCount) { - if (control is grid [i][j]) return data; - } - } - } - return null; + Control control = grid [row] [column]; + if (control !is null) { + GridData data = cast(GridData) control.getLayoutData (); + int hSpan = Math.max (1, Math.min (data.horizontalSpan, columnCount)); + int vSpan = Math.max (1, data.verticalSpan); + int i = first ? row + vSpan - 1 : row - vSpan + 1; + int j = first ? column + hSpan - 1 : column - hSpan + 1; + if (0 <= i && i < rowCount) { + if (0 <= j && j < columnCount) { + if (control is grid [i][j]) return data; + } + } + } + return null; } protected void layout (Composite composite, bool flushCache_) { - Rectangle rect = composite.getClientArea (); - layout (composite, true, rect.x, rect.y, rect.width, rect.height, flushCache_); + Rectangle rect = composite.getClientArea (); + layout (composite, true, rect.x, rect.y, rect.width, rect.height, flushCache_); } Point layout (Composite composite, bool move, int x, int y, int width, int height, bool flushCache_) { - if (numColumns < 1) { - return new Point (marginLeft + marginWidth * 2 + marginRight, marginTop + marginHeight * 2 + marginBottom); - } - Control [] children = composite.getChildren (); - int count = 0; - for (int i=0; i 0) { - if (data.cacheWidth < data.minimumWidth) { - int trim = 0; - //TEMPORARY CODE - if ( auto sa = cast(Scrollable)child ) { - Rectangle rect = sa.computeTrim (0, 0, 0, 0); - trim = rect.width; - } else { - trim = child.getBorderWidth () * 2; - } - data.cacheWidth = data.cacheHeight = SWT.DEFAULT; - data.computeSize (child, Math.max (0, data.minimumWidth - trim), data.heightHint, false); - } - } - if (data.grabExcessVerticalSpace && data.minimumHeight > 0) { - data.cacheHeight = Math.max (data.cacheHeight, data.minimumHeight); - } - } + if (numColumns < 1) { + return new Point (marginLeft + marginWidth * 2 + marginRight, marginTop + marginHeight * 2 + marginBottom); + } + Control [] children = composite.getChildren (); + int count = 0; + for (int i=0; i 0) { + if (data.cacheWidth < data.minimumWidth) { + int trim = 0; + //TEMPORARY CODE + if ( auto sa = cast(Scrollable)child ) { + Rectangle rect = sa.computeTrim (0, 0, 0, 0); + trim = rect.width; + } else { + trim = child.getBorderWidth () * 2; + } + data.cacheWidth = data.cacheHeight = SWT.DEFAULT; + data.computeSize (child, Math.max (0, data.minimumWidth - trim), data.heightHint, false); + } + } + if (data.grabExcessVerticalSpace && data.minimumHeight > 0) { + data.cacheHeight = Math.max (data.cacheHeight, data.minimumHeight); + } + } - /* Build the grid */ - int row = 0, column = 0, rowCount = 0, columnCount = numColumns; - Control [][] grid = new Control [][]( 4, columnCount ); - for (int i=0; i= grid.length) { - Control [][] newGrid = new Control[][]( lastRow + 4, columnCount ); - SimpleType!(Control[]).arraycopy (grid, 0, newGrid, 0, grid.length); - grid = newGrid; - } - if (grid [row] is null) { - grid [row] = new Control [columnCount]; - } - while (column < columnCount && grid [row] [column] !is null) { - column++; - } - int endCount = column + hSpan; - if (endCount <= columnCount) { - int index = column; - while (index < endCount && grid [row] [index] is null) { - index++; - } - if (index is endCount) break; - column = index; - } - if (column + hSpan >= columnCount) { - column = 0; - row++; - } - } - for (int j=0; j= grid.length) { + Control [][] newGrid = new Control[][]( lastRow + 4, columnCount ); + SimpleType!(Control[]).arraycopy (grid, 0, newGrid, 0, grid.length); + grid = newGrid; + } + if (grid [row] is null) { + grid [row] = new Control [columnCount]; + } + while (column < columnCount && grid [row] [column] !is null) { + column++; + } + int endCount = column + hSpan; + if (endCount <= columnCount) { + int index = column; + while (index < endCount && grid [row] [index] is null) { + index++; + } + if (index is endCount) break; + column = index; + } + if (column + hSpan >= columnCount) { + column = 0; + row++; + } + } + for (int j=0; j 1) { - int spanWidth = 0, spanMinWidth = 0, spanExpandCount = 0; - for (int k=0; k 0) { - if (makeColumnsEqualWidth) { - int equalWidth = (w + spanWidth) / hSpan; - int remainder = (w + spanWidth) % hSpan, last = -1; - for (int k = 0; k < hSpan; k++) { - widths [last=j-k] = Math.max (equalWidth, widths [j-k]); - } - if (last > -1) widths [last] += remainder; - } else { - if (spanExpandCount is 0) { - widths [j] += w; - } else { - int delta = w / spanExpandCount; - int remainder = w % spanExpandCount, last = -1; - for (int k = 0; k < hSpan; k++) { - if (expandColumn [j-k]) { - widths [last=j-k] += delta; - } - } - if (last > -1) widths [last] += remainder; - } - } - } - if (!data.grabExcessHorizontalSpace || data.minimumWidth !is 0) { - w = !data.grabExcessHorizontalSpace || data.minimumWidth is SWT.DEFAULT ? data.cacheWidth : data.minimumWidth; - w += data.horizontalIndent - spanMinWidth - (hSpan - 1) * horizontalSpacing; - if (w > 0) { - if (spanExpandCount is 0) { - minWidths [j] += w; - } else { - int delta = w / spanExpandCount; - int remainder = w % spanExpandCount, last = -1; - for (int k = 0; k < hSpan; k++) { - if (expandColumn [j-k]) { - minWidths [last=j-k] += delta; - } - } - if (last > -1) minWidths [last] += remainder; - } - } - } - } - } - } - } - if (makeColumnsEqualWidth) { - int minColumnWidth = 0; - int columnWidth = 0; - for (int i=0; i 0; - widths [i] = columnWidth; - } - } else { - if (width !is SWT.DEFAULT && expandCount > 0) { - int totalWidth = 0; - for (int i=0; i minWidths [j]) { - widths [last = j] = widths [j] + delta; - } else { - widths [j] = minWidths [j]; - expandColumn [j] = false; - c--; - } - } - } - if (last > -1) widths [last] += remainder; + /* Column widths */ + int availableWidth = width - horizontalSpacing * (columnCount - 1) - (marginLeft + marginWidth * 2 + marginRight); + int expandCount = 0; + int [] widths = new int [columnCount]; + int [] minWidths = new int [columnCount]; + bool [] expandColumn = new bool [columnCount]; + for (int j=0; j 1) { + int spanWidth = 0, spanMinWidth = 0, spanExpandCount = 0; + for (int k=0; k 0) { + if (makeColumnsEqualWidth) { + int equalWidth = (w + spanWidth) / hSpan; + int remainder = (w + spanWidth) % hSpan, last = -1; + for (int k = 0; k < hSpan; k++) { + widths [last=j-k] = Math.max (equalWidth, widths [j-k]); + } + if (last > -1) widths [last] += remainder; + } else { + if (spanExpandCount is 0) { + widths [j] += w; + } else { + int delta = w / spanExpandCount; + int remainder = w % spanExpandCount, last = -1; + for (int k = 0; k < hSpan; k++) { + if (expandColumn [j-k]) { + widths [last=j-k] += delta; + } + } + if (last > -1) widths [last] += remainder; + } + } + } + if (!data.grabExcessHorizontalSpace || data.minimumWidth !is 0) { + w = !data.grabExcessHorizontalSpace || data.minimumWidth is SWT.DEFAULT ? data.cacheWidth : data.minimumWidth; + w += data.horizontalIndent - spanMinWidth - (hSpan - 1) * horizontalSpacing; + if (w > 0) { + if (spanExpandCount is 0) { + minWidths [j] += w; + } else { + int delta = w / spanExpandCount; + int remainder = w % spanExpandCount, last = -1; + for (int k = 0; k < hSpan; k++) { + if (expandColumn [j-k]) { + minWidths [last=j-k] += delta; + } + } + if (last > -1) minWidths [last] += remainder; + } + } + } + } + } + } + } + if (makeColumnsEqualWidth) { + int minColumnWidth = 0; + int columnWidth = 0; + for (int i=0; i 0; + widths [i] = columnWidth; + } + } else { + if (width !is SWT.DEFAULT && expandCount > 0) { + int totalWidth = 0; + for (int i=0; i minWidths [j]) { + widths [last = j] = widths [j] + delta; + } else { + widths [j] = minWidths [j]; + expandColumn [j] = false; + c--; + } + } + } + if (last > -1) widths [last] += remainder; - for (int j=0; j 1) { - if (!data.grabExcessHorizontalSpace || data.minimumWidth !is 0) { - int spanWidth = 0, spanExpandCount = 0; - for (int k=0; k 0) { - if (spanExpandCount is 0) { - widths [j] += w; - } else { - int delta2 = w / spanExpandCount; - int remainder2 = w % spanExpandCount, last2 = -1; - for (int k = 0; k < hSpan; k++) { - if (expandColumn [j-k]) { - widths [last2=j-k] += delta2; - } - } - if (last2 > -1) widths [last2] += remainder2; - } - } - } - } - } - } - } - if (c is 0) break; - totalWidth = 0; - for (int i=0; i 1) { + if (!data.grabExcessHorizontalSpace || data.minimumWidth !is 0) { + int spanWidth = 0, spanExpandCount = 0; + for (int k=0; k 0) { + if (spanExpandCount is 0) { + widths [j] += w; + } else { + int delta2 = w / spanExpandCount; + int remainder2 = w % spanExpandCount, last2 = -1; + for (int k = 0; k < hSpan; k++) { + if (expandColumn [j-k]) { + widths [last2=j-k] += delta2; + } + } + if (last2 > -1) widths [last2] += remainder2; + } + } + } + } + } + } + } + if (c is 0) break; + totalWidth = 0; + for (int i=0; i currentWidth)) { - int trim = 0; - if ( auto sa = cast(Scrollable)child ) { - Rectangle rect = sa.computeTrim (0, 0, 0, 0); - trim = rect.width; - } else { - trim = child.getBorderWidth () * 2; - } - data.cacheWidth = data.cacheHeight = SWT.DEFAULT; - data.computeSize (child, Math.max (0, currentWidth - trim), data.heightHint, false); - if (data.grabExcessVerticalSpace && data.minimumHeight > 0) { - data.cacheHeight = Math.max (data.cacheHeight, data.minimumHeight); - } - if (flush is null) flush = new GridData [count]; - flush [flushLength++] = data; - } - } - } - } - } - } + /* Wrapping */ + GridData [] flush = null; + int flushLength = 0; + if (width !is SWT.DEFAULT) { + for (int j=0; j currentWidth)) { + int trim = 0; + if ( auto sa = cast(Scrollable)child ) { + Rectangle rect = sa.computeTrim (0, 0, 0, 0); + trim = rect.width; + } else { + trim = child.getBorderWidth () * 2; + } + data.cacheWidth = data.cacheHeight = SWT.DEFAULT; + data.computeSize (child, Math.max (0, currentWidth - trim), data.heightHint, false); + if (data.grabExcessVerticalSpace && data.minimumHeight > 0) { + data.cacheHeight = Math.max (data.cacheHeight, data.minimumHeight); + } + if (flush is null) flush = new GridData [count]; + flush [flushLength++] = data; + } + } + } + } + } + } - /* Row heights */ - int availableHeight = height - verticalSpacing * (rowCount - 1) - (marginTop + marginHeight * 2 + marginBottom); - expandCount = 0; - int [] heights = new int [rowCount]; - int [] minHeights = new int [rowCount]; - bool [] expandRow = new bool [rowCount]; - for (int i=0; i 1) { - int spanHeight = 0, spanMinHeight = 0, spanExpandCount = 0; - for (int k=0; k 0) { - if (spanExpandCount is 0) { - heights [i] += h; - } else { - int delta = h / spanExpandCount; - int remainder = h % spanExpandCount, last = -1; - for (int k = 0; k < vSpan; k++) { - if (expandRow [i-k]) { - heights [last=i-k] += delta; - } - } - if (last > -1) heights [last] += remainder; - } - } - if (!data.grabExcessVerticalSpace || data.minimumHeight !is 0) { - h = !data.grabExcessVerticalSpace || data.minimumHeight is SWT.DEFAULT ? data.cacheHeight : data.minimumHeight; - h += data.verticalIndent - spanMinHeight - (vSpan - 1) * verticalSpacing; - if (h > 0) { - if (spanExpandCount is 0) { - minHeights [i] += h; - } else { - int delta = h / spanExpandCount; - int remainder = h % spanExpandCount, last = -1; - for (int k = 0; k < vSpan; k++) { - if (expandRow [i-k]) { - minHeights [last=i-k] += delta; - } - } - if (last > -1) minHeights [last] += remainder; - } - } - } - } - } - } - } - if (height !is SWT.DEFAULT && expandCount > 0) { - int totalHeight = 0; - for (int i=0; i minHeights [i]) { - heights [last = i] = heights [i] + delta; - } else { - heights [i] = minHeights [i]; - expandRow [i] = false; - c--; - } - } - } - if (last > -1) heights [last] += remainder; + /* Row heights */ + int availableHeight = height - verticalSpacing * (rowCount - 1) - (marginTop + marginHeight * 2 + marginBottom); + expandCount = 0; + int [] heights = new int [rowCount]; + int [] minHeights = new int [rowCount]; + bool [] expandRow = new bool [rowCount]; + for (int i=0; i 1) { + int spanHeight = 0, spanMinHeight = 0, spanExpandCount = 0; + for (int k=0; k 0) { + if (spanExpandCount is 0) { + heights [i] += h; + } else { + int delta = h / spanExpandCount; + int remainder = h % spanExpandCount, last = -1; + for (int k = 0; k < vSpan; k++) { + if (expandRow [i-k]) { + heights [last=i-k] += delta; + } + } + if (last > -1) heights [last] += remainder; + } + } + if (!data.grabExcessVerticalSpace || data.minimumHeight !is 0) { + h = !data.grabExcessVerticalSpace || data.minimumHeight is SWT.DEFAULT ? data.cacheHeight : data.minimumHeight; + h += data.verticalIndent - spanMinHeight - (vSpan - 1) * verticalSpacing; + if (h > 0) { + if (spanExpandCount is 0) { + minHeights [i] += h; + } else { + int delta = h / spanExpandCount; + int remainder = h % spanExpandCount, last = -1; + for (int k = 0; k < vSpan; k++) { + if (expandRow [i-k]) { + minHeights [last=i-k] += delta; + } + } + if (last > -1) minHeights [last] += remainder; + } + } + } + } + } + } + } + if (height !is SWT.DEFAULT && expandCount > 0) { + int totalHeight = 0; + for (int i=0; i minHeights [i]) { + heights [last = i] = heights [i] + delta; + } else { + heights [i] = minHeights [i]; + expandRow [i] = false; + c--; + } + } + } + if (last > -1) heights [last] += remainder; - for (int i=0; i 1) { - if (!data.grabExcessVerticalSpace || data.minimumHeight !is 0) { - int spanHeight = 0, spanExpandCount = 0; - for (int k=0; k 0) { - if (spanExpandCount is 0) { - heights [i] += h; - } else { - int delta2 = h / spanExpandCount; - int remainder2 = h % spanExpandCount, last2 = -1; - for (int k = 0; k < vSpan; k++) { - if (expandRow [i-k]) { - heights [last2=i-k] += delta2; - } - } - if (last2 > -1) heights [last2] += remainder2; - } - } - } - } - } - } - } - if (c is 0) break; - totalHeight = 0; - for (int i=0; i 1) { + if (!data.grabExcessVerticalSpace || data.minimumHeight !is 0) { + int spanHeight = 0, spanExpandCount = 0; + for (int k=0; k 0) { + if (spanExpandCount is 0) { + heights [i] += h; + } else { + int delta2 = h / spanExpandCount; + int remainder2 = h % spanExpandCount, last2 = -1; + for (int k = 0; k < vSpan; k++) { + if (expandRow [i-k]) { + heights [last2=i-k] += delta2; + } + } + if (last2 > -1) heights [last2] += remainder2; + } + } + } + } + } + } + } + if (c is 0) break; + totalHeight = 0; + for (int i=0; iRowData object to change the initial * size of a Button in a Shell: *
    - * 		Display display = new Display();
    - * 		Shell shell = new Shell(display);
    - * 		shell.setLayout(new RowLayout());
    - * 		Button button1 = new Button(shell, SWT.PUSH);
    - * 		button1.setText("Button 1");
    - * 		button1.setLayoutData(new RowData(50, 40));
    + *      Display display = new Display();
    + *      Shell shell = new Shell(display);
    + *      shell.setLayout(new RowLayout());
    + *      Button button1 = new Button(shell, SWT.PUSH);
    + *      button1.setText("Button 1");
    + *      button1.setLayoutData(new RowData(50, 40));
      * 
    *

    * * @see RowLayout */ public final class RowData { - /** - * width specifies the desired width in pixels. This value - * is the wHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see dwt.widgets.Control#computeSize(int, int, bool) - */ - public int width = SWT.DEFAULT; - /** - * height specifies the preferred height in pixels. This value - * is the hHint passed into Control.computeSize(int, int, bool) - * to determine the preferred size of the control. - * - * The default value is SWT.DEFAULT. - * - * @see dwt.widgets.Control#computeSize(int, int, bool) - */ - public int height = SWT.DEFAULT; + /** + * width specifies the desired width in pixels. This value + * is the wHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see dwt.widgets.Control#computeSize(int, int, bool) + */ + public int width = SWT.DEFAULT; + /** + * height specifies the preferred height in pixels. This value + * is the hHint passed into Control.computeSize(int, int, bool) + * to determine the preferred size of the control. + * + * The default value is SWT.DEFAULT. + * + * @see dwt.widgets.Control#computeSize(int, int, bool) + */ + public int height = SWT.DEFAULT; - /** - * exclude informs the layout to ignore this control when sizing - * and positioning controls. If this value is true, - * the size and position of the control will not be managed by the - * layout. If this value is false, the size and - * position of the control will be computed and assigned. - * - * The default value is false. - * - * @since 3.1 - */ - public bool exclude = false; + /** + * exclude informs the layout to ignore this control when sizing + * and positioning controls. If this value is true, + * the size and position of the control will not be managed by the + * layout. If this value is false, the size and + * position of the control will be computed and assigned. + * + * The default value is false. + * + * @since 3.1 + */ + public bool exclude = false; /** * Constructs a new instance of RowData using @@ -87,8 +87,8 @@ * @param height a minimum height for the control */ public this (int width, int height) { - this.width = width; - this.height = height; + this.width = width; + this.height = height; } /** @@ -100,7 +100,7 @@ * and y coordinate specifies a minimum height for the control */ public this (Point point) { - this (point.x, point.y); + this (point.x, point.y); } char[] getName () { @@ -117,12 +117,12 @@ * @return a string representation of the RowData object */ public char[] toString () { - char[] string = getName ()~" {"; - if (width !is SWT.DEFAULT) string ~= "width="~to!(char[])(width)~" "; - if (height !is SWT.DEFAULT) string ~= "height="~to!(char[])(height)~" "; - if (exclude) string ~= "exclude="~to!(char[])(exclude)~" "; - string = trim( string ); - string ~= "}"; - return string; + char[] string = getName ()~" {"; + if (width !is SWT.DEFAULT) string ~= "width="~to!(char[])(width)~" "; + if (height !is SWT.DEFAULT) string ~= "height="~to!(char[])(height)~" "; + if (exclude) string ~= "exclude="~to!(char[])(exclude)~" "; + string = trim( string ); + string ~= "}"; + return string; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/layout/RowLayout.d --- a/dwt/layout/RowLayout.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/layout/RowLayout.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -40,21 +40,21 @@ * of its fields to non-default values, and then sets it into a * Shell. *
    - * 		RowLayout rowLayout = new RowLayout();
    - * 		rowLayout.wrap = false;
    - * 		rowLayout.pack = false;
    - * 		rowLayout.justify = true;
    - * 		rowLayout.type = SWT.VERTICAL;
    - * 		rowLayout.marginLeft = 5;
    - * 		rowLayout.marginTop = 5;
    - * 		rowLayout.marginRight = 5;
    - * 		rowLayout.marginBottom = 5;
    - * 		rowLayout.spacing = 0;
    - * 		shell.setLayout(rowLayout);
    + *      RowLayout rowLayout = new RowLayout();
    + *      rowLayout.wrap = false;
    + *      rowLayout.pack = false;
    + *      rowLayout.justify = true;
    + *      rowLayout.type = SWT.VERTICAL;
    + *      rowLayout.marginLeft = 5;
    + *      rowLayout.marginTop = 5;
    + *      rowLayout.marginRight = 5;
    + *      rowLayout.marginBottom = 5;
    + *      rowLayout.spacing = 0;
    + *      shell.setLayout(rowLayout);
      * 
    * If you are using the default field values, you only need one line of code: *
    - * 		shell.setLayout(new RowLayout());
    + *      shell.setLayout(new RowLayout());
      * 
    *

    * @@ -62,118 +62,118 @@ */ public final class RowLayout : Layout { - /** - * type specifies whether the layout places controls in rows or - * columns. - * - * The default value is HORIZONTAL. - * - * Possible values are:
      - *
    • HORIZONTAL: Position the controls horizontally from left to right
    • - *
    • VERTICAL: Position the controls vertically from top to bottom
    • - *
    - * - * @since 2.0 - */ - public int type = SWT.HORIZONTAL; + /** + * type specifies whether the layout places controls in rows or + * columns. + * + * The default value is HORIZONTAL. + * + * Possible values are:
      + *
    • HORIZONTAL: Position the controls horizontally from left to right
    • + *
    • VERTICAL: Position the controls vertically from top to bottom
    • + *
    + * + * @since 2.0 + */ + public int type = SWT.HORIZONTAL; - /** - * marginWidth specifies the number of pixels of horizontal margin - * that will be placed along the left and right edges of the layout. - * - * The default value is 0. - * - * @since 3.0 - */ - public int marginWidth = 0; + /** + * marginWidth specifies the number of pixels of horizontal margin + * that will be placed along the left and right edges of the layout. + * + * The default value is 0. + * + * @since 3.0 + */ + public int marginWidth = 0; - /** - * marginHeight specifies the number of pixels of vertical margin - * that will be placed along the top and bottom edges of the layout. - * - * The default value is 0. - * - * @since 3.0 - */ - public int marginHeight = 0; + /** + * marginHeight specifies the number of pixels of vertical margin + * that will be placed along the top and bottom edges of the layout. + * + * The default value is 0. + * + * @since 3.0 + */ + public int marginHeight = 0; - /** - * spacing specifies the number of pixels between the edge of one cell - * and the edge of its neighbouring cell. - * - * The default value is 3. - */ - public int spacing = 3; + /** + * spacing specifies the number of pixels between the edge of one cell + * and the edge of its neighbouring cell. + * + * The default value is 3. + */ + public int spacing = 3; - /** - * wrap specifies whether a control will be wrapped to the next - * row if there is insufficient space on the current row. - * - * The default value is true. - */ - public bool wrap = true; + /** + * wrap specifies whether a control will be wrapped to the next + * row if there is insufficient space on the current row. + * + * The default value is true. + */ + public bool wrap = true; - /** - * pack specifies whether all controls in the layout take - * their preferred size. If pack is false, all controls will - * have the same size which is the size required to accommodate the - * largest preferred height and the largest preferred width of all - * the controls in the layout. - * - * The default value is true. - */ - public bool pack = true; + /** + * pack specifies whether all controls in the layout take + * their preferred size. If pack is false, all controls will + * have the same size which is the size required to accommodate the + * largest preferred height and the largest preferred width of all + * the controls in the layout. + * + * The default value is true. + */ + public bool pack = true; - /** - * fill specifies whether the controls in a row should be - * all the same height for horizontal layouts, or the same - * width for vertical layouts. - * - * The default value is false. - * - * @since 3.0 - */ - public bool fill = false; + /** + * fill specifies whether the controls in a row should be + * all the same height for horizontal layouts, or the same + * width for vertical layouts. + * + * The default value is false. + * + * @since 3.0 + */ + public bool fill = false; - /** - * justify specifies whether the controls in a row should be - * fully justified, with any extra space placed between the controls. - * - * The default value is false. - */ - public bool justify = false; + /** + * justify specifies whether the controls in a row should be + * fully justified, with any extra space placed between the controls. + * + * The default value is false. + */ + public bool justify = false; - /** - * marginLeft specifies the number of pixels of horizontal margin - * that will be placed along the left edge of the layout. - * - * The default value is 3. - */ - public int marginLeft = 3; + /** + * marginLeft specifies the number of pixels of horizontal margin + * that will be placed along the left edge of the layout. + * + * The default value is 3. + */ + public int marginLeft = 3; - /** - * marginTop specifies the number of pixels of vertical margin - * that will be placed along the top edge of the layout. - * - * The default value is 3. - */ - public int marginTop = 3; + /** + * marginTop specifies the number of pixels of vertical margin + * that will be placed along the top edge of the layout. + * + * The default value is 3. + */ + public int marginTop = 3; - /** - * marginRight specifies the number of pixels of horizontal margin - * that will be placed along the right edge of the layout. - * - * The default value is 3. - */ - public int marginRight = 3; + /** + * marginRight specifies the number of pixels of horizontal margin + * that will be placed along the right edge of the layout. + * + * The default value is 3. + */ + public int marginRight = 3; - /** - * marginBottom specifies the number of pixels of vertical margin - * that will be placed along the bottom edge of the layout. - * - * The default value is 3. - */ - public int marginBottom = 3; + /** + * marginBottom specifies the number of pixels of vertical margin + * that will be placed along the bottom edge of the layout. + * + * The default value is 3. + */ + public int marginBottom = 3; /** * Constructs a new instance of this class. @@ -189,33 +189,33 @@ * @since 2.0 */ public this (int type) { - this.type = type; + this.type = type; } protected Point computeSize (Composite composite, int wHint, int hHint, bool flushCache_) { - Point extent; - if (type is SWT.HORIZONTAL) { - extent = layoutHorizontal (composite, false, (wHint !is SWT.DEFAULT) && wrap, wHint, flushCache_); - } else { - extent = layoutVertical (composite, false, (hHint !is SWT.DEFAULT) && wrap, hHint, flushCache_); - } - if (wHint !is SWT.DEFAULT) extent.x = wHint; - if (hHint !is SWT.DEFAULT) extent.y = hHint; - return extent; + Point extent; + if (type is SWT.HORIZONTAL) { + extent = layoutHorizontal (composite, false, (wHint !is SWT.DEFAULT) && wrap, wHint, flushCache_); + } else { + extent = layoutVertical (composite, false, (hHint !is SWT.DEFAULT) && wrap, hHint, flushCache_); + } + if (wHint !is SWT.DEFAULT) extent.x = wHint; + if (hHint !is SWT.DEFAULT) extent.y = hHint; + return extent; } Point computeSize (Control control, bool flushCache_) { - int wHint = SWT.DEFAULT, hHint = SWT.DEFAULT; - RowData data = cast(RowData) control.getLayoutData (); - if (data !is null) { - wHint = data.width; - hHint = data.height; - } - return control.computeSize (wHint, hHint, flushCache_); + int wHint = SWT.DEFAULT, hHint = SWT.DEFAULT; + RowData data = cast(RowData) control.getLayoutData (); + if (data !is null) { + wHint = data.width; + hHint = data.height; + } + return control.computeSize (wHint, hHint, flushCache_); } protected bool flushCache (Control control) { - return true; + return true; } char[] getName () { @@ -226,226 +226,226 @@ } protected void layout (Composite composite, bool flushCache_) { - Rectangle clientArea = composite.getClientArea (); - if (type is SWT.HORIZONTAL) { - layoutHorizontal (composite, true, wrap, clientArea.width, flushCache_); - } else { - layoutVertical (composite, true, wrap, clientArea.height, flushCache_); - } + Rectangle clientArea = composite.getClientArea (); + if (type is SWT.HORIZONTAL) { + layoutHorizontal (composite, true, wrap, clientArea.width, flushCache_); + } else { + layoutVertical (composite, true, wrap, clientArea.height, flushCache_); + } } Point layoutHorizontal (Composite composite, bool move, bool wrap, int width, bool flushCache_) { - Control [] children = composite.getChildren (); - int count = 0; - for (int i=0; i width)) { - wrapped = true; - if (move && (justify || fill)) wraps [i - 1] = maxHeight; - x = marginLeft + marginWidth; - y += spacing + maxHeight; - if (pack) maxHeight = 0; - } - if (pack || fill) { - maxHeight = Math.max (maxHeight, childHeight); - } - if (move) { - int childX = x + clientX, childY = y + clientY; - if (justify || fill) { - bounds [i] = new Rectangle (childX, childY, childWidth, childHeight); - } else { - child.setBounds (childX, childY, childWidth, childHeight); - } - } - x += spacing + childWidth; - maxX = Math.max (maxX, x); - } - maxX = Math.max (clientX + marginLeft + marginWidth, maxX - spacing); - if (!wrapped) maxX += marginRight + marginWidth; - if (move && (justify || fill)) { - int space = 0, margin = 0; - if (!wrapped) { - space = Math.max (0, (width - maxX) / (count + 1)); - margin = Math.max (0, ((width - maxX) % (count + 1)) / 2); - } else { - if (fill || justify) { - int last = 0; - if (count > 0) wraps [count - 1] = maxHeight; - for (int i=0; i width)) { + wrapped = true; + if (move && (justify || fill)) wraps [i - 1] = maxHeight; + x = marginLeft + marginWidth; + y += spacing + maxHeight; + if (pack) maxHeight = 0; + } + if (pack || fill) { + maxHeight = Math.max (maxHeight, childHeight); + } + if (move) { + int childX = x + clientX, childY = y + clientY; + if (justify || fill) { + bounds [i] = new Rectangle (childX, childY, childWidth, childHeight); + } else { + child.setBounds (childX, childY, childWidth, childHeight); + } + } + x += spacing + childWidth; + maxX = Math.max (maxX, x); + } + maxX = Math.max (clientX + marginLeft + marginWidth, maxX - spacing); + if (!wrapped) maxX += marginRight + marginWidth; + if (move && (justify || fill)) { + int space = 0, margin = 0; + if (!wrapped) { + space = Math.max (0, (width - maxX) / (count + 1)); + margin = Math.max (0, ((width - maxX) % (count + 1)) / 2); + } else { + if (fill || justify) { + int last = 0; + if (count > 0) wraps [count - 1] = maxHeight; + for (int i=0; i height)) { - wrapped = true; - if (move && (justify || fill)) wraps [i - 1] = maxWidth; - x += spacing + maxWidth; - y = marginTop + marginHeight; - if (pack) maxWidth = 0; - } - if (pack || fill) { - maxWidth = Math.max (maxWidth, childWidth); - } - if (move) { - int childX = x + clientX, childY = y + clientY; - if (justify || fill) { - bounds [i] = new Rectangle (childX, childY, childWidth, childHeight); - } else { - child.setBounds (childX, childY, childWidth, childHeight); - } - } - y += spacing + childHeight; - maxY = Math.max (maxY, y); - } - maxY = Math.max (clientY + marginTop + marginHeight, maxY - spacing); - if (!wrapped) maxY += marginBottom + marginHeight; - if (move && (justify || fill)) { - int space = 0, margin = 0; - if (!wrapped) { - space = Math.max (0, (height - maxY) / (count + 1)); - margin = Math.max (0, ((height - maxY) % (count + 1)) / 2); - } else { - if (fill || justify) { - int last = 0; - if (count > 0) wraps [count - 1] = maxWidth; - for (int i=0; i height)) { + wrapped = true; + if (move && (justify || fill)) wraps [i - 1] = maxWidth; + x += spacing + maxWidth; + y = marginTop + marginHeight; + if (pack) maxWidth = 0; + } + if (pack || fill) { + maxWidth = Math.max (maxWidth, childWidth); + } + if (move) { + int childX = x + clientX, childY = y + clientY; + if (justify || fill) { + bounds [i] = new Rectangle (childX, childY, childWidth, childHeight); + } else { + child.setBounds (childX, childY, childWidth, childHeight); + } + } + y += spacing + childHeight; + maxY = Math.max (maxY, y); + } + maxY = Math.max (clientY + marginTop + marginHeight, maxY - spacing); + if (!wrapped) maxY += marginBottom + marginHeight; + if (move && (justify || fill)) { + int space = 0, margin = 0; + if (!wrapped) { + space = Math.max (0, (height - maxY) / (count + 1)); + margin = Math.max (0, ((height - maxY) % (count + 1)) / 2); + } else { + if (fill || justify) { + int last = 0; + if (count > 0) wraps [count - 1] = maxWidth; + for (int i=0; i */ public class Button : Control { - GtkWidget* boxHandle, labelHandle, imageHandle, arrowHandle, groupHandle; - bool selected; - ImageList imageList; - Image image; - char[] text; + GtkWidget* boxHandle, labelHandle, imageHandle, arrowHandle, groupHandle; + bool selected; + ImageList imageList; + Image image; + char[] text; /** * Constructs a new instance of this class given its parent @@ -91,22 +91,22 @@ * @see Widget#getStyle */ public this (Composite parent, int style) { - super (parent, checkStyle (style)); + super (parent, checkStyle (style)); } static int checkStyle (int style) { - style = checkBits (style, SWT.PUSH, SWT.ARROW, SWT.CHECK, SWT.RADIO, SWT.TOGGLE, 0); - if ((style & (SWT.PUSH | SWT.TOGGLE)) !is 0) { - return checkBits (style, SWT.CENTER, SWT.LEFT, SWT.RIGHT, 0, 0, 0); - } - if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { - return checkBits (style, SWT.LEFT, SWT.RIGHT, SWT.CENTER, 0, 0, 0); - } - if ((style & SWT.ARROW) !is 0) { - style |= SWT.NO_FOCUS; - return checkBits (style, SWT.UP, SWT.DOWN, SWT.LEFT, SWT.RIGHT, 0, 0); - } - return style; + style = checkBits (style, SWT.PUSH, SWT.ARROW, SWT.CHECK, SWT.RADIO, SWT.TOGGLE, 0); + if ((style & (SWT.PUSH | SWT.TOGGLE)) !is 0) { + return checkBits (style, SWT.CENTER, SWT.LEFT, SWT.RIGHT, 0, 0, 0); + } + if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { + return checkBits (style, SWT.LEFT, SWT.RIGHT, SWT.CENTER, 0, 0, 0); + } + if ((style & SWT.ARROW) !is 0) { + style |= SWT.NO_FOCUS; + return checkBits (style, SWT.UP, SWT.DOWN, SWT.LEFT, SWT.RIGHT, 0, 0); + } + return style; } /** @@ -134,139 +134,139 @@ * @see SelectionEvent */ public void addSelectionListener (SelectionListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.Selection,typedListener); - addListener (SWT.DefaultSelection,typedListener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.Selection,typedListener); + addListener (SWT.DefaultSelection,typedListener); } override public Point computeSize (int wHint, int hHint, bool changed) { - checkWidget (); - if (wHint !is SWT.DEFAULT && wHint < 0) wHint = 0; - if (hHint !is SWT.DEFAULT && hHint < 0) hHint = 0; - /* - * Feature in GTK, GtkCheckButton and GtkRadioButton allocate - * only the minimum size necessary for its child. This causes the child - * alignment to fail. The fix is to set the child size to the size - * of the button. - */ - forceResize (); - int reqWidth = -1, reqHeight = -1; - if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { - OS.gtk_widget_get_size_request (boxHandle, &reqWidth, &reqHeight); - OS.gtk_widget_set_size_request (boxHandle, -1, -1); - } - Point size = computeNativeSize (handle, wHint, hHint, changed); - if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { - OS.gtk_widget_set_size_request (boxHandle, reqWidth, reqHeight); - } - if (wHint !is SWT.DEFAULT || hHint !is SWT.DEFAULT) { - if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_CAN_DEFAULT) !is 0) { - GtkBorder border; + checkWidget (); + if (wHint !is SWT.DEFAULT && wHint < 0) wHint = 0; + if (hHint !is SWT.DEFAULT && hHint < 0) hHint = 0; + /* + * Feature in GTK, GtkCheckButton and GtkRadioButton allocate + * only the minimum size necessary for its child. This causes the child + * alignment to fail. The fix is to set the child size to the size + * of the button. + */ + forceResize (); + int reqWidth = -1, reqHeight = -1; + if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { + OS.gtk_widget_get_size_request (boxHandle, &reqWidth, &reqHeight); + OS.gtk_widget_set_size_request (boxHandle, -1, -1); + } + Point size = computeNativeSize (handle, wHint, hHint, changed); + if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { + OS.gtk_widget_set_size_request (boxHandle, reqWidth, reqHeight); + } + if (wHint !is SWT.DEFAULT || hHint !is SWT.DEFAULT) { + if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_CAN_DEFAULT) !is 0) { + GtkBorder border; GtkBorder* buffer; - OS.gtk_widget_style_get1 (handle, OS.default_border.ptr, cast(int*)&buffer ); - if (buffer !is null) { + OS.gtk_widget_style_get1 (handle, OS.default_border.ptr, cast(int*)&buffer ); + if (buffer !is null) { border = *buffer; - } else { - /* Use the GTK+ default value of 1 for each. */ - border.left = border.right = border.top = border.bottom = 1; - } - if (wHint !is SWT.DEFAULT) size.x += border.left + border.right; - if (hHint !is SWT.DEFAULT) size.y += border.top + border.bottom; - } - } - return size; + } else { + /* Use the GTK+ default value of 1 for each. */ + border.left = border.right = border.top = border.bottom = 1; + } + if (wHint !is SWT.DEFAULT) size.x += border.left + border.right; + if (hHint !is SWT.DEFAULT) size.y += border.top + border.bottom; + } + } + return size; } override void createHandle (int index) { - state |= HANDLE; - if ((style & SWT.PUSH) is 0) state |= THEME_BACKGROUND; - int bits = SWT.ARROW | SWT.TOGGLE | SWT.CHECK | SWT.RADIO | SWT.PUSH; - fixedHandle = cast(GtkWidget*)OS.g_object_new (display.gtk_fixed_get_type (), null); - if (fixedHandle is null) error (SWT.ERROR_NO_HANDLES); - OS.gtk_fixed_set_has_window (cast(GtkFixed*)fixedHandle, true); - switch (style & bits) { - case SWT.ARROW: - int arrow_type = OS.GTK_ARROW_UP; - if ((style & SWT.UP) !is 0) arrow_type = OS.GTK_ARROW_UP; - if ((style & SWT.DOWN) !is 0) arrow_type = OS.GTK_ARROW_DOWN; + state |= HANDLE; + if ((style & SWT.PUSH) is 0) state |= THEME_BACKGROUND; + int bits = SWT.ARROW | SWT.TOGGLE | SWT.CHECK | SWT.RADIO | SWT.PUSH; + fixedHandle = cast(GtkWidget*)OS.g_object_new (display.gtk_fixed_get_type (), null); + if (fixedHandle is null) error (SWT.ERROR_NO_HANDLES); + OS.gtk_fixed_set_has_window (cast(GtkFixed*)fixedHandle, true); + switch (style & bits) { + case SWT.ARROW: + int arrow_type = OS.GTK_ARROW_UP; + if ((style & SWT.UP) !is 0) arrow_type = OS.GTK_ARROW_UP; + if ((style & SWT.DOWN) !is 0) arrow_type = OS.GTK_ARROW_DOWN; if ((style & SWT.LEFT) !is 0) arrow_type = OS.GTK_ARROW_LEFT; if ((style & SWT.RIGHT) !is 0) arrow_type = OS.GTK_ARROW_RIGHT; - handle = OS.gtk_button_new (); - if (handle is null) error (SWT.ERROR_NO_HANDLES); - arrowHandle = OS.gtk_arrow_new (arrow_type, OS.GTK_SHADOW_OUT); - if (arrowHandle is null) error (SWT.ERROR_NO_HANDLES); - break; - case SWT.TOGGLE: - handle = OS.gtk_toggle_button_new (); - if (handle is null) error (SWT.ERROR_NO_HANDLES); - break; - case SWT.CHECK: - handle = OS.gtk_check_button_new (); - if (handle is null) error (SWT.ERROR_NO_HANDLES); - break; - case SWT.RADIO: - /* - * Feature in GTK. In GTK, radio button must always be part of - * a radio button group. In a GTK radio group, one button is always - * selected. This means that it is not possible to have a single - * radio button that is unselected. This is necessary to allow - * applications to implement their own radio behavior or use radio - * buttons outside of radio groups. The fix is to create a hidden - * radio button for each radio button we create and add them - * to the same group. This allows the visible button to be - * unselected. - */ - groupHandle = cast(GtkWidget*)OS.gtk_radio_button_new (null); - if (groupHandle is null) error (SWT.ERROR_NO_HANDLES); - OS.g_object_ref (groupHandle); - OS.gtk_object_sink (cast(GtkObject*)groupHandle); - handle = OS.gtk_radio_button_new ( OS.gtk_radio_button_get_group (cast(GtkRadioButton*)groupHandle)); - if (handle is null) error (SWT.ERROR_NO_HANDLES); - break; - case SWT.PUSH: - default: - handle = OS.gtk_button_new (); - if (handle is null) error (SWT.ERROR_NO_HANDLES); - OS.GTK_WIDGET_SET_FLAGS(handle, OS.GTK_CAN_DEFAULT); - break; - } - if ((style & SWT.ARROW) !is 0) { - OS.gtk_container_add (cast(GtkContainer*)handle, arrowHandle); - } else { - boxHandle = OS.gtk_hbox_new (false, 4); - if (boxHandle is null) error (SWT.ERROR_NO_HANDLES); - labelHandle = OS.gtk_label_new_with_mnemonic (null); - if (labelHandle is null) error (SWT.ERROR_NO_HANDLES); - imageHandle = OS.gtk_image_new (); - if (imageHandle is null) error (SWT.ERROR_NO_HANDLES); - OS.gtk_container_add (cast(GtkContainer*)handle, boxHandle); - OS.gtk_container_add (cast(GtkContainer*)boxHandle, imageHandle); - OS.gtk_container_add (cast(GtkContainer*)boxHandle, labelHandle); - } - OS.gtk_container_add (cast(GtkContainer*)fixedHandle, handle); + handle = OS.gtk_button_new (); + if (handle is null) error (SWT.ERROR_NO_HANDLES); + arrowHandle = OS.gtk_arrow_new (arrow_type, OS.GTK_SHADOW_OUT); + if (arrowHandle is null) error (SWT.ERROR_NO_HANDLES); + break; + case SWT.TOGGLE: + handle = OS.gtk_toggle_button_new (); + if (handle is null) error (SWT.ERROR_NO_HANDLES); + break; + case SWT.CHECK: + handle = OS.gtk_check_button_new (); + if (handle is null) error (SWT.ERROR_NO_HANDLES); + break; + case SWT.RADIO: + /* + * Feature in GTK. In GTK, radio button must always be part of + * a radio button group. In a GTK radio group, one button is always + * selected. This means that it is not possible to have a single + * radio button that is unselected. This is necessary to allow + * applications to implement their own radio behavior or use radio + * buttons outside of radio groups. The fix is to create a hidden + * radio button for each radio button we create and add them + * to the same group. This allows the visible button to be + * unselected. + */ + groupHandle = cast(GtkWidget*)OS.gtk_radio_button_new (null); + if (groupHandle is null) error (SWT.ERROR_NO_HANDLES); + OS.g_object_ref (groupHandle); + OS.gtk_object_sink (cast(GtkObject*)groupHandle); + handle = OS.gtk_radio_button_new ( OS.gtk_radio_button_get_group (cast(GtkRadioButton*)groupHandle)); + if (handle is null) error (SWT.ERROR_NO_HANDLES); + break; + case SWT.PUSH: + default: + handle = OS.gtk_button_new (); + if (handle is null) error (SWT.ERROR_NO_HANDLES); + OS.GTK_WIDGET_SET_FLAGS(handle, OS.GTK_CAN_DEFAULT); + break; + } + if ((style & SWT.ARROW) !is 0) { + OS.gtk_container_add (cast(GtkContainer*)handle, arrowHandle); + } else { + boxHandle = OS.gtk_hbox_new (false, 4); + if (boxHandle is null) error (SWT.ERROR_NO_HANDLES); + labelHandle = OS.gtk_label_new_with_mnemonic (null); + if (labelHandle is null) error (SWT.ERROR_NO_HANDLES); + imageHandle = OS.gtk_image_new (); + if (imageHandle is null) error (SWT.ERROR_NO_HANDLES); + OS.gtk_container_add (cast(GtkContainer*)handle, boxHandle); + OS.gtk_container_add (cast(GtkContainer*)boxHandle, imageHandle); + OS.gtk_container_add (cast(GtkContainer*)boxHandle, labelHandle); + } + OS.gtk_container_add (cast(GtkContainer*)fixedHandle, handle); if ((style & SWT.ARROW) !is 0) return; - _setAlignment (style & (SWT.LEFT | SWT.CENTER | SWT.RIGHT)); + _setAlignment (style & (SWT.LEFT | SWT.CENTER | SWT.RIGHT)); } override void createWidget (int index) { - super.createWidget (index); - text = ""; + super.createWidget (index); + text = ""; } override void deregister () { - super.deregister (); - if (boxHandle !is null) display.removeWidget (boxHandle); - if (labelHandle !is null) display.removeWidget (labelHandle); - if (imageHandle !is null) display.removeWidget (imageHandle); - if (arrowHandle !is null) display.removeWidget (arrowHandle); + super.deregister (); + if (boxHandle !is null) display.removeWidget (boxHandle); + if (labelHandle !is null) display.removeWidget (labelHandle); + if (imageHandle !is null) display.removeWidget (imageHandle); + if (arrowHandle !is null) display.removeWidget (arrowHandle); } override GtkWidget* fontHandle () { - if (labelHandle !is null) return labelHandle; - return super.fontHandle (); + if (labelHandle !is null) return labelHandle; + return super.fontHandle (); } /** @@ -286,18 +286,18 @@ * */ public int getAlignment () { - checkWidget (); - if ((style & SWT.ARROW) !is 0) { - if ((style & SWT.UP) !is 0) return SWT.UP; - if ((style & SWT.DOWN) !is 0) return SWT.DOWN; - if ((style & SWT.LEFT) !is 0) return SWT.LEFT; - if ((style & SWT.RIGHT) !is 0) return SWT.RIGHT; - return SWT.UP; - } - if ((style & SWT.LEFT) !is 0) return SWT.LEFT; - if ((style & SWT.CENTER) !is 0) return SWT.CENTER; - if ((style & SWT.RIGHT) !is 0) return SWT.RIGHT; - return SWT.LEFT; + checkWidget (); + if ((style & SWT.ARROW) !is 0) { + if ((style & SWT.UP) !is 0) return SWT.UP; + if ((style & SWT.DOWN) !is 0) return SWT.DOWN; + if ((style & SWT.LEFT) !is 0) return SWT.LEFT; + if ((style & SWT.RIGHT) !is 0) return SWT.RIGHT; + return SWT.UP; + } + if ((style & SWT.LEFT) !is 0) return SWT.LEFT; + if ((style & SWT.CENTER) !is 0) return SWT.CENTER; + if ((style & SWT.RIGHT) !is 0) return SWT.RIGHT; + return SWT.LEFT; } /** @@ -312,12 +312,12 @@ * */ public Image getImage () { - checkWidget (); - return image; + checkWidget (); + return image; } override char[] getNameText () { - return getText (); + return getText (); } /** @@ -337,9 +337,9 @@ * */ public bool getSelection () { - checkWidget (); - if ((style & (SWT.CHECK | SWT.RADIO | SWT.TOGGLE)) is 0) return false; - return cast(bool)OS.gtk_toggle_button_get_active (cast(GtkToggleButton*)handle); + checkWidget (); + if ((style & (SWT.CHECK | SWT.RADIO | SWT.TOGGLE)) is 0) return false; + return cast(bool)OS.gtk_toggle_button_get_active (cast(GtkToggleButton*)handle); } /** @@ -355,108 +355,108 @@ * */ public char[] getText () { - checkWidget(); - if ((style & SWT.ARROW) !is 0) return ""; - return text; + checkWidget(); + if ((style & SWT.ARROW) !is 0) return ""; + return text; } override int /*long*/ gtk_button_press_event (GtkWidget* widget, GdkEventButton* event) { - auto result = super.gtk_button_press_event (widget, event); - if (result !is 0) return result; - if ((style & SWT.RADIO) !is 0) selected = getSelection (); - return result; + auto result = super.gtk_button_press_event (widget, event); + if (result !is 0) return result; + if ((style & SWT.RADIO) !is 0) selected = getSelection (); + return result; } override int /*long*/ gtk_clicked (GtkWidget* widget) { - if ((style & SWT.RADIO) !is 0) { - if ((parent.getStyle () & SWT.NO_RADIO_GROUP) !is 0) { - setSelection (!selected); - } else { - selectRadio (); - } - } - postEvent (SWT.Selection); - return 0; + if ((style & SWT.RADIO) !is 0) { + if ((parent.getStyle () & SWT.NO_RADIO_GROUP) !is 0) { + setSelection (!selected); + } else { + selectRadio (); + } + } + postEvent (SWT.Selection); + return 0; } override int /*long*/ gtk_focus_in_event (GtkWidget* widget, GdkEventFocus* event) { - auto result = super.gtk_focus_in_event (widget, event); - // widget could be disposed at this point - if (handle is null) return 0; - if ((style & SWT.PUSH) !is 0 && OS.GTK_WIDGET_HAS_DEFAULT (handle)) { - Decorations menuShell = menuShell (); - menuShell.defaultButton = this; - } - return result; + auto result = super.gtk_focus_in_event (widget, event); + // widget could be disposed at this point + if (handle is null) return 0; + if ((style & SWT.PUSH) !is 0 && OS.GTK_WIDGET_HAS_DEFAULT (handle)) { + Decorations menuShell = menuShell (); + menuShell.defaultButton = this; + } + return result; } override int /*long*/ gtk_focus_out_event (GtkWidget* widget, GdkEventFocus* event) { - auto result = super.gtk_focus_out_event (widget, event); - // widget could be disposed at this point - if (handle is null) return 0; - if ((style & SWT.PUSH) !is 0 && !OS.GTK_WIDGET_HAS_DEFAULT (handle)) { - Decorations menuShell = menuShell (); - if (menuShell.defaultButton is this) { - menuShell.defaultButton = null; - } - } - return result; + auto result = super.gtk_focus_out_event (widget, event); + // widget could be disposed at this point + if (handle is null) return 0; + if ((style & SWT.PUSH) !is 0 && !OS.GTK_WIDGET_HAS_DEFAULT (handle)) { + Decorations menuShell = menuShell (); + if (menuShell.defaultButton is this) { + menuShell.defaultButton = null; + } + } + return result; } override int /*long*/ gtk_key_press_event (GtkWidget* widget, GdkEventKey* event) { - auto result = super.gtk_key_press_event (widget, event); - if (result !is 0) return result; - if ((style & SWT.RADIO) !is 0) selected = getSelection (); - return result; + auto result = super.gtk_key_press_event (widget, event); + if (result !is 0) return result; + if ((style & SWT.RADIO) !is 0) selected = getSelection (); + return result; } override void hookEvents () { - super.hookEvents(); - OS.g_signal_connect_closure (handle, OS.clicked.ptr, display.closures [CLICKED], false); - if (labelHandle !is null) { - OS.g_signal_connect_closure_by_id (cast(void*)labelHandle, display.signalIds [MNEMONIC_ACTIVATE], 0, display.closures [MNEMONIC_ACTIVATE], false); - } + super.hookEvents(); + OS.g_signal_connect_closure (handle, OS.clicked.ptr, display.closures [CLICKED], false); + if (labelHandle !is null) { + OS.g_signal_connect_closure_by_id (cast(void*)labelHandle, display.signalIds [MNEMONIC_ACTIVATE], 0, display.closures [MNEMONIC_ACTIVATE], false); + } } override bool isDescribedByLabel () { - return false; + return false; } alias Control.mnemonicHit mnemonicHit; override bool mnemonicHit (char key) { - if (labelHandle is null) return false; - bool result = super.mnemonicHit (labelHandle, key); - if (result) setFocus (); - return result; + if (labelHandle is null) return false; + bool result = super.mnemonicHit (labelHandle, key); + if (result) setFocus (); + return result; } alias Control.mnemonicMatch mnemonicMatch; override bool mnemonicMatch (char key) { - if (labelHandle is null) return false; - return mnemonicMatch (labelHandle, key); + if (labelHandle is null) return false; + return mnemonicMatch (labelHandle, key); } override void register () { - super.register (); - if (boxHandle !is null) display.addWidget (boxHandle, this); - if (labelHandle !is null) display.addWidget (labelHandle, this); - if (imageHandle !is null) display.addWidget (imageHandle, this); - if (arrowHandle !is null) display.addWidget (arrowHandle, this); + super.register (); + if (boxHandle !is null) display.addWidget (boxHandle, this); + if (labelHandle !is null) display.addWidget (labelHandle, this); + if (imageHandle !is null) display.addWidget (imageHandle, this); + if (arrowHandle !is null) display.addWidget (arrowHandle, this); } override void releaseHandle () { - super.releaseHandle (); - boxHandle = imageHandle = labelHandle = arrowHandle = null; + super.releaseHandle (); + boxHandle = imageHandle = labelHandle = arrowHandle = null; } override void releaseWidget () { - super.releaseWidget (); - if (groupHandle !is null) OS.g_object_unref (groupHandle); - groupHandle = null; - if (imageList !is null) imageList.dispose (); - imageList = null; - image = null; - text = null; + super.releaseWidget (); + if (groupHandle !is null) OS.g_object_unref (groupHandle); + groupHandle = null; + if (imageList !is null) imageList.dispose (); + imageList = null; + image = null; + text = null; } /** @@ -477,49 +477,49 @@ * @see #addSelectionListener */ public void removeSelectionListener (SelectionListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.Selection, listener); - eventTable.unhook (SWT.DefaultSelection,listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.Selection, listener); + eventTable.unhook (SWT.DefaultSelection,listener); } override void resizeHandle (int width, int height) { - super.resizeHandle (width, height); - /* - * Feature in GTK, GtkCheckButton and GtkRadioButton allocate - * only the minimum size necessary for its child. This causes the child - * alignment to fail. The fix is to set the child size to the size - * of the button. - */ - if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { - OS.gtk_widget_set_size_request (boxHandle, width, -1); - } + super.resizeHandle (width, height); + /* + * Feature in GTK, GtkCheckButton and GtkRadioButton allocate + * only the minimum size necessary for its child. This causes the child + * alignment to fail. The fix is to set the child size to the size + * of the button. + */ + if ((style & (SWT.CHECK | SWT.RADIO)) !is 0) { + OS.gtk_widget_set_size_request (boxHandle, width, -1); + } } void selectRadio () { - /* - * This code is intentionally commented. When two groups - * of radio buttons with the same parent are separated by - * another control, the correct behavior should be that - * the two groups act independently. This is consistent - * with radio tool and menu items. The commented code - * implements this behavior. - */ -// int index = 0; -// Control [] children = parent._getChildren (); -// while (index < children.length && children [index] !is this) index++; -// int i = index - 1; -// while (i >= 0 && children [i].setRadioSelection (false)) --i; -// int j = index + 1; -// while (j < children.length && children [j].setRadioSelection (false)) j++; -// setSelection (true); - Control [] children = parent._getChildren (); - for (int i=0; i= 0 && children [i].setRadioSelection (false)) --i; +// int j = index + 1; +// while (j < children.length && children [j].setRadioSelection (false)) j++; +// setSelection (true); + Control [] children = parent._getChildren (); + for (int i=0; i */ public void setAlignment (int alignment) { - checkWidget (); - _setAlignment (alignment); + checkWidget (); + _setAlignment (alignment); } void _setAlignment (int alignment) { - if ((style & SWT.ARROW) !is 0) { - if ((style & (SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT)) is 0) return; - style &= ~(SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT); - style |= alignment & (SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT); - int arrow_type = OS.GTK_ARROW_UP; - bool isRTL = (style & SWT.RIGHT_TO_LEFT) !is 0; - switch (alignment) { - case SWT.UP: arrow_type = OS.GTK_ARROW_UP; break; - case SWT.DOWN: arrow_type = OS.GTK_ARROW_DOWN; break; - case SWT.LEFT: arrow_type = isRTL ? OS.GTK_ARROW_RIGHT : OS.GTK_ARROW_LEFT; break; - case SWT.RIGHT: arrow_type = isRTL ? OS.GTK_ARROW_LEFT : OS.GTK_ARROW_RIGHT; break; + if ((style & SWT.ARROW) !is 0) { + if ((style & (SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT)) is 0) return; + style &= ~(SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT); + style |= alignment & (SWT.UP | SWT.DOWN | SWT.LEFT | SWT.RIGHT); + int arrow_type = OS.GTK_ARROW_UP; + bool isRTL = (style & SWT.RIGHT_TO_LEFT) !is 0; + switch (alignment) { + case SWT.UP: arrow_type = OS.GTK_ARROW_UP; break; + case SWT.DOWN: arrow_type = OS.GTK_ARROW_DOWN; break; + case SWT.LEFT: arrow_type = isRTL ? OS.GTK_ARROW_RIGHT : OS.GTK_ARROW_LEFT; break; + case SWT.RIGHT: arrow_type = isRTL ? OS.GTK_ARROW_LEFT : OS.GTK_ARROW_RIGHT; break; default: - } - OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, arrow_type, OS.GTK_SHADOW_OUT); - return; - } - if ((alignment & (SWT.LEFT | SWT.RIGHT | SWT.CENTER)) is 0) return; - style &= ~(SWT.LEFT | SWT.RIGHT | SWT.CENTER); - style |= alignment & (SWT.LEFT | SWT.RIGHT | SWT.CENTER); - /* Alignment not honoured when image and text are visible */ - bool bothVisible = OS.GTK_WIDGET_VISIBLE (labelHandle) && OS.GTK_WIDGET_VISIBLE (imageHandle); - if (bothVisible) { - if ((style & (SWT.RADIO | SWT.CHECK)) !is 0) alignment = SWT.LEFT; - if ((style & (SWT.PUSH | SWT.TOGGLE)) !is 0) alignment = SWT.CENTER; - } - if ((alignment & SWT.LEFT) !is 0) { - if (bothVisible) { - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, false, false, 0, OS.GTK_PACK_START); - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, false, false, 0, OS.GTK_PACK_START); - } - OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0.0f, 0.5f); - OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_LEFT); - OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 0.0f, 0.5f); - return; - } - if ((alignment & SWT.CENTER) !is 0) { - if (bothVisible) { - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, true, true, 0, OS.GTK_PACK_END); - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, true, true, 0, OS.GTK_PACK_START); - OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0f, 0.5f); - OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 1f, 0.5f); - } else { - OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0.5f, 0.5f); - OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_CENTER); - OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 0.5f, 0.5f); - } - return; - } - if ((alignment & SWT.RIGHT) !is 0) { - if (bothVisible) { - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, false, false, 0, OS.GTK_PACK_END); - OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, false, false, 0, OS.GTK_PACK_END); - } - OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 1.0f, 0.5f); - OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_RIGHT); - OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 1.0f, 0.5f); - return; - } + } + OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, arrow_type, OS.GTK_SHADOW_OUT); + return; + } + if ((alignment & (SWT.LEFT | SWT.RIGHT | SWT.CENTER)) is 0) return; + style &= ~(SWT.LEFT | SWT.RIGHT | SWT.CENTER); + style |= alignment & (SWT.LEFT | SWT.RIGHT | SWT.CENTER); + /* Alignment not honoured when image and text are visible */ + bool bothVisible = OS.GTK_WIDGET_VISIBLE (labelHandle) && OS.GTK_WIDGET_VISIBLE (imageHandle); + if (bothVisible) { + if ((style & (SWT.RADIO | SWT.CHECK)) !is 0) alignment = SWT.LEFT; + if ((style & (SWT.PUSH | SWT.TOGGLE)) !is 0) alignment = SWT.CENTER; + } + if ((alignment & SWT.LEFT) !is 0) { + if (bothVisible) { + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, false, false, 0, OS.GTK_PACK_START); + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, false, false, 0, OS.GTK_PACK_START); + } + OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0.0f, 0.5f); + OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_LEFT); + OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 0.0f, 0.5f); + return; + } + if ((alignment & SWT.CENTER) !is 0) { + if (bothVisible) { + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, true, true, 0, OS.GTK_PACK_END); + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, true, true, 0, OS.GTK_PACK_START); + OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0f, 0.5f); + OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 1f, 0.5f); + } else { + OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 0.5f, 0.5f); + OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_CENTER); + OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 0.5f, 0.5f); + } + return; + } + if ((alignment & SWT.RIGHT) !is 0) { + if (bothVisible) { + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, labelHandle, false, false, 0, OS.GTK_PACK_END); + OS.gtk_box_set_child_packing (cast(GtkBox*)boxHandle, imageHandle, false, false, 0, OS.GTK_PACK_END); + } + OS.gtk_misc_set_alignment (cast(GtkMisc*)labelHandle, 1.0f, 0.5f); + OS.gtk_label_set_justify (cast(GtkLabel*)labelHandle, OS.GTK_JUSTIFY_RIGHT); + OS.gtk_misc_set_alignment (cast(GtkMisc*)imageHandle, 1.0f, 0.5f); + return; + } } alias Control.setBackgroundColor setBackgroundColor; override void setBackgroundColor (GdkColor* color) { - super.setBackgroundColor (color); - setBackgroundColor(fixedHandle, color); - if (labelHandle !is null) setBackgroundColor(labelHandle, color); - if (imageHandle !is null) setBackgroundColor(imageHandle, color); + super.setBackgroundColor (color); + setBackgroundColor(fixedHandle, color); + if (labelHandle !is null) setBackgroundColor(labelHandle, color); + if (imageHandle !is null) setBackgroundColor(imageHandle, color); } override void setFontDescription (PangoFontDescription* font) { - super.setFontDescription (font); - if (labelHandle !is null) OS.gtk_widget_modify_font (labelHandle, font); - if (imageHandle !is null) OS.gtk_widget_modify_font (imageHandle, font); + super.setFontDescription (font); + if (labelHandle !is null) OS.gtk_widget_modify_font (labelHandle, font); + if (imageHandle !is null) OS.gtk_widget_modify_font (imageHandle, font); } override bool setRadioSelection (bool value) { - if ((style & SWT.RADIO) is 0) return false; - if (getSelection () !is value) { - setSelection (value); - postEvent (SWT.Selection); - } - return true; + if ((style & SWT.RADIO) is 0) return false; + if (getSelection () !is value) { + setSelection (value); + postEvent (SWT.Selection); + } + return true; } alias Control.setForegroundColor setForegroundColor; override void setForegroundColor (GdkColor* color) { - super.setForegroundColor (color); - setForegroundColor (fixedHandle, color); - if (labelHandle !is null) setForegroundColor (labelHandle, color); - if (imageHandle !is null) setForegroundColor (imageHandle, color); + super.setForegroundColor (color); + setForegroundColor (fixedHandle, color); + if (labelHandle !is null) setForegroundColor (labelHandle, color); + if (imageHandle !is null) setForegroundColor (imageHandle, color); } /** @@ -655,40 +655,40 @@ * */ public void setImage (Image image) { - checkWidget (); - if ((style & SWT.ARROW) !is 0) return; - if (imageList !is null) imageList.dispose (); - imageList = null; - if (image !is null) { - if (image.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT); - imageList = new ImageList (); - int imageIndex = imageList.add (image); - auto pixbuf = imageList.getPixbuf (imageIndex); - OS.gtk_image_set_from_pixbuf (cast(GtkImage*)imageHandle, pixbuf); - if (text.length is 0) OS.gtk_widget_hide (labelHandle); - OS.gtk_widget_show (imageHandle); - } else { - OS.gtk_image_set_from_pixbuf (cast(GtkImage*)imageHandle, null); - OS.gtk_widget_show (labelHandle); - OS.gtk_widget_hide (imageHandle); - } - this.image = image; - _setAlignment (style); + checkWidget (); + if ((style & SWT.ARROW) !is 0) return; + if (imageList !is null) imageList.dispose (); + imageList = null; + if (image !is null) { + if (image.isDisposed()) error (SWT.ERROR_INVALID_ARGUMENT); + imageList = new ImageList (); + int imageIndex = imageList.add (image); + auto pixbuf = imageList.getPixbuf (imageIndex); + OS.gtk_image_set_from_pixbuf (cast(GtkImage*)imageHandle, pixbuf); + if (text.length is 0) OS.gtk_widget_hide (labelHandle); + OS.gtk_widget_show (imageHandle); + } else { + OS.gtk_image_set_from_pixbuf (cast(GtkImage*)imageHandle, null); + OS.gtk_widget_show (labelHandle); + OS.gtk_widget_hide (imageHandle); + } + this.image = image; + _setAlignment (style); } override void setOrientation () { - super.setOrientation (); - if ((style & SWT.RIGHT_TO_LEFT) !is 0) { - if (labelHandle !is null) OS.gtk_widget_set_direction (labelHandle, OS.GTK_TEXT_DIR_RTL); - if (imageHandle !is null) OS.gtk_widget_set_direction (imageHandle, OS.GTK_TEXT_DIR_RTL); - if (arrowHandle !is null) { - switch (style & (SWT.LEFT | SWT.RIGHT)) { - case SWT.LEFT: OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, OS.GTK_ARROW_RIGHT, OS.GTK_SHADOW_OUT); break; - case SWT.RIGHT: OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, OS.GTK_ARROW_LEFT, OS.GTK_SHADOW_OUT); break; + super.setOrientation (); + if ((style & SWT.RIGHT_TO_LEFT) !is 0) { + if (labelHandle !is null) OS.gtk_widget_set_direction (labelHandle, OS.GTK_TEXT_DIR_RTL); + if (imageHandle !is null) OS.gtk_widget_set_direction (imageHandle, OS.GTK_TEXT_DIR_RTL); + if (arrowHandle !is null) { + switch (style & (SWT.LEFT | SWT.RIGHT)) { + case SWT.LEFT: OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, OS.GTK_ARROW_RIGHT, OS.GTK_SHADOW_OUT); break; + case SWT.RIGHT: OS.gtk_arrow_set (cast(GtkArrow*)arrowHandle, OS.GTK_ARROW_LEFT, OS.GTK_SHADOW_OUT); break; default: - } - } - } + } + } + } } /** @@ -708,12 +708,12 @@ * */ public void setSelection (bool selected) { - checkWidget(); - if ((style & (SWT.CHECK | SWT.RADIO | SWT.TOGGLE)) is 0) return; - OS.g_signal_handlers_block_matched (handle, OS.G_SIGNAL_MATCH_DATA, 0, 0, null, null, cast(void*)CLICKED); - OS.gtk_toggle_button_set_active (cast(GtkToggleButton*)handle, selected); - if ((style & SWT.RADIO) !is 0) OS.gtk_toggle_button_set_active (cast(GtkToggleButton*)groupHandle, !selected); - OS.g_signal_handlers_unblock_matched (handle, OS.G_SIGNAL_MATCH_DATA, 0, 0, null, null, cast(void*)CLICKED); + checkWidget(); + if ((style & (SWT.CHECK | SWT.RADIO | SWT.TOGGLE)) is 0) return; + OS.g_signal_handlers_block_matched (handle, OS.G_SIGNAL_MATCH_DATA, 0, 0, null, null, cast(void*)CLICKED); + OS.gtk_toggle_button_set_active (cast(GtkToggleButton*)handle, selected); + if ((style & SWT.RADIO) !is 0) OS.gtk_toggle_button_set_active (cast(GtkToggleButton*)groupHandle, !selected); + OS.g_signal_handlers_unblock_matched (handle, OS.G_SIGNAL_MATCH_DATA, 0, 0, null, null, cast(void*)CLICKED); } /** @@ -748,29 +748,29 @@ * */ public void setText (char[] string) { - checkWidget (); - if (string is null) error (SWT.ERROR_NULL_ARGUMENT); - if ((style & SWT.ARROW) !is 0) return; - text = string; - char [] chars = fixMnemonic (string); - OS.gtk_label_set_text_with_mnemonic (cast(GtkLabel*)labelHandle, toStringz(chars)); - if (image is null) OS.gtk_widget_hide (imageHandle); - OS.gtk_widget_show (labelHandle); - _setAlignment (style); + checkWidget (); + if (string is null) error (SWT.ERROR_NULL_ARGUMENT); + if ((style & SWT.ARROW) !is 0) return; + text = string; + char [] chars = fixMnemonic (string); + OS.gtk_label_set_text_with_mnemonic (cast(GtkLabel*)labelHandle, toStringz(chars)); + if (image is null) OS.gtk_widget_hide (imageHandle); + OS.gtk_widget_show (labelHandle); + _setAlignment (style); } override void showWidget () { - super.showWidget (); - if (boxHandle !is null) OS.gtk_widget_show (boxHandle); - if (labelHandle !is null) OS.gtk_widget_show (labelHandle); - if (arrowHandle !is null) OS.gtk_widget_show (arrowHandle); + super.showWidget (); + if (boxHandle !is null) OS.gtk_widget_show (boxHandle); + if (labelHandle !is null) OS.gtk_widget_show (labelHandle); + if (arrowHandle !is null) OS.gtk_widget_show (arrowHandle); } alias Control.traversalCode traversalCode; override int traversalCode (int key, GdkEventKey* event) { - int code = super.traversalCode (key, event); - if ((style & SWT.RADIO) !is 0) code |= SWT.TRAVERSE_ARROW_NEXT | SWT.TRAVERSE_ARROW_PREVIOUS; - return code; + int code = super.traversalCode (key, event); + if ((style & SWT.RADIO) !is 0) code |= SWT.TRAVERSE_ARROW_NEXT | SWT.TRAVERSE_ARROW_PREVIOUS; + return code; } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/widgets/Canvas.d --- a/dwt/widgets/Canvas.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/widgets/Canvas.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2006 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 @@ -41,7 +41,7 @@ * @see Composite */ public class Canvas : Composite { - Caret caret; + Caret caret; this () {} @@ -73,7 +73,7 @@ * @see Widget#getStyle */ public this (Composite parent, int style) { - super (parent, style); + super (parent, style); } /** @@ -98,10 +98,10 @@ * @since 3.2 */ public void drawBackground (GC gc, int x, int y, int width, int height) { - checkWidget (); - if (gc is null) error (SWT.ERROR_NULL_ARGUMENT); - if (gc.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); - super.drawBackground (gc, x, y, width, height); + checkWidget (); + if (gc is null) error (SWT.ERROR_NULL_ARGUMENT); + if (gc.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); + super.drawBackground (gc, x, y, width, height); } /** @@ -123,49 +123,49 @@ * */ public Caret getCaret () { - checkWidget(); - return caret; + checkWidget(); + return caret; } override Point getIMCaretPos () { - if (caret is null) return super.getIMCaretPos (); - return new Point (caret.x, caret.y); + if (caret is null) return super.getIMCaretPos (); + return new Point (caret.x, caret.y); } override int /*long*/ gtk_expose_event (GtkWidget* widget, GdkEventExpose* event) { - if ((state & OBSCURED) !is 0) return 0; - bool isFocus = caret !is null && caret.isFocusCaret (); - if (isFocus) caret.killFocus (); - auto result = super.gtk_expose_event (widget, event); - if (isFocus) caret.setFocus (); - return result; + if ((state & OBSCURED) !is 0) return 0; + bool isFocus = caret !is null && caret.isFocusCaret (); + if (isFocus) caret.killFocus (); + auto result = super.gtk_expose_event (widget, event); + if (isFocus) caret.setFocus (); + return result; } override int /*long*/ gtk_focus_in_event (GtkWidget* widget, GdkEventFocus* event) { - auto result = super.gtk_focus_in_event (widget, event); - if (caret !is null) caret.setFocus (); - return result; + auto result = super.gtk_focus_in_event (widget, event); + if (caret !is null) caret.setFocus (); + return result; } override int /*long*/ gtk_focus_out_event (GtkWidget* widget, GdkEventFocus* event) { - auto result = super.gtk_focus_out_event (widget, event); - if (caret !is null) caret.killFocus (); - return result; + auto result = super.gtk_focus_out_event (widget, event); + if (caret !is null) caret.killFocus (); + return result; } override void redrawWidget (int x, int y, int width, int height, bool redrawAll, bool all, bool trim) { - bool isFocus = caret !is null && caret.isFocusCaret (); - if (isFocus) caret.killFocus (); - super.redrawWidget (x, y, width, height, redrawAll, all, trim); - if (isFocus) caret.setFocus (); + bool isFocus = caret !is null && caret.isFocusCaret (); + if (isFocus) caret.killFocus (); + super.redrawWidget (x, y, width, height, redrawAll, all, trim); + if (isFocus) caret.setFocus (); } override void releaseChildren (bool destroy) { - if (caret !is null) { - caret.release (false); - caret = null; - } - super.releaseChildren (destroy); + if (caret !is null) { + caret.release (false); + caret = null; + } + super.releaseChildren (destroy); } /** @@ -191,97 +191,97 @@ * */ public void scroll (int destX, int destY, int x, int y, int width, int height, bool all) { - checkWidget(); - if (width <= 0 || height <= 0) return; - int deltaX = destX - x, deltaY = destY - y; - if (deltaX is 0 && deltaY is 0) return; - if (!isVisible ()) return; - bool isFocus = caret !is null && caret.isFocusCaret (); - if (isFocus) caret.killFocus (); - auto window = paintWindow (); - auto visibleRegion = OS.gdk_drawable_get_visible_region (window); - GdkRectangle* srcRect = new GdkRectangle (); - srcRect.x = x; - srcRect.y = y; - srcRect.width = width; - srcRect.height = height; - auto copyRegion = OS.gdk_region_rectangle (srcRect); - OS.gdk_region_intersect(copyRegion, visibleRegion); - auto invalidateRegion = OS.gdk_region_rectangle (srcRect); - OS.gdk_region_subtract (invalidateRegion, visibleRegion); - OS.gdk_region_offset (invalidateRegion, deltaX, deltaY); - GdkRectangle* copyRect = new GdkRectangle(); - OS.gdk_region_get_clipbox (copyRegion, copyRect); - if (copyRect.width !is 0 && copyRect.height !is 0) { - update (); - } - Control control = findBackgroundControl (); - if (control is null) control = this; - if (control.backgroundImage !is null) { - redrawWidget (x, y, width, height, false, false, false); - redrawWidget (destX, destY, width, height, false, false, false); - } else { -// GC gc = new GC (this); -// gc.copyArea (x, y, width, height, destX, destY); -// gc.dispose (); - auto gdkGC = OS.gdk_gc_new (window); - OS.gdk_gc_set_exposures (gdkGC, true); - OS.gdk_draw_drawable (window, gdkGC, window, copyRect.x, copyRect.y, copyRect.x + deltaX, copyRect.y + deltaY, copyRect.width, copyRect.height); - OS.g_object_unref (gdkGC); - bool disjoint = (destX + width < x) || (x + width < destX) || (destY + height < y) || (y + height < destY); - if (disjoint) { - GdkRectangle* rect = new GdkRectangle (); - rect.x = x; - rect.y = y; - rect.width = width; - rect.height = height; - OS.gdk_region_union_with_rect (invalidateRegion, rect); - } else { - GdkRectangle* rect = new GdkRectangle (); - if (deltaX !is 0) { - int newX = destX - deltaX; - if (deltaX < 0) newX = destX + width; - rect.x = newX; - rect.y = y; - rect.width = Math.abs(deltaX); - rect.height = height; - OS.gdk_region_union_with_rect (invalidateRegion, rect); - } - if (deltaY !is 0) { - int newY = destY - deltaY; - if (deltaY < 0) newY = destY + height; - rect.x = x; - rect.y = newY; - rect.width = width; - rect.height = Math.abs(deltaY); - OS.gdk_region_union_with_rect (invalidateRegion, rect); - } - } - OS.gdk_window_invalidate_region(window, invalidateRegion, all); - OS.gdk_region_destroy (visibleRegion); - OS.gdk_region_destroy (copyRegion); - OS.gdk_region_destroy (invalidateRegion); - } - if (all) { - Control [] children = _getChildren (); - for (int i=0; i= Math.max (x, rect.x) && - Math.min(y + height, rect.y + rect.height) >= Math.max (y, rect.y)) { - child.setLocation (rect.x + deltaX, rect.y + deltaY); - } - } - } - if (isFocus) caret.setFocus (); + checkWidget(); + if (width <= 0 || height <= 0) return; + int deltaX = destX - x, deltaY = destY - y; + if (deltaX is 0 && deltaY is 0) return; + if (!isVisible ()) return; + bool isFocus = caret !is null && caret.isFocusCaret (); + if (isFocus) caret.killFocus (); + auto window = paintWindow (); + auto visibleRegion = OS.gdk_drawable_get_visible_region (window); + GdkRectangle* srcRect = new GdkRectangle (); + srcRect.x = x; + srcRect.y = y; + srcRect.width = width; + srcRect.height = height; + auto copyRegion = OS.gdk_region_rectangle (srcRect); + OS.gdk_region_intersect(copyRegion, visibleRegion); + auto invalidateRegion = OS.gdk_region_rectangle (srcRect); + OS.gdk_region_subtract (invalidateRegion, visibleRegion); + OS.gdk_region_offset (invalidateRegion, deltaX, deltaY); + GdkRectangle* copyRect = new GdkRectangle(); + OS.gdk_region_get_clipbox (copyRegion, copyRect); + if (copyRect.width !is 0 && copyRect.height !is 0) { + update (); + } + Control control = findBackgroundControl (); + if (control is null) control = this; + if (control.backgroundImage !is null) { + redrawWidget (x, y, width, height, false, false, false); + redrawWidget (destX, destY, width, height, false, false, false); + } else { +// GC gc = new GC (this); +// gc.copyArea (x, y, width, height, destX, destY); +// gc.dispose (); + auto gdkGC = OS.gdk_gc_new (window); + OS.gdk_gc_set_exposures (gdkGC, true); + OS.gdk_draw_drawable (window, gdkGC, window, copyRect.x, copyRect.y, copyRect.x + deltaX, copyRect.y + deltaY, copyRect.width, copyRect.height); + OS.g_object_unref (gdkGC); + bool disjoint = (destX + width < x) || (x + width < destX) || (destY + height < y) || (y + height < destY); + if (disjoint) { + GdkRectangle* rect = new GdkRectangle (); + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + OS.gdk_region_union_with_rect (invalidateRegion, rect); + } else { + GdkRectangle* rect = new GdkRectangle (); + if (deltaX !is 0) { + int newX = destX - deltaX; + if (deltaX < 0) newX = destX + width; + rect.x = newX; + rect.y = y; + rect.width = Math.abs(deltaX); + rect.height = height; + OS.gdk_region_union_with_rect (invalidateRegion, rect); + } + if (deltaY !is 0) { + int newY = destY - deltaY; + if (deltaY < 0) newY = destY + height; + rect.x = x; + rect.y = newY; + rect.width = width; + rect.height = Math.abs(deltaY); + OS.gdk_region_union_with_rect (invalidateRegion, rect); + } + } + OS.gdk_window_invalidate_region(window, invalidateRegion, all); + OS.gdk_region_destroy (visibleRegion); + OS.gdk_region_destroy (copyRegion); + OS.gdk_region_destroy (invalidateRegion); + } + if (all) { + Control [] children = _getChildren (); + for (int i=0; i= Math.max (x, rect.x) && + Math.min(y + height, rect.y + rect.height) >= Math.max (y, rect.y)) { + child.setLocation (rect.x + deltaX, rect.y + deltaY); + } + } + } + if (isFocus) caret.setFocus (); } override int setBounds (int x, int y, int width, int height, bool move, bool resize) { - bool isFocus = caret !is null && caret.isFocusCaret (); - if (isFocus) caret.killFocus (); - int result = super.setBounds (x, y, width, height, move, resize); - if (isFocus) caret.setFocus (); - return result; + bool isFocus = caret !is null && caret.isFocusCaret (); + if (isFocus) caret.killFocus (); + int result = super.setBounds (x, y, width, height, move, resize); + if (isFocus) caret.setFocus (); + return result; } /** @@ -305,34 +305,34 @@ * */ public void setCaret (Caret caret) { - checkWidget(); - Caret newCaret = caret; - Caret oldCaret = this.caret; - this.caret = newCaret; - if (hasFocus ()) { - if (oldCaret !is null) oldCaret.killFocus (); - if (newCaret !is null) { - if (newCaret.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); - newCaret.setFocus (); - } - } + checkWidget(); + Caret newCaret = caret; + Caret oldCaret = this.caret; + this.caret = newCaret; + if (hasFocus ()) { + if (oldCaret !is null) oldCaret.killFocus (); + if (newCaret !is null) { + if (newCaret.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); + newCaret.setFocus (); + } + } } override public void setFont (Font font) { - checkWidget(); - if (caret !is null) caret.setFont (font); - super.setFont (font); + checkWidget(); + if (caret !is null) caret.setFont (font); + super.setFont (font); } void updateCaret () { - auto imHandle = imHandle (); - if (imHandle is null) return; - GdkRectangle* rect = new GdkRectangle (); - rect.x = caret.x; - rect.y = caret.y; - rect.width = caret.width; - rect.height = caret.height; - OS.gtk_im_context_set_cursor_location (imHandle, rect); + auto imHandle = imHandle (); + if (imHandle is null) return; + GdkRectangle* rect = new GdkRectangle (); + rect.x = caret.x; + rect.y = caret.y; + rect.width = caret.width; + rect.height = caret.height; + OS.gtk_im_context_set_cursor_location (imHandle, rect); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/widgets/Caret.d --- a/dwt/widgets/Caret.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/widgets/Caret.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * 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 @@ -49,12 +49,12 @@ *

    */ public class Caret : Widget { - Canvas parent; - int x, y, width, height; - bool isVisible_, isShowing; - int blinkRate; - Image image; - Font font; + Canvas parent; + int x, y, width, height; + bool isVisible_, isShowing; + int blinkRate; + Image image; + Font font; /** * Constructs a new instance of this class given its parent @@ -85,52 +85,52 @@ * @see Widget#getStyle */ public this (Canvas parent, int style) { - super (parent, style); - this.parent = parent; - createWidget (0); + super (parent, style); + this.parent = parent; + createWidget (0); } bool blinkCaret () { - if (!isVisible_) return true; - if (!isShowing) return showCaret (); - if (blinkRate is 0) return true; - return hideCaret (); + if (!isVisible_) return true; + if (!isShowing) return showCaret (); + if (blinkRate is 0) return true; + return hideCaret (); } void createWidget (int index) { - super.createWidget (index); - blinkRate = display.getCaretBlinkTime (); - isVisible_ = true; - if (parent.getCaret () is null) { - parent.setCaret (this); - } + super.createWidget (index); + blinkRate = display.getCaretBlinkTime (); + isVisible_ = true; + if (parent.getCaret () is null) { + parent.setCaret (this); + } } bool drawCaret () { - if (parent is null) return false; - if (parent.isDisposed ()) return false; - auto window = parent.paintWindow (); - auto gc = OS.gdk_gc_new (window); - GdkColor* color = new GdkColor (); - color.red = 0xffff; - color.green = 0xffff; - color.blue = 0xffff; - auto colormap = OS.gdk_colormap_get_system (); - OS.gdk_colormap_alloc_color (colormap, color, true, true); - OS.gdk_gc_set_foreground (gc, color); - OS.gdk_gc_set_function (gc, OS.GDK_XOR); - if (image !is null && !image.isDisposed() && image.mask is null) { - int width; int height; - OS.gdk_drawable_get_size(image.pixmap, &width, &height); - OS.gdk_draw_drawable(window, gc, image.pixmap, 0, 0, x, y, width, height); - } else { - int nWidth = width, nHeight = height; - if (nWidth <= 0) nWidth = 1; - OS.gdk_draw_rectangle (window, gc, 1, x, y, nWidth, nHeight); - } - OS.g_object_unref (gc); - OS.gdk_colormap_free_colors (colormap, color, 1); - return true; + if (parent is null) return false; + if (parent.isDisposed ()) return false; + auto window = parent.paintWindow (); + auto gc = OS.gdk_gc_new (window); + GdkColor* color = new GdkColor (); + color.red = 0xffff; + color.green = 0xffff; + color.blue = 0xffff; + auto colormap = OS.gdk_colormap_get_system (); + OS.gdk_colormap_alloc_color (colormap, color, true, true); + OS.gdk_gc_set_foreground (gc, color); + OS.gdk_gc_set_function (gc, OS.GDK_XOR); + if (image !is null && !image.isDisposed() && image.mask is null) { + int width; int height; + OS.gdk_drawable_get_size(image.pixmap, &width, &height); + OS.gdk_draw_drawable(window, gc, image.pixmap, 0, 0, x, y, width, height); + } else { + int nWidth = width, nHeight = height; + if (nWidth <= 0) nWidth = 1; + OS.gdk_draw_rectangle (window, gc, 1, x, y, nWidth, nHeight); + } + OS.g_object_unref (gc); + OS.gdk_colormap_free_colors (colormap, color, 1); + return true; } /** @@ -145,12 +145,12 @@ * */ public Rectangle getBounds () { - checkWidget(); - if (image !is null) { - Rectangle rect = image.getBounds (); - return new Rectangle (x, y, rect.width, rect.height); - } - return new Rectangle (x, y, width, height); + checkWidget(); + if (image !is null) { + Rectangle rect = image.getBounds (); + return new Rectangle (x, y, rect.width, rect.height); + } + return new Rectangle (x, y, width, height); } /** @@ -164,9 +164,9 @@ * */ public Font getFont () { - checkWidget(); - if (font !is null) return font; - return parent.getFont (); + checkWidget(); + if (font !is null) return font; + return parent.getFont (); } /** @@ -180,8 +180,8 @@ * */ public Image getImage () { - checkWidget(); - return image; + checkWidget(); + return image; } /** @@ -196,8 +196,8 @@ * */ public Point getLocation () { - checkWidget(); - return new Point (x, y); + checkWidget(); + return new Point (x, y); } /** @@ -211,8 +211,8 @@ * */ public Canvas getParent () { - checkWidget(); - return parent; + checkWidget(); + return parent; } /** @@ -226,12 +226,12 @@ * */ public Point getSize () { - checkWidget(); - if (image !is null) { - Rectangle rect = image.getBounds (); - return new Point (rect.width, rect.height); - } - return new Point (width, height); + checkWidget(); + if (image !is null) { + Rectangle rect = image.getBounds (); + return new Point (rect.width, rect.height); + } + return new Point (width, height); } /** @@ -252,14 +252,14 @@ * */ public bool getVisible () { - checkWidget(); - return isVisible_; + checkWidget(); + return isVisible_; } bool hideCaret () { - if (!isShowing) return true; - isShowing = false; - return drawCaret (); + if (!isShowing) return true; + isShowing = false; + return drawCaret (); } /** @@ -277,33 +277,33 @@ * @see #getVisible */ public bool isVisible () { - checkWidget(); - return isVisible_ && parent.isVisible () && parent.hasFocus (); + checkWidget(); + return isVisible_ && parent.isVisible () && parent.hasFocus (); } bool isFocusCaret () { - return this is display.currentCaret; + return this is display.currentCaret; } void killFocus () { - if (display.currentCaret !is this) return; - display.setCurrentCaret (null); - if (isVisible_) hideCaret (); + if (display.currentCaret !is this) return; + display.setCurrentCaret (null); + if (isVisible_) hideCaret (); } void releaseParent () { - super.releaseParent (); - if (this is parent.getCaret ()) parent.setCaret (null); + super.releaseParent (); + if (this is parent.getCaret ()) parent.setCaret (null); } void releaseWidget () { - super.releaseWidget (); - if (display.currentCaret is this) { - hideCaret (); - display.setCurrentCaret (null); - } - parent = null; - image = null; + super.releaseWidget (); + if (display.currentCaret is this) { + hideCaret (); + display.setCurrentCaret (null); + } + parent = null; + image = null; } /** @@ -323,14 +323,14 @@ * */ public void setBounds (int x, int y, int width, int height) { - checkWidget(); - if (this.x is x && this.y is y && this.width is width && this.height is height) return; - bool isFocus = isFocusCaret (); - if (isFocus && isVisible_) hideCaret (); - this.x = x; this.y = y; - this.width = width; this.height = height; - parent.updateCaret (); - if (isFocus && isVisible_) showCaret (); + checkWidget(); + if (this.x is x && this.y is y && this.width is width && this.height is height) return; + bool isFocus = isFocusCaret (); + if (isFocus && isVisible_) hideCaret (); + this.x = x; this.y = y; + this.width = width; this.height = height; + parent.updateCaret (); + if (isFocus && isVisible_) showCaret (); } /** @@ -347,15 +347,15 @@ * */ public void setBounds (Rectangle rect) { - checkWidget(); - if (rect is null) error (SWT.ERROR_NULL_ARGUMENT); - setBounds (rect.x, rect.y, rect.width, rect.height); + checkWidget(); + if (rect is null) error (SWT.ERROR_NULL_ARGUMENT); + setBounds (rect.x, rect.y, rect.width, rect.height); } void setFocus () { - if (display.currentCaret is this) return; - display.setCurrentCaret (this); - if (isVisible_) showCaret (); + if (display.currentCaret is this) return; + display.setCurrentCaret (this); + if (isVisible_) showCaret (); } /** @@ -374,11 +374,11 @@ * */ public void setFont (Font font) { - checkWidget(); - if (font !is null && font.isDisposed ()) { - error (SWT.ERROR_INVALID_ARGUMENT); - } - this.font = font; + checkWidget(); + if (font !is null && font.isDisposed ()) { + error (SWT.ERROR_INVALID_ARGUMENT); + } + this.font = font; } /** @@ -397,14 +397,14 @@ * */ public void setImage (Image image) { - checkWidget(); - if (image !is null && image.isDisposed ()) { - error (SWT.ERROR_INVALID_ARGUMENT); - } - bool isFocus = isFocusCaret (); - if (isFocus && isVisible_) hideCaret (); - this.image = image; - if (isFocus && isVisible_) showCaret (); + checkWidget(); + if (image !is null && image.isDisposed ()) { + error (SWT.ERROR_INVALID_ARGUMENT); + } + bool isFocus = isFocusCaret (); + if (isFocus && isVisible_) hideCaret (); + this.image = image; + if (isFocus && isVisible_) showCaret (); } /** @@ -421,8 +421,8 @@ * */ public void setLocation (int x, int y) { - checkWidget(); - setBounds (x, y, width, height); + checkWidget(); + setBounds (x, y, width, height); } /** @@ -438,9 +438,9 @@ * */ public void setLocation (Point location) { - checkWidget(); - if (location is null) error (SWT.ERROR_NULL_ARGUMENT); - setLocation (location.x, location.y); + checkWidget(); + if (location is null) error (SWT.ERROR_NULL_ARGUMENT); + setLocation (location.x, location.y); } /** @@ -455,8 +455,8 @@ * */ public void setSize (int width, int height) { - checkWidget(); - setBounds (x, y, width, height); + checkWidget(); + setBounds (x, y, width, height); } /** @@ -473,9 +473,9 @@ * */ public void setSize (Point size) { - checkWidget(); - if (size is null) error (SWT.ERROR_NULL_ARGUMENT); - setSize (size.x, size.y); + checkWidget(); + if (size is null) error (SWT.ERROR_NULL_ARGUMENT); + setSize (size.x, size.y); } /** @@ -495,21 +495,21 @@ * */ public void setVisible (bool visible) { - checkWidget(); - if (visible is isVisible_) return; - isVisible_ = visible; - if (!isFocusCaret ()) return; - if (isVisible_) { - showCaret (); - } else { - hideCaret (); - } + checkWidget(); + if (visible is isVisible_) return; + isVisible_ = visible; + if (!isFocusCaret ()) return; + if (isVisible_) { + showCaret (); + } else { + hideCaret (); + } } bool showCaret () { - if (isShowing) return true; - isShowing = true; - return drawCaret (); + if (isShowing) return true; + isShowing = true; + return drawCaret (); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/widgets/Composite.d --- a/dwt/widgets/Composite.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/widgets/Composite.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -61,17 +61,17 @@ * @see Canvas */ public class Composite : Scrollable { - public int embeddedHandle; - GtkIMContext* imHandle_; + public int embeddedHandle; + GtkIMContext* imHandle_; GtkWidget* socketHandle; - Layout layout_; - Control[] tabList; - int layoutCount, backgroundMode; + Layout layout_; + Control[] tabList; + int layoutCount, backgroundMode; - static const char[] NO_INPUT_METHOD = "dwt.internal.gtk.noInputMethod"; //$NON-NLS-1$ + static const char[] NO_INPUT_METHOD = "dwt.internal.gtk.noInputMethod"; //$NON-NLS-1$ this () { - /* Do nothing */ + /* Do nothing */ } /** @@ -105,52 +105,52 @@ * @see Widget#getStyle */ public this (Composite parent, int style) { - super (parent, style); + super (parent, style); } Control [] _getChildren () { - auto parentHandle = parentingHandle (); - auto list = OS.gtk_container_get_children (cast(GtkContainer*)parentHandle); - if (list is null) return new Control [0]; - int count = OS.g_list_length (list); - Control [] children = new Control [count]; - int i = 0; - auto temp = list; - while (temp !is null) { - auto handle = cast(GtkWidget*)OS.g_list_data (temp); - if (handle !is null) { - Widget widget = display.getWidget (handle); - if (widget !is null && widget !is this) { - if (auto c = cast(Control)widget) { - children [i++] = c; - } - } - } - temp = cast(GList*)OS.g_list_next (temp); - } - OS.g_list_free (list); - if (i is count) return children; - Control [] newChildren = new Control [i]; - System.arraycopy (children, 0, newChildren, 0, i); - return newChildren; + auto parentHandle = parentingHandle (); + auto list = OS.gtk_container_get_children (cast(GtkContainer*)parentHandle); + if (list is null) return new Control [0]; + int count = OS.g_list_length (list); + Control [] children = new Control [count]; + int i = 0; + auto temp = list; + while (temp !is null) { + auto handle = cast(GtkWidget*)OS.g_list_data (temp); + if (handle !is null) { + Widget widget = display.getWidget (handle); + if (widget !is null && widget !is this) { + if (auto c = cast(Control)widget) { + children [i++] = c; + } + } + } + temp = cast(GList*)OS.g_list_next (temp); + } + OS.g_list_free (list); + if (i is count) return children; + Control [] newChildren = new Control [i]; + System.arraycopy (children, 0, newChildren, 0, i); + return newChildren; } Control [] _getTabList () { - if (tabList is null) return tabList; - int count = 0; - for (int i=0; i 0 ? this : parent.findDeferredControl (); + return layoutCount > 0 ? this : parent.findDeferredControl (); } override Menu [] findMenus (Control control) { - if (control is this) return new Menu [0]; - Menu result [] = super.findMenus (control); - Control [] children = _getChildren (); - for (int i=0; i {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); - if ((state & CANVAS) !is 0) return; - auto parentHandle = parentingHandle (); - auto parentWindow = OS.GTK_WIDGET_WINDOW (cast(GtkWidget*)parentHandle); - if (parentWindow is null) return; - GObject* userData; - auto windowList = OS.gdk_window_get_children (parentWindow); - if (windowList !is null) { - auto windows = windowList; - while (windows !is null) { - auto window = cast(GdkDrawable*)OS.g_list_data (windows); - if (window !is redrawWindow) { - OS.gdk_window_get_user_data (window, cast(void**)&userData); - if (userData is null || OS.G_OBJECT_TYPE (cast(GTypeInstance*)userData) !is display.gtk_fixed_get_type ()) { - OS.gdk_window_lower (window); - } - } - windows = cast(GList*)OS.g_list_next (windows); - } - OS.g_list_free (windowList); - } + if ((state & CANVAS) !is 0) return; + auto parentHandle = parentingHandle (); + auto parentWindow = OS.GTK_WIDGET_WINDOW (cast(GtkWidget*)parentHandle); + if (parentWindow is null) return; + GObject* userData; + auto windowList = OS.gdk_window_get_children (parentWindow); + if (windowList !is null) { + auto windows = windowList; + while (windows !is null) { + auto window = cast(GdkDrawable*)OS.g_list_data (windows); + if (window !is redrawWindow) { + OS.gdk_window_get_user_data (window, cast(void**)&userData); + if (userData is null || OS.G_OBJECT_TYPE (cast(GTypeInstance*)userData) !is display.gtk_fixed_get_type ()) { + OS.gdk_window_lower (window); + } + } + windows = cast(GList*)OS.g_list_next (windows); + } + OS.g_list_free (windowList); + } Stdout.formatln( "{}: parent.fixZOrder gtk_container_get_children {:x}", __LINE__, parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); } override GtkWidget* focusHandle () { - if (socketHandle !is null) return socketHandle; - return super.focusHandle (); + if (socketHandle !is null) return socketHandle; + return super.focusHandle (); } override bool forceFocus (GtkWidget* focusHandle) { - if (socketHandle !is null) OS.GTK_WIDGET_SET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); - bool result = super.forceFocus (focusHandle); - if (socketHandle !is null) OS.GTK_WIDGET_UNSET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); - return result; + if (socketHandle !is null) OS.GTK_WIDGET_SET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); + bool result = super.forceFocus (focusHandle); + if (socketHandle !is null) OS.GTK_WIDGET_UNSET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); + return result; } /** @@ -518,8 +518,8 @@ * @since 3.2 */ public int getBackgroundMode () { - checkWidget (); - return backgroundMode; + checkWidget (); + return backgroundMode; } /** @@ -544,35 +544,35 @@ * */ public Control [] getChildren () { - checkWidget(); - return _getChildren (); + checkWidget(); + return _getChildren (); } int getChildrenCount () { - /* - * NOTE: The current implementation will count - * non-registered children. - */ - auto list = OS.gtk_container_get_children (cast(GtkContainer*)handle); - if (list is null) return 0; - int count = OS.g_list_length (list); - OS.g_list_free (list); - return count; + /* + * NOTE: The current implementation will count + * non-registered children. + */ + auto list = OS.gtk_container_get_children (cast(GtkContainer*)handle); + if (list is null) return 0; + int count = OS.g_list_length (list); + OS.g_list_free (list); + return count; } override public Rectangle getClientArea () { - checkWidget(); - if ((state & CANVAS) !is 0) { - if ((state & ZERO_WIDTH) !is 0 && (state & ZERO_HEIGHT) !is 0) { - return new Rectangle (0, 0, 0, 0); - } - forceResize (); - auto clientHandle = clientHandle (); - int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (clientHandle); - int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (clientHandle); - return new Rectangle (0, 0, width, height); - } - return super.getClientArea(); + checkWidget(); + if ((state & CANVAS) !is 0) { + if ((state & ZERO_WIDTH) !is 0 && (state & ZERO_HEIGHT) !is 0) { + return new Rectangle (0, 0, 0, 0); + } + forceResize (); + auto clientHandle = clientHandle (); + int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (clientHandle); + int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (clientHandle); + return new Rectangle (0, 0, width, height); + } + return super.getClientArea(); } /** @@ -587,8 +587,8 @@ * */ public Layout getLayout () { - checkWidget(); - return layout_; + checkWidget(); + return layout_; } /** @@ -608,8 +608,8 @@ * @since 3.1 */ public bool getLayoutDeferred () { - checkWidget (); - return layoutCount > 0 ; + checkWidget (); + return layoutCount > 0 ; } /** @@ -625,160 +625,160 @@ * @see #setTabList */ public Control [] getTabList () { - checkWidget (); - Control [] tabList = _getTabList (); - if (tabList is null) { - int count = 0; - Control [] list =_getChildren (); - for (int i=0; i */ public void layout () { - checkWidget (); - layout (true); + checkWidget (); + layout (true); } /** @@ -865,9 +865,9 @@ * */ public void layout (bool changed) { - checkWidget (); - if (layout_ is null) return; - layout (changed, false); + checkWidget (); + if (layout_ is null) return; + layout (changed, false); } /** @@ -906,10 +906,10 @@ * @since 3.1 */ public void layout (bool changed, bool all) { - checkWidget (); - if (layout_ is null && !all) return; - markLayout (changed, all); - updateLayout (all); + checkWidget (); + if (layout_ is null && !all) return; + markLayout (changed, all); + updateLayout (all); } /** @@ -941,223 +941,208 @@ * @since 3.1 */ public void layout (Control [] changed) { - checkWidget (); - if (changed is null) error (SWT.ERROR_INVALID_ARGUMENT); - for (int i=0; i=0; i--) { - update [i].updateLayout (false); - } + checkWidget (); + if (changed is null) error (SWT.ERROR_INVALID_ARGUMENT); + for (int i=0; i=0; i--) { + update [i].updateLayout (false); + } } override void markLayout (bool changed, bool all) { - if (layout_ !is null) { - state |= LAYOUT_NEEDED; - if (changed) state |= LAYOUT_CHANGED; - } - if (all) { - Control [] children = _getChildren (); - for (int i=0; i {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); - while (temp !is null) { - Stdout.formatln( "{}: loop start {}->{}", __LINE__, temp, cast(void*)temp.data ); - data = (*temp).data; - widget = cast(GtkWidget*) data; - if (child is widget) { - Stdout.formatln( "{}: child is widget", __LINE__ ); - childLink = temp; - childData = data; - } else if (sibling is widget) { - Stdout.formatln( "{}: sibling is widget", __LINE__ ); - siblingLink = temp; - } - if (childData !is null && (sibling is null || siblingLink !is null)) break; - temp = OS.g_list_next(temp); - Stdout.formatln( "{}: loop end", __LINE__ ); - } - Stdout.formatln( "{}: after loop childLink={}", __LINE__, childLink ); - children = OS.g_list_remove_link (children, childLink); - if (siblingLink is null || OS.g_list_next(siblingLink) is null) { - OS.g_list_free_1 (childLink); - Stdout.formatln( "{}: parent.moveBelow gtk_container_get_children {:x}", __LINE__, parentingHandle() ); - Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); - Stdout.formatln( " {} {}", children, childData ); - children = OS.g_list_append (children, childData); - Stdout.formatln( "{}: parent.moveBelow gtk_container_get_children {:x}", __LINE__, parentingHandle() ); - Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); - } else { - Stdout.formatln( "{}: parent.moveBelow gtk_container_get_children {:x}", __LINE__, parentingHandle() ); - Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); - temp = OS.g_list_next( siblingLink ); + if (child is sibling) return; + auto parentHandle = parentingHandle (); + if (sibling is null && cast(GtkWidget*)parentHandle is cast(GtkWidget*)fixedHandle) { + moveAbove (child, scrolledHandle !is null ? cast(GtkWidget*)scrolledHandle : handle); + return; + } + auto fixed = cast(GtkFixed*)parentHandle; + GList* children = fixed.children; + if (children is null) return; + void* data; + GtkWidget* widget; + void* childData; + GList* childLink; + GList* siblingLink; + GList* temp = children; + while (temp !is null) { + data = temp.data; + widget = *cast(GtkWidget**) temp.data; + if (child is widget) { + childLink = temp; + childData = data; + } else if (sibling is widget) { + siblingLink = temp; + } + if (childData !is null && (sibling is null || siblingLink !is null)) break; + temp = OS.g_list_next(temp); + } + children = OS.g_list_remove_link (children, childLink); + if (siblingLink is null || OS.g_list_next(siblingLink) is null) { + OS.g_list_free_1 (childLink); + children = OS.g_list_append (children, childData); + } else { + temp = OS.g_list_next( siblingLink ); OS.g_list_set_next (childLink, temp); OS.g_list_set_previous (temp, childLink); OS.g_list_set_previous (childLink, siblingLink); OS.g_list_set_next (siblingLink, childLink); - } - fixed.children = children; + } + fixed.children = children; parentHandle = cast(GtkWidget*)fixed; - Stdout.formatln( "{}: parent.moveBelow gtk_container_get_children {:x}", __LINE__, parentingHandle() ); - Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentingHandle()) ); } Point minimumSize (int wHint, int hHint, bool changed) { - Control [] children = _getChildren (); - int width = 0, height = 0; - for (int i=0; i */ public void setLayout (Layout layout) { - checkWidget(); - this.layout_ = layout; + checkWidget(); + this.layout_ = layout; } /** @@ -1245,49 +1230,49 @@ * @since 3.1 */ public void setLayoutDeferred (bool defer) { - if (!defer) { - if (--layoutCount is 0) { - if ((state & LAYOUT_CHILD) !is 0 || (state & LAYOUT_NEEDED) !is 0) { - updateLayout (true); - } - } - } else { - layoutCount++; - } + if (!defer) { + if (--layoutCount is 0) { + if ((state & LAYOUT_CHILD) !is 0 || (state & LAYOUT_NEEDED) !is 0) { + updateLayout (true); + } + } + } else { + layoutCount++; + } } override bool setScrollBarVisible (ScrollBar bar, bool visible) { - bool changed = super.setScrollBarVisible (bar, visible); - if (changed && layout_ !is null) { - markLayout (false, false); - updateLayout (false); - } - return changed; + bool changed = super.setScrollBarVisible (bar, visible); + if (changed && layout_ !is null) { + markLayout (false, false); + updateLayout (false); + } + return changed; } override bool setTabGroupFocus (bool next) { - if (isTabItem ()) return setTabItemFocus (next); - bool takeFocus = (style & SWT.NO_FOCUS) is 0; - if ((state & CANVAS) !is 0) takeFocus = hooksKeys (); - if (socketHandle !is null) takeFocus = true; - if (takeFocus && setTabItemFocus (next)) return true; - Control [] children = _getChildren (); - for (int i=0; i */ public void setTabList (Control [] tabList) { - checkWidget (); - if (tabList !is null) { - for (int i=0; i */ public abstract class Control : Widget, Drawable { - GtkWidget* fixedHandle; - GdkWindow* redrawWindow; + GtkWidget* fixedHandle; + GdkWindow* redrawWindow; GdkWindow* enableWindow; - int drawCount; - Composite parent; - Cursor cursor; - Menu menu; - Image backgroundImage; - Font font; - char[] toolTipText; - Object layoutData; - Accessible accessible; + int drawCount; + Composite parent; + Cursor cursor; + Menu menu; + Image backgroundImage; + Font font; + char[] toolTipText; + Object layoutData; + Accessible accessible; this () { } @@ -121,202 +121,202 @@ * @see Widget#getStyle */ public this (Composite parent, int style) { - super (parent, style); - this.parent = parent; - createWidget (0); + super (parent, style); + this.parent = parent; + createWidget (0); } PangoFontDescription* defaultFont () { - return display.getSystemFont ().handle; + return display.getSystemFont ().handle; } override void deregister () { - super.deregister (); - if (fixedHandle !is null) display.removeWidget (fixedHandle); - auto imHandle = imHandle (); - if (imHandle !is null) display.removeWidget (cast(GtkWidget*)imHandle); + super.deregister (); + if (fixedHandle !is null) display.removeWidget (fixedHandle); + auto imHandle = imHandle (); + if (imHandle !is null) display.removeWidget (cast(GtkWidget*)imHandle); } bool drawGripper (int x, int y, int width, int height, bool vertical) { - auto paintHandle = paintHandle (); - auto window = OS.GTK_WIDGET_WINDOW (paintHandle); - if (window is null) return false; - int orientation = vertical ? OS.GTK_ORIENTATION_HORIZONTAL : OS.GTK_ORIENTATION_VERTICAL; + auto paintHandle = paintHandle (); + auto window = OS.GTK_WIDGET_WINDOW (paintHandle); + if (window is null) return false; + int orientation = vertical ? OS.GTK_ORIENTATION_HORIZONTAL : OS.GTK_ORIENTATION_VERTICAL; char dummy; - OS.gtk_paint_handle (OS.gtk_widget_get_style (paintHandle), window, OS.GTK_STATE_NORMAL, OS.GTK_SHADOW_OUT, null, paintHandle, &dummy, x, y, width, height, orientation); - return true; + OS.gtk_paint_handle (OS.gtk_widget_get_style (paintHandle), window, OS.GTK_STATE_NORMAL, OS.GTK_SHADOW_OUT, null, paintHandle, &dummy, x, y, width, height, orientation); + return true; } void enableWidget (bool enabled) { - OS.gtk_widget_set_sensitive (handle, enabled); + OS.gtk_widget_set_sensitive (handle, enabled); } GtkWidget* enterExitHandle () { - return eventHandle (); + return eventHandle (); } GtkWidget* eventHandle () { - return handle; + return handle; } GdkWindow* eventWindow () { - auto eventHandle = eventHandle (); - OS.gtk_widget_realize (eventHandle); - return OS.GTK_WIDGET_WINDOW (eventHandle); + auto eventHandle = eventHandle (); + OS.gtk_widget_realize (eventHandle); + return OS.GTK_WIDGET_WINDOW (eventHandle); } void fixFocus (Control focusControl) { - Shell shell = getShell (); - Control control = this; - while (control !is shell && (control = control.parent) !is null) { - if (control.setFocus ()) return; - } - shell.setSavedFocus (focusControl); - auto focusHandle = shell.vboxHandle; - OS.GTK_WIDGET_SET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); - OS.gtk_widget_grab_focus (focusHandle); - OS.GTK_WIDGET_UNSET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); + Shell shell = getShell (); + Control control = this; + while (control !is shell && (control = control.parent) !is null) { + if (control.setFocus ()) return; + } + shell.setSavedFocus (focusControl); + auto focusHandle = shell.vboxHandle; + OS.GTK_WIDGET_SET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); + OS.gtk_widget_grab_focus (focusHandle); + OS.GTK_WIDGET_UNSET_FLAGS (focusHandle, OS.GTK_CAN_FOCUS); } public void fixStyle () { - if (fixedHandle !is null) fixStyle (fixedHandle); + if (fixedHandle !is null) fixStyle (fixedHandle); } void fixStyle (GtkWidget* handle) { - /* - * Feature in GTK. Some GTK themes apply a different background to - * the contents of a GtkNotebook. However, in an SWT TabFolder, the - * children are not parented below the GtkNotebook widget, and usually - * have their own GtkFixed. The fix is to look up the correct style - * for a child of a GtkNotebook and apply its background to any GtkFixed - * widgets that are direct children of an SWT TabFolder. - * - * Note that this has to be when the theme settings changes and that it - * should not override the application background. - */ - if ((state & BACKGROUND) !is 0) return; - auto childStyle = parent.childStyle (); - if (childStyle !is null) { - GdkColor color; - OS.gtk_style_get_bg (childStyle, 0, &color); - OS.gtk_widget_modify_bg (handle, 0, &color); - } + /* + * Feature in GTK. Some GTK themes apply a different background to + * the contents of a GtkNotebook. However, in an SWT TabFolder, the + * children are not parented below the GtkNotebook widget, and usually + * have their own GtkFixed. The fix is to look up the correct style + * for a child of a GtkNotebook and apply its background to any GtkFixed + * widgets that are direct children of an SWT TabFolder. + * + * Note that this has to be when the theme settings changes and that it + * should not override the application background. + */ + if ((state & BACKGROUND) !is 0) return; + auto childStyle = parent.childStyle (); + if (childStyle !is null) { + GdkColor color; + OS.gtk_style_get_bg (childStyle, 0, &color); + OS.gtk_widget_modify_bg (handle, 0, &color); + } } GtkWidget* focusHandle () { - return handle; + return handle; } GtkWidget* fontHandle () { - return handle; + return handle; } bool hasFocus () { - return this is display.getFocusControl(); + return this is display.getFocusControl(); } override void hookEvents () { - /* Connect the keyboard signals */ - auto focusHandle = focusHandle (); - int focusMask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | OS.GDK_FOCUS_CHANGE_MASK; - OS.gtk_widget_add_events (focusHandle, focusMask); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [POPUP_MENU], 0, display.closures [POPUP_MENU], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [SHOW_HELP], 0, display.closures [SHOW_HELP], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_PRESS_EVENT], 0, display.closures [KEY_PRESS_EVENT], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_RELEASE_EVENT], 0, display.closures [KEY_RELEASE_EVENT], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS], 0, display.closures [FOCUS], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_IN_EVENT], 0, display.closures [FOCUS_IN_EVENT], false); - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_OUT_EVENT], 0, display.closures [FOCUS_OUT_EVENT], false); - - /* Connect the mouse signals */ - auto eventHandle = eventHandle (); - int eventMask = OS.GDK_POINTER_MOTION_MASK | OS.GDK_BUTTON_PRESS_MASK | - OS.GDK_BUTTON_RELEASE_MASK; - OS.gtk_widget_add_events (eventHandle, eventMask); - OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT], false); - OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT], false); - OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT], false); - OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [SCROLL_EVENT], 0, display.closures [SCROLL_EVENT], false); - - /* Connect enter/exit signals */ - auto enterExitHandle = enterExitHandle (); - int enterExitMask = OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK; - OS.gtk_widget_add_events (enterExitHandle, enterExitMask); - OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [ENTER_NOTIFY_EVENT], 0, display.closures [ENTER_NOTIFY_EVENT], false); - OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [LEAVE_NOTIFY_EVENT], 0, display.closures [LEAVE_NOTIFY_EVENT], false); - - /* - * Feature in GTK. Events such as mouse move are propagate up - * the widget hierarchy and are seen by the parent. This is the - * correct GTK behavior but not correct for SWT. The fix is to - * hook a signal after and stop the propagation using a negative - * event number to distinguish this case. - * - * The signal is hooked to the fixedHandle to catch events sent to - * lightweight widgets. - */ - auto blockHandle = fixedHandle !is null ? fixedHandle : eventHandle; - OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT_INVERSE], true); - OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT_INVERSE], true); - OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT_INVERSE], true); - - /* Connect the event_after signal for both key and mouse */ - OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); - if (focusHandle !is eventHandle) { - OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); - } - - /* Connect the paint signal */ - auto paintHandle = paintHandle (); - int paintMask = OS.GDK_EXPOSURE_MASK | OS.GDK_VISIBILITY_NOTIFY_MASK; - OS.gtk_widget_add_events (paintHandle, paintMask); - OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT_INVERSE], false); - OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [VISIBILITY_NOTIFY_EVENT], 0, display.closures [VISIBILITY_NOTIFY_EVENT], false); - OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT], true); - - /* Connect the Input Method signals */ - OS.g_signal_connect_closure_by_id (handle, display.signalIds [REALIZE], 0, display.closures [REALIZE], true); - OS.g_signal_connect_closure_by_id (handle, display.signalIds [UNREALIZE], 0, display.closures [UNREALIZE], false); - auto imHandle = imHandle (); - if (imHandle !is null) { - OS.g_signal_connect_closure (imHandle, OS.commit.ptr, display.closures [COMMIT], false); - OS.g_signal_connect_closure (imHandle, OS.preedit_changed.ptr, display.closures [PREEDIT_CHANGED], false); - } - - OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [STYLE_SET], 0, display.closures [STYLE_SET], false); - - auto topHandle = topHandle (); - OS.g_signal_connect_closure_by_id (topHandle, display.signalIds [MAP], 0, display.closures [MAP], true); + /* Connect the keyboard signals */ + auto focusHandle = focusHandle (); + int focusMask = OS.GDK_KEY_PRESS_MASK | OS.GDK_KEY_RELEASE_MASK | OS.GDK_FOCUS_CHANGE_MASK; + OS.gtk_widget_add_events (focusHandle, focusMask); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [POPUP_MENU], 0, display.closures [POPUP_MENU], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [SHOW_HELP], 0, display.closures [SHOW_HELP], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_PRESS_EVENT], 0, display.closures [KEY_PRESS_EVENT], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [KEY_RELEASE_EVENT], 0, display.closures [KEY_RELEASE_EVENT], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS], 0, display.closures [FOCUS], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_IN_EVENT], 0, display.closures [FOCUS_IN_EVENT], false); + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [FOCUS_OUT_EVENT], 0, display.closures [FOCUS_OUT_EVENT], false); + + /* Connect the mouse signals */ + auto eventHandle = eventHandle (); + int eventMask = OS.GDK_POINTER_MOTION_MASK | OS.GDK_BUTTON_PRESS_MASK | + OS.GDK_BUTTON_RELEASE_MASK; + OS.gtk_widget_add_events (eventHandle, eventMask); + OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT], false); + OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT], false); + OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT], false); + OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [SCROLL_EVENT], 0, display.closures [SCROLL_EVENT], false); + + /* Connect enter/exit signals */ + auto enterExitHandle = enterExitHandle (); + int enterExitMask = OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK; + OS.gtk_widget_add_events (enterExitHandle, enterExitMask); + OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [ENTER_NOTIFY_EVENT], 0, display.closures [ENTER_NOTIFY_EVENT], false); + OS.g_signal_connect_closure_by_id (enterExitHandle, display.signalIds [LEAVE_NOTIFY_EVENT], 0, display.closures [LEAVE_NOTIFY_EVENT], false); + + /* + * Feature in GTK. Events such as mouse move are propagate up + * the widget hierarchy and are seen by the parent. This is the + * correct GTK behavior but not correct for SWT. The fix is to + * hook a signal after and stop the propagation using a negative + * event number to distinguish this case. + * + * The signal is hooked to the fixedHandle to catch events sent to + * lightweight widgets. + */ + auto blockHandle = fixedHandle !is null ? fixedHandle : eventHandle; + OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_PRESS_EVENT], 0, display.closures [BUTTON_PRESS_EVENT_INVERSE], true); + OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [BUTTON_RELEASE_EVENT], 0, display.closures [BUTTON_RELEASE_EVENT_INVERSE], true); + OS.g_signal_connect_closure_by_id (blockHandle, display.signalIds [MOTION_NOTIFY_EVENT], 0, display.closures [MOTION_NOTIFY_EVENT_INVERSE], true); + + /* Connect the event_after signal for both key and mouse */ + OS.g_signal_connect_closure_by_id (eventHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); + if (focusHandle !is eventHandle) { + OS.g_signal_connect_closure_by_id (focusHandle, display.signalIds [EVENT_AFTER], 0, display.closures [EVENT_AFTER], false); + } + + /* Connect the paint signal */ + auto paintHandle = paintHandle (); + int paintMask = OS.GDK_EXPOSURE_MASK | OS.GDK_VISIBILITY_NOTIFY_MASK; + OS.gtk_widget_add_events (paintHandle, paintMask); + OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT_INVERSE], false); + OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [VISIBILITY_NOTIFY_EVENT], 0, display.closures [VISIBILITY_NOTIFY_EVENT], false); + OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [EXPOSE_EVENT], 0, display.closures [EXPOSE_EVENT], true); + + /* Connect the Input Method signals */ + OS.g_signal_connect_closure_by_id (handle, display.signalIds [REALIZE], 0, display.closures [REALIZE], true); + OS.g_signal_connect_closure_by_id (handle, display.signalIds [UNREALIZE], 0, display.closures [UNREALIZE], false); + auto imHandle = imHandle (); + if (imHandle !is null) { + OS.g_signal_connect_closure (imHandle, OS.commit.ptr, display.closures [COMMIT], false); + OS.g_signal_connect_closure (imHandle, OS.preedit_changed.ptr, display.closures [PREEDIT_CHANGED], false); + } + + OS.g_signal_connect_closure_by_id (paintHandle, display.signalIds [STYLE_SET], 0, display.closures [STYLE_SET], false); + + auto topHandle = topHandle (); + OS.g_signal_connect_closure_by_id (topHandle, display.signalIds [MAP], 0, display.closures [MAP], true); } override int /*long*/ hoverProc (GtkWidget* widget) { - int x, y; + int x, y; int mask; - OS.gdk_window_get_pointer (null, &x, &y, &mask); - sendMouseEvent (SWT.MouseHover, 0, /*time*/0, x , y , false, mask ); - /* Always return zero in order to cancel the hover timer */ - return 0; + OS.gdk_window_get_pointer (null, &x, &y, &mask); + sendMouseEvent (SWT.MouseHover, 0, /*time*/0, x , y , false, mask ); + /* Always return zero in order to cancel the hover timer */ + return 0; } override GtkWidget* topHandle() { - if (fixedHandle !is null) return fixedHandle; - return super.topHandle (); + if (fixedHandle !is null) return fixedHandle; + return super.topHandle (); } GtkWidget* paintHandle () { - auto topHandle = topHandle (); - auto paintHandle = handle; - while (paintHandle !is topHandle) { - if ((OS.GTK_WIDGET_FLAGS (paintHandle) & OS.GTK_NO_WINDOW) is 0) break; - paintHandle = OS.gtk_widget_get_parent (paintHandle); - } - return paintHandle; + auto topHandle = topHandle (); + auto paintHandle = handle; + while (paintHandle !is topHandle) { + if ((OS.GTK_WIDGET_FLAGS (paintHandle) & OS.GTK_NO_WINDOW) is 0) break; + paintHandle = OS.gtk_widget_get_parent (paintHandle); + } + return paintHandle; } override GdkWindow* paintWindow () { - auto paintHandle = paintHandle (); - OS.gtk_widget_realize (paintHandle); - return OS.GTK_WIDGET_WINDOW (paintHandle); + auto paintHandle = paintHandle (); + OS.gtk_widget_realize (paintHandle); + return OS.GTK_WIDGET_WINDOW (paintHandle); } /** @@ -347,87 +347,87 @@ * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint) { - return computeSize (wHint, hHint, true); + return computeSize (wHint, hHint, true); } Control computeTabGroup () { - if (isTabGroup()) return this; - return parent.computeTabGroup (); + if (isTabGroup()) return this; + return parent.computeTabGroup (); } Control[] computeTabList() { - if (isTabGroup()) { - if (getVisible() && getEnabled()) { - return [this]; - } - } - return new Control[0]; + if (isTabGroup()) { + if (getVisible() && getEnabled()) { + return [this]; + } + } + return new Control[0]; } Control computeTabRoot () { - Control[] tabList = parent._getTabList(); - if (tabList !is null) { - int index = 0; - while (index < tabList.length) { - if (tabList [index] is this) break; - index++; - } - if (index is tabList.length) { - if (isTabGroup ()) return this; - } - } - return parent.computeTabRoot (); + Control[] tabList = parent._getTabList(); + if (tabList !is null) { + int index = 0; + while (index < tabList.length) { + if (tabList [index] is this) break; + index++; + } + if (index is tabList.length) { + if (isTabGroup ()) return this; + } + } + return parent.computeTabRoot (); } void checkBuffered () { - style |= SWT.DOUBLE_BUFFERED; + style |= SWT.DOUBLE_BUFFERED; } void checkBackground () { - Shell shell = getShell (); - if (this is shell) return; - state &= ~PARENT_BACKGROUND; - Composite composite = parent; - do { - int mode = composite.backgroundMode; - if (mode !is SWT.INHERIT_NONE) { - if (mode is SWT.INHERIT_DEFAULT) { - Control control = this; - do { - if ((control.state & THEME_BACKGROUND) is 0) { - return; - } - control = control.parent; - } while (control !is composite); - } - state |= PARENT_BACKGROUND; - return; - } - if (composite is shell) break; - composite = composite.parent; - } while (true); + Shell shell = getShell (); + if (this is shell) return; + state &= ~PARENT_BACKGROUND; + Composite composite = parent; + do { + int mode = composite.backgroundMode; + if (mode !is SWT.INHERIT_NONE) { + if (mode is SWT.INHERIT_DEFAULT) { + Control control = this; + do { + if ((control.state & THEME_BACKGROUND) is 0) { + return; + } + control = control.parent; + } while (control !is composite); + } + state |= PARENT_BACKGROUND; + return; + } + if (composite is shell) break; + composite = composite.parent; + } while (true); } void checkBorder () { - if (getBorderWidth () is 0) style &= ~SWT.BORDER; + if (getBorderWidth () is 0) style &= ~SWT.BORDER; } GtkStyle* childStyle () { - return parent.childStyle (); + return parent.childStyle (); } override void createWidget (int index) { - state |= DRAG_DETECT; - checkOrientation (parent); - super.createWidget (index); - checkBackground (); - if ((state & PARENT_BACKGROUND) !is 0) setBackground (); - checkBuffered (); - showWidget (); - setInitialBounds (); - setZOrder (null, false, false); - setRelations (); - checkBorder (); + state |= DRAG_DETECT; + checkOrientation (parent); + super.createWidget (index); + checkBackground (); + if ((state & PARENT_BACKGROUND) !is 0) setBackground (); + checkBuffered (); + showWidget (); + setInitialBounds (); + setZOrder (null, false, false); + setRelations (); + checkBorder (); } /** @@ -465,47 +465,47 @@ * @see "computeTrim, getClientArea for controls that implement them" */ public Point computeSize (int wHint, int hHint, bool changed) { - checkWidget(); - if (wHint !is SWT.DEFAULT && wHint < 0) wHint = 0; - if (hHint !is SWT.DEFAULT && hHint < 0) hHint = 0; - return computeNativeSize (handle, wHint, hHint, changed); + checkWidget(); + if (wHint !is SWT.DEFAULT && wHint < 0) wHint = 0; + if (hHint !is SWT.DEFAULT && hHint < 0) hHint = 0; + return computeNativeSize (handle, wHint, hHint, changed); } Point computeNativeSize (GtkWidget* h, int wHint, int hHint, bool changed) { - int width = wHint, height = hHint; - if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { - GtkRequisition requisition; - gtk_widget_size_request (h, &requisition); - width = OS.GTK_WIDGET_REQUISITION_WIDTH (h); - height = OS.GTK_WIDGET_REQUISITION_HEIGHT (h); - } else if (wHint is SWT.DEFAULT || hHint is SWT.DEFAULT) { - int reqWidth, reqHeight; - OS.gtk_widget_get_size_request (h, &reqWidth, &reqHeight); - OS.gtk_widget_set_size_request (h, wHint, hHint); - GtkRequisition requisition; - gtk_widget_size_request (h, &requisition); - OS.gtk_widget_set_size_request (h, reqWidth, reqHeight); - width = wHint is SWT.DEFAULT ? requisition.width : wHint; - height = hHint is SWT.DEFAULT ? requisition.height : hHint; - } - return new Point (width, height); + int width = wHint, height = hHint; + if (wHint is SWT.DEFAULT && hHint is SWT.DEFAULT) { + GtkRequisition requisition; + gtk_widget_size_request (h, &requisition); + width = OS.GTK_WIDGET_REQUISITION_WIDTH (h); + height = OS.GTK_WIDGET_REQUISITION_HEIGHT (h); + } else if (wHint is SWT.DEFAULT || hHint is SWT.DEFAULT) { + int reqWidth, reqHeight; + OS.gtk_widget_get_size_request (h, &reqWidth, &reqHeight); + OS.gtk_widget_set_size_request (h, wHint, hHint); + GtkRequisition requisition; + gtk_widget_size_request (h, &requisition); + OS.gtk_widget_set_size_request (h, reqWidth, reqHeight); + width = wHint is SWT.DEFAULT ? requisition.width : wHint; + height = hHint is SWT.DEFAULT ? requisition.height : hHint; + } + return new Point (width, height); } void forceResize () { - /* - * Force size allocation on all children of this widget's - * topHandle. Note that all calls to gtk_widget_size_allocate() - * must be preceded by a call to gtk_widget_size_request(). - */ - auto topHandle = topHandle (); - GtkRequisition requisition; - gtk_widget_size_request (topHandle, &requisition); - GtkAllocation allocation; - allocation.x = OS.GTK_WIDGET_X (topHandle); - allocation.y = OS.GTK_WIDGET_Y (topHandle); - allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); - allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); - OS.gtk_widget_size_allocate (topHandle, &allocation); + /* + * Force size allocation on all children of this widget's + * topHandle. Note that all calls to gtk_widget_size_allocate() + * must be preceded by a call to gtk_widget_size_request(). + */ + auto topHandle = topHandle (); + GtkRequisition requisition; + gtk_widget_size_request (topHandle, &requisition); + GtkAllocation allocation; + allocation.x = OS.GTK_WIDGET_X (topHandle); + allocation.y = OS.GTK_WIDGET_Y (topHandle); + allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); + allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); + OS.gtk_widget_size_allocate (topHandle, &allocation); } /** @@ -526,11 +526,11 @@ * @since 2.0 */ public Accessible getAccessible () { - checkWidget (); - if (accessible is null) { - accessible = Accessible.internal_new_Accessible (this); - } - return accessible; + checkWidget (); + if (accessible is null) { + accessible = Accessible.internal_new_Accessible (this); + } + return accessible; } /** @@ -547,13 +547,13 @@ * */ public Rectangle getBounds () { - checkWidget(); - auto topHandle = topHandle (); - int x = OS.GTK_WIDGET_X (topHandle); - int y = OS.GTK_WIDGET_Y (topHandle); - int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); - int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); - return new Rectangle (x, y, width, height); + checkWidget(); + auto topHandle = topHandle (); + int x = OS.GTK_WIDGET_X (topHandle); + int y = OS.GTK_WIDGET_Y (topHandle); + int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); + int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); + return new Rectangle (x, y, width, height); } /** @@ -575,9 +575,9 @@ * */ public void setBounds (Rectangle rect) { - checkWidget (); - if (rect is null) error (SWT.ERROR_NULL_ARGUMENT); - setBounds (rect.x, rect.y, Math.max (0, rect.width), Math.max (0, rect.height), true, true); + checkWidget (); + if (rect is null) error (SWT.ERROR_NULL_ARGUMENT); + setBounds (rect.x, rect.y, Math.max (0, rect.width), Math.max (0, rect.height), true, true); } /** @@ -604,130 +604,130 @@ * */ public void setBounds (int x, int y, int width, int height) { - checkWidget(); - setBounds (x, y, Math.max (0, width), Math.max (0, height), true, true); + checkWidget(); + setBounds (x, y, Math.max (0, width), Math.max (0, height), true, true); } void markLayout (bool changed, bool all) { - /* Do nothing */ + /* Do nothing */ } void moveHandle (int x, int y) { - auto topHandle = topHandle (); - auto parentHandle = parent.parentingHandle (); - /* - * Feature in GTK. Calling gtk_fixed_move() to move a child causes - * the whole parent to redraw. This is a performance problem. The - * fix is temporarily make the parent not visible during the move. - * - * NOTE: Because every widget in SWT has an X window, the new and - * old bounds of the child are correctly redrawn. - */ - int flags = OS.GTK_WIDGET_FLAGS (parentHandle); - OS.GTK_WIDGET_UNSET_FLAGS (parentHandle, OS.GTK_VISIBLE); - OS.gtk_fixed_move (cast(GtkFixed*)parentHandle, topHandle, x, y); - if ((flags & OS.GTK_VISIBLE) !is 0) { - OS.GTK_WIDGET_SET_FLAGS (parentHandle, OS.GTK_VISIBLE); - } + auto topHandle = topHandle (); + auto parentHandle = parent.parentingHandle (); + /* + * Feature in GTK. Calling gtk_fixed_move() to move a child causes + * the whole parent to redraw. This is a performance problem. The + * fix is temporarily make the parent not visible during the move. + * + * NOTE: Because every widget in SWT has an X window, the new and + * old bounds of the child are correctly redrawn. + */ + int flags = OS.GTK_WIDGET_FLAGS (parentHandle); + OS.GTK_WIDGET_UNSET_FLAGS (parentHandle, OS.GTK_VISIBLE); + OS.gtk_fixed_move (cast(GtkFixed*)parentHandle, topHandle, x, y); + if ((flags & OS.GTK_VISIBLE) !is 0) { + OS.GTK_WIDGET_SET_FLAGS (parentHandle, OS.GTK_VISIBLE); + } } void resizeHandle (int width, int height) { - auto topHandle = topHandle (); - OS.gtk_widget_set_size_request (topHandle, width, height); - if (topHandle !is handle) OS.gtk_widget_set_size_request (handle, width, height); + auto topHandle = topHandle (); + OS.gtk_widget_set_size_request (topHandle, width, height); + if (topHandle !is handle) OS.gtk_widget_set_size_request (handle, width, height); } int setBounds (int x, int y, int width, int height, bool move, bool resize) { - auto topHandle = topHandle (); - bool sameOrigin = true, sameExtent = true; - if (move) { - int oldX = OS.GTK_WIDGET_X (topHandle); - int oldY = OS.GTK_WIDGET_Y (topHandle); - sameOrigin = x is oldX && y is oldY; - if (!sameOrigin) { - if (enableWindow !is null) { - OS.gdk_window_move (enableWindow, x, y); - } - moveHandle (x, y); - } - } - if (resize) { - int oldWidth = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); - int oldHeight = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); - sameExtent = width is oldWidth && height is oldHeight; - if (!sameExtent && !(width is 0 && height is 0)) { - int newWidth = Math.max (1, width); - int newHeight = Math.max (1, height); - if (redrawWindow !is null) { - OS.gdk_window_resize (redrawWindow, newWidth, newHeight); - } - if (enableWindow !is null) { - OS.gdk_window_resize (enableWindow, newWidth, newHeight); - } - resizeHandle (newWidth, newHeight); - } - } - if (!sameOrigin || !sameExtent) { - /* - * Cause a size allocation this widget's topHandle. Note that - * all calls to gtk_widget_size_allocate() must be preceded by - * a call to gtk_widget_size_request(). - */ - GtkRequisition requisition; - gtk_widget_size_request (topHandle, &requisition); - GtkAllocation allocation; - if (move) { - allocation.x = x; - allocation.y = y; - } else { - allocation.x = OS.GTK_WIDGET_X (topHandle); - allocation.y = OS.GTK_WIDGET_Y (topHandle); - } - if (resize) { - allocation.width = width; - allocation.height = height; - } else { - allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); - allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); - } - OS.gtk_widget_size_allocate (topHandle, &allocation); - } - /* - * Bug in GTK. Widgets cannot be sized smaller than 1x1. - * The fix is to hide zero-sized widgets and show them again - * when they are resized larger. - */ - if (!sameExtent) { - state = (width is 0) ? state | ZERO_WIDTH : state & ~ZERO_WIDTH; - state = (height is 0) ? state | ZERO_HEIGHT : state & ~ZERO_HEIGHT; - if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) !is 0) { - if (enableWindow !is null) { - OS.gdk_window_hide (enableWindow); - } - OS.gtk_widget_hide (topHandle); - } else { - if ((state & HIDDEN) is 0) { - if (enableWindow !is null) { - OS.gdk_window_show_unraised (enableWindow); - } - OS.gtk_widget_show (topHandle); - } - } - } - int result = 0; - if (move && !sameOrigin) { - Control control = findBackgroundControl (); - if (control !is null && control.backgroundImage !is null) { - if (isVisible ()) redrawWidget (0, 0, 0, 0, true, true, true); - } - sendEvent (SWT.Move); - result |= MOVED; - } - if (resize && !sameExtent) { - sendEvent (SWT.Resize); - result |= RESIZED; - } - return result; + auto topHandle = topHandle (); + bool sameOrigin = true, sameExtent = true; + if (move) { + int oldX = OS.GTK_WIDGET_X (topHandle); + int oldY = OS.GTK_WIDGET_Y (topHandle); + sameOrigin = x is oldX && y is oldY; + if (!sameOrigin) { + if (enableWindow !is null) { + OS.gdk_window_move (enableWindow, x, y); + } + moveHandle (x, y); + } + } + if (resize) { + int oldWidth = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); + int oldHeight = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); + sameExtent = width is oldWidth && height is oldHeight; + if (!sameExtent && !(width is 0 && height is 0)) { + int newWidth = Math.max (1, width); + int newHeight = Math.max (1, height); + if (redrawWindow !is null) { + OS.gdk_window_resize (redrawWindow, newWidth, newHeight); + } + if (enableWindow !is null) { + OS.gdk_window_resize (enableWindow, newWidth, newHeight); + } + resizeHandle (newWidth, newHeight); + } + } + if (!sameOrigin || !sameExtent) { + /* + * Cause a size allocation this widget's topHandle. Note that + * all calls to gtk_widget_size_allocate() must be preceded by + * a call to gtk_widget_size_request(). + */ + GtkRequisition requisition; + gtk_widget_size_request (topHandle, &requisition); + GtkAllocation allocation; + if (move) { + allocation.x = x; + allocation.y = y; + } else { + allocation.x = OS.GTK_WIDGET_X (topHandle); + allocation.y = OS.GTK_WIDGET_Y (topHandle); + } + if (resize) { + allocation.width = width; + allocation.height = height; + } else { + allocation.width = OS.GTK_WIDGET_WIDTH (topHandle); + allocation.height = OS.GTK_WIDGET_HEIGHT (topHandle); + } + OS.gtk_widget_size_allocate (topHandle, &allocation); + } + /* + * Bug in GTK. Widgets cannot be sized smaller than 1x1. + * The fix is to hide zero-sized widgets and show them again + * when they are resized larger. + */ + if (!sameExtent) { + state = (width is 0) ? state | ZERO_WIDTH : state & ~ZERO_WIDTH; + state = (height is 0) ? state | ZERO_HEIGHT : state & ~ZERO_HEIGHT; + if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) !is 0) { + if (enableWindow !is null) { + OS.gdk_window_hide (enableWindow); + } + OS.gtk_widget_hide (topHandle); + } else { + if ((state & HIDDEN) is 0) { + if (enableWindow !is null) { + OS.gdk_window_show_unraised (enableWindow); + } + OS.gtk_widget_show (topHandle); + } + } + } + int result = 0; + if (move && !sameOrigin) { + Control control = findBackgroundControl (); + if (control !is null && control.backgroundImage !is null) { + if (isVisible ()) redrawWidget (0, 0, 0, 0, true, true, true); + } + sendEvent (SWT.Move); + result |= MOVED; + } + if (resize && !sameExtent) { + sendEvent (SWT.Resize); + result |= RESIZED; + } + return result; } /** @@ -744,11 +744,11 @@ * */ public Point getLocation () { - checkWidget(); - auto topHandle = topHandle (); - int x = OS.GTK_WIDGET_X (topHandle); - int y = OS.GTK_WIDGET_Y (topHandle); - return new Point (x, y); + checkWidget(); + auto topHandle = topHandle (); + int x = OS.GTK_WIDGET_X (topHandle); + int y = OS.GTK_WIDGET_Y (topHandle); + return new Point (x, y); } /** @@ -766,9 +766,9 @@ * */ public void setLocation (Point location) { - checkWidget (); - if (location is null) error (SWT.ERROR_NULL_ARGUMENT); - setBounds (location.x, location.y, 0, 0, true, false); + checkWidget (); + if (location is null) error (SWT.ERROR_NULL_ARGUMENT); + setBounds (location.x, location.y, 0, 0, true, false); } /** @@ -787,8 +787,8 @@ * */ public void setLocation(int x, int y) { - checkWidget(); - setBounds (x, y, 0, 0, true, false); + checkWidget(); + setBounds (x, y, 0, 0, true, false); } /** @@ -805,11 +805,11 @@ * */ public Point getSize () { - checkWidget(); - auto topHandle = topHandle (); - int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); - int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); - return new Point (width, height); + checkWidget(); + auto topHandle = topHandle (); + int width = (state & ZERO_WIDTH) !is 0 ? 0 : OS.GTK_WIDGET_WIDTH (topHandle); + int height = (state & ZERO_HEIGHT) !is 0 ? 0 : OS.GTK_WIDGET_HEIGHT (topHandle); + return new Point (width, height); } /** @@ -831,36 +831,36 @@ * */ public void setSize (Point size) { - checkWidget (); - if (size is null) error (SWT.ERROR_NULL_ARGUMENT); - setBounds (0, 0, Math.max (0, size.x), Math.max (0, size.y), false, true); + checkWidget (); + if (size is null) error (SWT.ERROR_NULL_ARGUMENT); + setBounds (0, 0, Math.max (0, size.x), Math.max (0, size.y), false, true); } void setRelations () { - auto parentHandle = parent.parentingHandle (); + auto parentHandle = parent.parentingHandle (); Stdout.formatln( "setRelations {:x}", cast(uint)parentHandle ); Stdout.formatln( "showWidget gtk_container_get_children {:x}", parentHandle ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentHandle) ); - auto list = OS.gtk_container_get_children (cast(GtkContainer*)parentHandle); - if (list is null) return; - int count = OS.g_list_length (list); - if (count > 1) { - /* - * the receiver is the last item in the list, so its predecessor will - * be the second-last item in the list - */ - auto handle = cast(GtkWidget*) OS.g_list_nth_data (list, count - 2); - if (handle !is null) { - Widget widget = display.getWidget (handle); - if (widget !is null && widget !is this) { - if (auto sibling = cast(Control)widget ) { - sibling.addRelation (this); - } - } - } - } - OS.g_list_free (list); + auto list = OS.gtk_container_get_children (cast(GtkContainer*)parentHandle); + if (list is null) return; + int count = OS.g_list_length (list); + if (count > 1) { + /* + * the receiver is the last item in the list, so its predecessor will + * be the second-last item in the list + */ + auto handle = cast(GtkWidget*) OS.g_list_nth_data (list, count - 2); + if (handle !is null) { + Widget widget = display.getWidget (handle); + if (widget !is null && widget !is this) { + if (auto sibling = cast(Control)widget ) { + sibling.addRelation (this); + } + } + } + } + OS.g_list_free (list); } /** @@ -880,8 +880,8 @@ * */ public void setSize (int width, int height) { - checkWidget(); - setBounds (0, 0, Math.max (0, width), Math.max (0, height), false, true); + checkWidget(); + setBounds (0, 0, Math.max (0, width), Math.max (0, height), false, true); } /* @@ -889,7 +889,7 @@ * a layout should be read by screen readers as the recevier's label. */ bool isDescribedByLabel () { - return true; + return true; } /** @@ -913,12 +913,12 @@ * @see Composite#getChildren */ public void moveAbove (Control control) { - checkWidget(); - if (control !is null) { - if (control.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); - if (parent !is control.parent) return; - } - setZOrder (control, true, true); + checkWidget(); + if (control !is null) { + if (control.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); + if (parent !is control.parent) return; + } + setZOrder (control, true, true); } /** @@ -942,12 +942,12 @@ * @see Composite#getChildren */ public void moveBelow (Control control) { - checkWidget(); - if (control !is null) { - if (control.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); - if (parent !is control.parent) return; - } - setZOrder (control, false, true); + checkWidget(); + if (control !is null) { + if (control.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); + if (parent !is control.parent) return; + } + setZOrder (control, false, true); } /** @@ -963,7 +963,7 @@ * @see #computeSize(int, int, bool) */ public void pack () { - pack (true); + pack (true); } /** @@ -988,7 +988,7 @@ * @see #computeSize(int, int, bool) */ public void pack (bool changed) { - setSize (computeSize (SWT.DEFAULT, SWT.DEFAULT, changed)); + setSize (computeSize (SWT.DEFAULT, SWT.DEFAULT, changed)); } /** @@ -1002,8 +1002,8 @@ * */ public void setLayoutData (Object layoutData) { - checkWidget(); - this.layoutData = layoutData; + checkWidget(); + this.layoutData = layoutData; } /** @@ -1023,11 +1023,11 @@ * @since 2.1 */ public Point toControl (int x, int y) { - checkWidget (); - auto window = eventWindow (); - int origin_x, origin_y; - OS.gdk_window_get_origin (window, &origin_x, &origin_y); - return new Point (x - origin_x , y - origin_y ); + checkWidget (); + auto window = eventWindow (); + int origin_x, origin_y; + OS.gdk_window_get_origin (window, &origin_x, &origin_y); + return new Point (x - origin_x , y - origin_y ); } /** @@ -1047,9 +1047,9 @@ * */ public Point toControl (Point point) { - checkWidget (); - if (point is null) error (SWT.ERROR_NULL_ARGUMENT); - return toControl (point.x, point.y); + checkWidget (); + if (point is null) error (SWT.ERROR_NULL_ARGUMENT); + return toControl (point.x, point.y); } /** @@ -1069,11 +1069,11 @@ * @since 2.1 */ public Point toDisplay (int x, int y) { - checkWidget(); - auto window = eventWindow (); - int origin_x, origin_y; - OS.gdk_window_get_origin (window, &origin_x, &origin_y); - return new Point (origin_x + x, origin_y + y); + checkWidget(); + auto window = eventWindow (); + int origin_x, origin_y; + OS.gdk_window_get_origin (window, &origin_x, &origin_y); + return new Point (origin_x + x, origin_y + y); } /** @@ -1093,9 +1093,9 @@ * */ public Point toDisplay (Point point) { - checkWidget(); - if (point is null) error (SWT.ERROR_NULL_ARGUMENT); - return toDisplay (point.x, point.y); + checkWidget(); + if (point is null) error (SWT.ERROR_NULL_ARGUMENT); + return toDisplay (point.x, point.y); } /** @@ -1118,11 +1118,11 @@ * @see #removeControlListener */ public void addControlListener(ControlListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.Resize,typedListener); - addListener (SWT.Move,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.Resize,typedListener); + addListener (SWT.Move,typedListener); } /** @@ -1147,10 +1147,10 @@ * @since 3.3 */ public void addDragDetectListener (DragDetectListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.DragDetect,typedListener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.DragDetect,typedListener); } /** @@ -1173,11 +1173,11 @@ * @see #removeFocusListener */ public void addFocusListener(FocusListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener(SWT.FocusIn,typedListener); - addListener(SWT.FocusOut,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener(SWT.FocusIn,typedListener); + addListener(SWT.FocusOut,typedListener); } /** @@ -1200,10 +1200,10 @@ * @see #removeHelpListener */ public void addHelpListener (HelpListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.Help, typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.Help, typedListener); } /** @@ -1237,11 +1237,11 @@ * @see #removeKeyListener */ public void addKeyListener(KeyListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener(SWT.KeyUp,typedListener); - addListener(SWT.KeyDown,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener(SWT.KeyUp,typedListener); + addListener(SWT.KeyDown,typedListener); } /** @@ -1266,10 +1266,10 @@ * @since 3.3 */ public void addMenuDetectListener (MenuDetectListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.MenuDetect, typedListener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.MenuDetect, typedListener); } /** @@ -1292,12 +1292,12 @@ * @see #removeMouseListener */ public void addMouseListener(MouseListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener(SWT.MouseDown,typedListener); - addListener(SWT.MouseUp,typedListener); - addListener(SWT.MouseDoubleClick,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener(SWT.MouseDown,typedListener); + addListener(SWT.MouseUp,typedListener); + addListener(SWT.MouseDoubleClick,typedListener); } /** @@ -1320,10 +1320,10 @@ * @see #removeMouseMoveListener */ public void addMouseMoveListener(MouseMoveListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener(SWT.MouseMove,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener(SWT.MouseMove,typedListener); } /** @@ -1346,12 +1346,12 @@ * @see #removeMouseTrackListener */ public void addMouseTrackListener (MouseTrackListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.MouseEnter,typedListener); - addListener (SWT.MouseExit,typedListener); - addListener (SWT.MouseHover,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.MouseEnter,typedListener); + addListener (SWT.MouseExit,typedListener); + addListener (SWT.MouseHover,typedListener); } /** @@ -1376,10 +1376,10 @@ * @since 3.3 */ public void addMouseWheelListener (MouseWheelListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.MouseWheel, typedListener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.MouseWheel, typedListener); } /** @@ -1402,10 +1402,10 @@ * @see #removePaintListener */ public void addPaintListener(PaintListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener(SWT.Paint,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener(SWT.Paint,typedListener); } void addRelation (Control control) { @@ -1431,10 +1431,10 @@ * @see #removeTraverseListener */ public void addTraverseListener (TraverseListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - TypedListener typedListener = new TypedListener (listener); - addListener (SWT.Traverse,typedListener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + TypedListener typedListener = new TypedListener (listener); + addListener (SWT.Traverse,typedListener); } /** @@ -1455,11 +1455,11 @@ * @see #addControlListener */ public void removeControlListener (ControlListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.Move, listener); - eventTable.unhook (SWT.Resize, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.Move, listener); + eventTable.unhook (SWT.Resize, listener); } /** @@ -1482,10 +1482,10 @@ * @since 3.3 */ public void removeDragDetectListener(DragDetectListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.DragDetect, listener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.DragDetect, listener); } /** @@ -1506,11 +1506,11 @@ * @see #addFocusListener */ public void removeFocusListener(FocusListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.FocusIn, listener); - eventTable.unhook (SWT.FocusOut, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.FocusIn, listener); + eventTable.unhook (SWT.FocusOut, listener); } /** * Removes the listener from the collection of listeners who will @@ -1530,10 +1530,10 @@ * @see #addHelpListener */ public void removeHelpListener (HelpListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.Help, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.Help, listener); } /** * Removes the listener from the collection of listeners who will @@ -1553,11 +1553,11 @@ * @see #addKeyListener */ public void removeKeyListener(KeyListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.KeyUp, listener); - eventTable.unhook (SWT.KeyDown, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.KeyUp, listener); + eventTable.unhook (SWT.KeyDown, listener); } /** * Removes the listener from the collection of listeners who will @@ -1580,10 +1580,10 @@ * @since 3.3 */ public void removeMenuDetectListener (MenuDetectListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.MenuDetect, listener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.MenuDetect, listener); } /** * Removes the listener from the collection of listeners who will @@ -1603,12 +1603,12 @@ * @see #addMouseListener */ public void removeMouseListener (MouseListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.MouseDown, listener); - eventTable.unhook (SWT.MouseUp, listener); - eventTable.unhook (SWT.MouseDoubleClick, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.MouseDown, listener); + eventTable.unhook (SWT.MouseUp, listener); + eventTable.unhook (SWT.MouseDoubleClick, listener); } /** * Removes the listener from the collection of listeners who will @@ -1628,10 +1628,10 @@ * @see #addMouseMoveListener */ public void removeMouseMoveListener(MouseMoveListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.MouseMove, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.MouseMove, listener); } /** @@ -1652,12 +1652,12 @@ * @see #addMouseTrackListener */ public void removeMouseTrackListener(MouseTrackListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.MouseEnter, listener); - eventTable.unhook (SWT.MouseExit, listener); - eventTable.unhook (SWT.MouseHover, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.MouseEnter, listener); + eventTable.unhook (SWT.MouseExit, listener); + eventTable.unhook (SWT.MouseHover, listener); } /** @@ -1680,10 +1680,10 @@ * @since 3.3 */ public void removeMouseWheelListener (MouseWheelListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.MouseWheel, listener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.MouseWheel, listener); } /** @@ -1704,26 +1704,26 @@ * @see #addPaintListener */ public void removePaintListener(PaintListener listener) { - checkWidget(); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook(SWT.Paint, listener); + checkWidget(); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook(SWT.Paint, listener); } /* * Remove "Labelled by" relations from the receiver. */ void removeRelation () { - if (!isDescribedByLabel ()) return; /* there will not be any */ - auto accessible = OS.gtk_widget_get_accessible (handle); - if (accessible is null) return; - auto set = ATK.atk_object_ref_relation_set (accessible); - int count = ATK.atk_relation_set_get_n_relations (set); - for (int i = 0; i < count; i++) { - auto relation = ATK.atk_relation_set_get_relation (set, 0); - ATK.atk_relation_set_remove (set, relation); - } - OS.g_object_unref (set); + if (!isDescribedByLabel ()) return; /* there will not be any */ + auto accessible = OS.gtk_widget_get_accessible (handle); + if (accessible is null) return; + auto set = ATK.atk_object_ref_relation_set (accessible); + int count = ATK.atk_relation_set_get_n_relations (set); + for (int i = 0; i < count; i++) { + auto relation = ATK.atk_relation_set_get_relation (set, 0); + ATK.atk_relation_set_remove (set, relation); + } + OS.g_object_unref (set); } /** @@ -1744,10 +1744,10 @@ * @see #addTraverseListener */ public void removeTraverseListener(TraverseListener listener) { - checkWidget (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) return; - eventTable.unhook (SWT.Traverse, listener); + checkWidget (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) return; + eventTable.unhook (SWT.Traverse, listener); } /** @@ -1787,9 +1787,9 @@ * @since 3.3 */ public bool dragDetect (Event event) { - checkWidget (); - if (event is null) error (SWT.ERROR_NULL_ARGUMENT); - return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); + checkWidget (); + if (event is null) error (SWT.ERROR_NULL_ARGUMENT); + return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); } /** @@ -1829,107 +1829,107 @@ * @since 3.3 */ public bool dragDetect (MouseEvent event) { - checkWidget (); - if (event is null) error (SWT.ERROR_NULL_ARGUMENT); - return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); + checkWidget (); + if (event is null) error (SWT.ERROR_NULL_ARGUMENT); + return dragDetect (event.button, event.count, event.stateMask, event.x, event.y); } bool dragDetect (int button, int count, int stateMask, int x, int y) { - if (button !is 1 || count !is 1) return false; - if (!dragDetect (x, y, false, null)) return false; - return sendDragEvent (button, stateMask, x, y, true); + if (button !is 1 || count !is 1) return false; + if (!dragDetect (x, y, false, null)) return false; + return sendDragEvent (button, stateMask, x, y, true); } bool dragDetect (int x, int y, bool filter, bool* consume) { - bool quit = false, dragging = false; - while (!quit) { - GdkEvent* eventPtr; - while (true) { - eventPtr = OS.gdk_event_get (); - if (eventPtr !is null) { - break; - } else { - try {Thread.sleep(0.050);} catch (Exception ex) {} - } - } - switch (cast(int)OS.GDK_EVENT_TYPE (eventPtr)) { - case OS.GDK_MOTION_NOTIFY: { - GdkEventMotion* gdkMotionEvent = cast(GdkEventMotion*)eventPtr; - if ((gdkMotionEvent.state & OS.GDK_BUTTON1_MASK) !is 0) { - if (OS.gtk_drag_check_threshold (handle, x, y, cast(int) gdkMotionEvent.x, cast(int) gdkMotionEvent.y)) { - dragging = true; - quit = true; - } - } else { - quit = true; - } - int newX, newY; - OS.gdk_window_get_pointer (gdkMotionEvent.window, &newX, &newY, null); - break; - } - case OS.GDK_KEY_PRESS: - case OS.GDK_KEY_RELEASE: { - GdkEventKey* gdkEvent = cast(GdkEventKey*)eventPtr; - if (gdkEvent.keyval is OS.GDK_Escape) quit = true; - break; - } - case OS.GDK_BUTTON_RELEASE: - case OS.GDK_BUTTON_PRESS: - case OS.GDK_2BUTTON_PRESS: - case OS.GDK_3BUTTON_PRESS: { - OS.gdk_event_put (eventPtr); - quit = true; - break; - } - default: - OS.gtk_main_do_event (eventPtr); - } - OS.gdk_event_free (eventPtr); - } - return dragging; + bool quit = false, dragging = false; + while (!quit) { + GdkEvent* eventPtr; + while (true) { + eventPtr = OS.gdk_event_get (); + if (eventPtr !is null) { + break; + } else { + try {Thread.sleep(0.050);} catch (Exception ex) {} + } + } + switch (cast(int)OS.GDK_EVENT_TYPE (eventPtr)) { + case OS.GDK_MOTION_NOTIFY: { + GdkEventMotion* gdkMotionEvent = cast(GdkEventMotion*)eventPtr; + if ((gdkMotionEvent.state & OS.GDK_BUTTON1_MASK) !is 0) { + if (OS.gtk_drag_check_threshold (handle, x, y, cast(int) gdkMotionEvent.x, cast(int) gdkMotionEvent.y)) { + dragging = true; + quit = true; + } + } else { + quit = true; + } + int newX, newY; + OS.gdk_window_get_pointer (gdkMotionEvent.window, &newX, &newY, null); + break; + } + case OS.GDK_KEY_PRESS: + case OS.GDK_KEY_RELEASE: { + GdkEventKey* gdkEvent = cast(GdkEventKey*)eventPtr; + if (gdkEvent.keyval is OS.GDK_Escape) quit = true; + break; + } + case OS.GDK_BUTTON_RELEASE: + case OS.GDK_BUTTON_PRESS: + case OS.GDK_2BUTTON_PRESS: + case OS.GDK_3BUTTON_PRESS: { + OS.gdk_event_put (eventPtr); + quit = true; + break; + } + default: + OS.gtk_main_do_event (eventPtr); + } + OS.gdk_event_free (eventPtr); + } + return dragging; } bool filterKey (int keyval, GdkEventKey* event) { - auto imHandle = imHandle (); - if (imHandle !is null) { - return cast(bool)OS.gtk_im_context_filter_keypress (imHandle, event); - } - return false; + auto imHandle = imHandle (); + if (imHandle !is null) { + return cast(bool)OS.gtk_im_context_filter_keypress (imHandle, event); + } + return false; } Control findBackgroundControl () { - if ((state & BACKGROUND) !is 0 || backgroundImage !is null) return this; - return (state & PARENT_BACKGROUND) !is 0 ? parent.findBackgroundControl () : null; + if ((state & BACKGROUND) !is 0 || backgroundImage !is null) return this; + return (state & PARENT_BACKGROUND) !is 0 ? parent.findBackgroundControl () : null; } Menu [] findMenus (Control control) { - if (menu !is null && this !is control) return [menu]; - return new Menu [0]; + if (menu !is null && this !is control) return [menu]; + return new Menu [0]; } void fixChildren (Shell newShell, Shell oldShell, Decorations newDecorations, Decorations oldDecorations, Menu [] menus) { - oldShell.fixShell (newShell, this); - oldDecorations.fixDecorations (newDecorations, this, menus); + oldShell.fixShell (newShell, this); + oldDecorations.fixDecorations (newDecorations, this, menus); } override int /*long*/ fixedMapProc (GtkWidget* widget) { - OS.GTK_WIDGET_SET_FLAGS (widget, OS.GTK_MAPPED); - auto widgetList = OS.gtk_container_get_children (cast(GtkContainer*)widget); - if (widgetList !is null) { - auto widgets = widgetList; - while (widgets !is null) { - auto child = cast(GtkWidget*)OS.g_list_data (widgets); - if (OS.GTK_WIDGET_VISIBLE (child) && OS.gtk_widget_get_child_visible (child) && !OS.GTK_WIDGET_MAPPED (child)) { - OS.gtk_widget_map (child); - } - widgets = cast(GList*)OS.g_list_next (widgets); - } - OS.g_list_free (widgetList); - } - if ((OS.GTK_WIDGET_FLAGS (widget) & OS.GTK_NO_WINDOW) is 0) { - OS.gdk_window_show_unraised (OS.GTK_WIDGET_WINDOW (widget)); - } - return 0; + OS.GTK_WIDGET_SET_FLAGS (widget, OS.GTK_MAPPED); + auto widgetList = OS.gtk_container_get_children (cast(GtkContainer*)widget); + if (widgetList !is null) { + auto widgets = widgetList; + while (widgets !is null) { + auto child = cast(GtkWidget*)OS.g_list_data (widgets); + if (OS.GTK_WIDGET_VISIBLE (child) && OS.gtk_widget_get_child_visible (child) && !OS.GTK_WIDGET_MAPPED (child)) { + OS.gtk_widget_map (child); + } + widgets = cast(GList*)OS.g_list_next (widgets); + } + OS.g_list_free (widgetList); + } + if ((OS.GTK_WIDGET_FLAGS (widget) & OS.GTK_NO_WINDOW) is 0) { + OS.gdk_window_show_unraised (OS.GTK_WIDGET_WINDOW (widget)); + } + return 0; } /** @@ -1946,31 +1946,31 @@ * @see #setFocus */ public bool forceFocus () { - checkWidget(); - if (display.focusEvent is SWT.FocusOut) return false; - Shell shell = getShell (); - shell.setSavedFocus (this); - if (!isEnabled () || !isVisible ()) return false; - shell.bringToTop (false); - return forceFocus (focusHandle ()); + checkWidget(); + if (display.focusEvent is SWT.FocusOut) return false; + Shell shell = getShell (); + shell.setSavedFocus (this); + if (!isEnabled () || !isVisible ()) return false; + shell.bringToTop (false); + return forceFocus (focusHandle ()); } bool forceFocus (GtkWidget* focusHandle) { - /* When the control is zero sized it must be realized */ - OS.gtk_widget_realize (focusHandle); - OS.gtk_widget_grab_focus (focusHandle); - Shell shell = getShell (); - auto shellHandle = shell.shellHandle; - auto handle = OS.gtk_window_get_focus (cast(GtkWindow*)shellHandle); - while (handle !is null) { - if (handle is focusHandle) return true; - Widget widget = display.getWidget (handle); - if (widget !is null && (null !is cast(Control)widget)) { - return widget is this; - } - handle = OS.gtk_widget_get_parent (handle); - } - return false; + /* When the control is zero sized it must be realized */ + OS.gtk_widget_realize (focusHandle); + OS.gtk_widget_grab_focus (focusHandle); + Shell shell = getShell (); + auto shellHandle = shell.shellHandle; + auto handle = OS.gtk_window_get_focus (cast(GtkWindow*)shellHandle); + while (handle !is null) { + if (handle is focusHandle) return true; + Widget widget = display.getWidget (handle); + if (widget !is null && (null !is cast(Control)widget)) { + return widget is this; + } + handle = OS.gtk_widget_get_parent (handle); + } + return false; } /** @@ -1984,14 +1984,14 @@ * */ public Color getBackground () { - checkWidget(); - Control control = findBackgroundControl (); - if (control is null) control = this; - return Color.gtk_new (display, control.getBackgroundColor ()); + checkWidget(); + Control control = findBackgroundControl (); + if (control is null) control = this; + return Color.gtk_new (display, control.getBackgroundColor ()); } GdkColor* getBackgroundColor () { - return getBgColor (); + return getBgColor (); } /** @@ -2007,26 +2007,26 @@ * @since 3.2 */ public Image getBackgroundImage () { - checkWidget (); - Control control = findBackgroundControl (); - if (control is null) control = this; - return control.backgroundImage; + checkWidget (); + Control control = findBackgroundControl (); + if (control is null) control = this; + return control.backgroundImage; } GdkColor* getBgColor () { - auto fontHandle = fontHandle (); - OS.gtk_widget_realize (fontHandle); - GdkColor* color = new GdkColor (); - OS.gtk_style_get_bg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); - return color; + auto fontHandle = fontHandle (); + OS.gtk_widget_realize (fontHandle); + GdkColor* color = new GdkColor (); + OS.gtk_style_get_bg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); + return color; } GdkColor* getBaseColor () { - auto fontHandle = fontHandle (); - OS.gtk_widget_realize (fontHandle); - GdkColor* color = new GdkColor (); - OS.gtk_style_get_base (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); - return color; + auto fontHandle = fontHandle (); + OS.gtk_widget_realize (fontHandle); + GdkColor* color = new GdkColor (); + OS.gtk_style_get_base (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); + return color; } /** @@ -2040,8 +2040,8 @@ * */ public int getBorderWidth () { - checkWidget(); - return 0; + checkWidget(); + return 0; } /** @@ -2059,8 +2059,8 @@ * @since 3.3 */ public Cursor getCursor () { - checkWidget (); - return cursor; + checkWidget (); + return cursor; } /** @@ -2077,8 +2077,8 @@ * @since 3.3 */ public bool getDragDetect () { - checkWidget (); - return (state & DRAG_DETECT) !is 0; + checkWidget (); + return (state & DRAG_DETECT) !is 0; } /** @@ -2097,8 +2097,8 @@ * @see #isEnabled */ public bool getEnabled () { - checkWidget (); - return (state & DISABLED) is 0; + checkWidget (); + return (state & DISABLED) is 0; } /** @@ -2112,15 +2112,15 @@ * */ public Font getFont () { - checkWidget(); - if (font !is null) return font; - return Font.gtk_new (display, defaultFont ()); + checkWidget(); + if (font !is null) return font; + return Font.gtk_new (display, defaultFont ()); } PangoFontDescription* getFontDescription () { - auto fontHandle = fontHandle (); - OS.gtk_widget_realize (fontHandle); - return OS.gtk_style_get_font_desc (OS.gtk_widget_get_style (fontHandle)); + auto fontHandle = fontHandle (); + OS.gtk_widget_realize (fontHandle); + return OS.gtk_style_get_font_desc (OS.gtk_widget_get_style (fontHandle)); } /** @@ -2134,32 +2134,32 @@ * */ public Color getForeground () { - checkWidget(); - return Color.gtk_new (display, getForegroundColor ()); + checkWidget(); + return Color.gtk_new (display, getForegroundColor ()); } GdkColor* getForegroundColor () { - return getFgColor (); + return getFgColor (); } GdkColor* getFgColor () { - auto fontHandle = fontHandle (); - OS.gtk_widget_realize (fontHandle); - GdkColor* color = new GdkColor (); - OS.gtk_style_get_fg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); - return color; + auto fontHandle = fontHandle (); + OS.gtk_widget_realize (fontHandle); + GdkColor* color = new GdkColor (); + OS.gtk_style_get_fg (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); + return color; } Point getIMCaretPos () { - return new Point (0, 0); + return new Point (0, 0); } GdkColor* getTextColor () { - auto fontHandle = fontHandle (); - OS.gtk_widget_realize (fontHandle); - GdkColor* color = new GdkColor (); - OS.gtk_style_get_text (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); - return color; + auto fontHandle = fontHandle (); + OS.gtk_widget_realize (fontHandle); + GdkColor* color = new GdkColor (); + OS.gtk_style_get_text (OS.gtk_widget_get_style (fontHandle), OS.GTK_STATE_NORMAL, color); + return color; } /** @@ -2173,8 +2173,8 @@ * */ public Object getLayoutData () { - checkWidget(); - return layoutData; + checkWidget(); + return layoutData; } /** @@ -2193,8 +2193,8 @@ * */ public Menu getMenu () { - checkWidget(); - return menu; + checkWidget(); + return menu; } /** @@ -2205,36 +2205,36 @@ * @since 3.0 */ public dwt.widgets.Monitor.Monitor getMonitor () { - checkWidget(); - dwt.widgets.Monitor.Monitor monitor = null; - auto screen = OS.gdk_screen_get_default (); - if (screen !is null) { - int monitorNumber = OS.gdk_screen_get_monitor_at_window (screen, paintWindow ()); - GdkRectangle dest; - OS.gdk_screen_get_monitor_geometry (screen, monitorNumber, &dest); - monitor = new dwt.widgets.Monitor.Monitor (); - monitor.handle = monitorNumber; - monitor.x = dest.x; - monitor.y = dest.y; - monitor.width = dest.width; - monitor.height = dest.height; - Rectangle workArea = null; - if (monitorNumber is 0) workArea = display.getWorkArea (); - if (workArea !is null) { - monitor.clientX = workArea.x; - monitor.clientY = workArea.y; - monitor.clientWidth = workArea.width; - monitor.clientHeight = workArea.height; - } else { - monitor.clientX = monitor.x; - monitor.clientY = monitor.y; - monitor.clientWidth = monitor.width; - monitor.clientHeight = monitor.height; - } - } else { - monitor = display.getPrimaryMonitor (); - } - return monitor; + checkWidget(); + dwt.widgets.Monitor.Monitor monitor = null; + auto screen = OS.gdk_screen_get_default (); + if (screen !is null) { + int monitorNumber = OS.gdk_screen_get_monitor_at_window (screen, paintWindow ()); + GdkRectangle dest; + OS.gdk_screen_get_monitor_geometry (screen, monitorNumber, &dest); + monitor = new dwt.widgets.Monitor.Monitor (); + monitor.handle = monitorNumber; + monitor.x = dest.x; + monitor.y = dest.y; + monitor.width = dest.width; + monitor.height = dest.height; + Rectangle workArea = null; + if (monitorNumber is 0) workArea = display.getWorkArea (); + if (workArea !is null) { + monitor.clientX = workArea.x; + monitor.clientY = workArea.y; + monitor.clientWidth = workArea.width; + monitor.clientHeight = workArea.height; + } else { + monitor.clientX = monitor.x; + monitor.clientY = monitor.y; + monitor.clientWidth = monitor.width; + monitor.clientHeight = monitor.height; + } + } else { + monitor = display.getPrimaryMonitor (); + } + return monitor; } /** @@ -2250,25 +2250,25 @@ * */ public Composite getParent () { - checkWidget(); - return parent; + checkWidget(); + return parent; } Control [] getPath () { - int count = 0; - Shell shell = getShell (); - Control control = this; - while (control !is shell) { - count++; - control = control.parent; - } - control = this; - Control [] result = new Control [count]; - while (control !is shell) { - result [--count] = control; - control = control.parent; - } - return result; + int count = 0; + Shell shell = getShell (); + Control control = this; + while (control !is shell) { + count++; + control = control.parent; + } + control = this; + Control [] result = new Control [count]; + while (control !is shell) { + result [--count] = control; + control = control.parent; + } + return result; } /** @@ -2287,12 +2287,12 @@ * @see #getParent */ public Shell getShell() { - checkWidget(); - return _getShell(); + checkWidget(); + return _getShell(); } Shell _getShell() { - return parent._getShell(); + return parent._getShell(); } /** @@ -2307,8 +2307,8 @@ * */ public char[] getToolTipText () { - checkWidget(); - return toolTipText; + checkWidget(); + return toolTipText; } /** * Returns true if the receiver is visible, and @@ -2328,379 +2328,379 @@ * */ public bool getVisible () { - checkWidget(); - return (state & HIDDEN) is 0; + checkWidget(); + return (state & HIDDEN) is 0; } override int /*long*/ gtk_button_press_event (GtkWidget* widget, GdkEventButton* gdkEvent) { - if (gdkEvent.type is OS.GDK_3BUTTON_PRESS) return 0; - /* - * When a shell is created with SWT.ON_TOP and SWT.NO_FOCUS, - * do not activate the shell when the user clicks on the - * the client area or on the border or a control within the - * shell that does not take focus. - */ - Shell shell = _getShell (); - if (((shell.style & SWT.ON_TOP) !is 0) && (((shell.style & SWT.NO_FOCUS) is 0) || ((style & SWT.NO_FOCUS) is 0))) { - shell.forceActive(); - } - int /*long*/ result = 0; - if (gdkEvent.type is OS.GDK_BUTTON_PRESS) { - display.clickCount = 1; - auto nextEvent = OS.gdk_event_peek (); - if (nextEvent !is null) { - int eventType = OS.GDK_EVENT_TYPE (nextEvent); - if (eventType is OS.GDK_2BUTTON_PRESS) display.clickCount = 2; - if (eventType is OS.GDK_3BUTTON_PRESS) display.clickCount = 3; - OS.gdk_event_free (nextEvent); - } - bool dragging = false; - if ((state & DRAG_DETECT) !is 0 && hooks (SWT.DragDetect)) { - if (gdkEvent.button is 1) { - bool consume = false; - if (dragDetect (cast(int) gdkEvent.x, cast(int) gdkEvent.y, true, &consume)) { - dragging = true; - if (consume ) result = 1; - } - if (isDisposed ()) return 1; - } - } - if (!sendMouseEvent (SWT.MouseDown, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state)) { - result = 1; - } - if (isDisposed ()) return 1; - if (dragging) { - sendDragEvent (gdkEvent.button, gdkEvent.state, cast(int) gdkEvent.x, cast(int) gdkEvent.y, false); - if (isDisposed ()) return 1; - } - /* - * Pop up the context menu in the button press event for widgets - * that have default operating system menus in order to stop the - * operating system from displaying the menu if necessary. - */ - if ((state & MENU) !is 0) { - if (gdkEvent.button is 3) { - if (showMenu (cast(int)gdkEvent.x_root, cast(int)gdkEvent.y_root)) { - result = 1; - } - } - } - } else { - display.clickCount = 2; - result = sendMouseEvent (SWT.MouseDoubleClick, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - if (isDisposed ()) return 1; - } - if (!shell.isDisposed ()) shell.setActiveControl (this); - return result; + if (gdkEvent.type is OS.GDK_3BUTTON_PRESS) return 0; + /* + * When a shell is created with SWT.ON_TOP and SWT.NO_FOCUS, + * do not activate the shell when the user clicks on the + * the client area or on the border or a control within the + * shell that does not take focus. + */ + Shell shell = _getShell (); + if (((shell.style & SWT.ON_TOP) !is 0) && (((shell.style & SWT.NO_FOCUS) is 0) || ((style & SWT.NO_FOCUS) is 0))) { + shell.forceActive(); + } + int /*long*/ result = 0; + if (gdkEvent.type is OS.GDK_BUTTON_PRESS) { + display.clickCount = 1; + auto nextEvent = OS.gdk_event_peek (); + if (nextEvent !is null) { + int eventType = OS.GDK_EVENT_TYPE (nextEvent); + if (eventType is OS.GDK_2BUTTON_PRESS) display.clickCount = 2; + if (eventType is OS.GDK_3BUTTON_PRESS) display.clickCount = 3; + OS.gdk_event_free (nextEvent); + } + bool dragging = false; + if ((state & DRAG_DETECT) !is 0 && hooks (SWT.DragDetect)) { + if (gdkEvent.button is 1) { + bool consume = false; + if (dragDetect (cast(int) gdkEvent.x, cast(int) gdkEvent.y, true, &consume)) { + dragging = true; + if (consume ) result = 1; + } + if (isDisposed ()) return 1; + } + } + if (!sendMouseEvent (SWT.MouseDown, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state)) { + result = 1; + } + if (isDisposed ()) return 1; + if (dragging) { + sendDragEvent (gdkEvent.button, gdkEvent.state, cast(int) gdkEvent.x, cast(int) gdkEvent.y, false); + if (isDisposed ()) return 1; + } + /* + * Pop up the context menu in the button press event for widgets + * that have default operating system menus in order to stop the + * operating system from displaying the menu if necessary. + */ + if ((state & MENU) !is 0) { + if (gdkEvent.button is 3) { + if (showMenu (cast(int)gdkEvent.x_root, cast(int)gdkEvent.y_root)) { + result = 1; + } + } + } + } else { + display.clickCount = 2; + result = sendMouseEvent (SWT.MouseDoubleClick, gdkEvent.button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + if (isDisposed ()) return 1; + } + if (!shell.isDisposed ()) shell.setActiveControl (this); + return result; } override int /*long*/ gtk_button_release_event (GtkWidget* widget, GdkEventButton* gdkEvent) { - /* - * Feature in GTK. When button 4, 5, 6, or 7 is released, GTK - * does not deliver a corresponding GTK event. Button 6 and 7 - * are mapped to buttons 4 and 5 in SWT. The fix is to change - * the button number of the event to a negative number so that - * it gets dispatched by GTK. SWT has been modified to look - * for negative button numbers. - */ - int button = gdkEvent.button; - switch (button) { - case -6: button = 4; break; - case -7: button = 5; break; + /* + * Feature in GTK. When button 4, 5, 6, or 7 is released, GTK + * does not deliver a corresponding GTK event. Button 6 and 7 + * are mapped to buttons 4 and 5 in SWT. The fix is to change + * the button number of the event to a negative number so that + * it gets dispatched by GTK. SWT has been modified to look + * for negative button numbers. + */ + int button = gdkEvent.button; + switch (button) { + case -6: button = 4; break; + case -7: button = 5; break; default: - } - return sendMouseEvent (SWT.MouseUp, button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + } + return sendMouseEvent (SWT.MouseUp, button, display.clickCount, 0, false, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; } override int /*long*/ gtk_commit (GtkIMContext* imcontext, char* text) { - char [] chars = fromUtf8z( text ); + char [] chars = fromUtf8z( text ); if (chars.length is 0) return 0; - sendIMKeyEvent (SWT.KeyDown, null, chars); - return 0; + sendIMKeyEvent (SWT.KeyDown, null, chars); + return 0; } override int /*long*/ gtk_enter_notify_event (GtkWidget* widget, GdkEventCrossing* gdkEvent) { - if (display.currentControl is this) return 0; - if (gdkEvent.mode !is OS.GDK_CROSSING_NORMAL && gdkEvent.mode !is OS.GDK_CROSSING_UNGRAB) return 0; - if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) !is 0) return 0; - if (display.currentControl !is null && !display.currentControl.isDisposed ()) { - display.removeMouseHoverTimeout (display.currentControl.handle); - display.currentControl.sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state); - } - if (!isDisposed ()) { - display.currentControl = this; - return sendMouseEvent (SWT.MouseEnter, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - } - return 0; + if (display.currentControl is this) return 0; + if (gdkEvent.mode !is OS.GDK_CROSSING_NORMAL && gdkEvent.mode !is OS.GDK_CROSSING_UNGRAB) return 0; + if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) !is 0) return 0; + if (display.currentControl !is null && !display.currentControl.isDisposed ()) { + display.removeMouseHoverTimeout (display.currentControl.handle); + display.currentControl.sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state); + } + if (!isDisposed ()) { + display.currentControl = this; + return sendMouseEvent (SWT.MouseEnter, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + } + return 0; } override int /*long*/ gtk_event_after (GtkWidget* widget, GdkEvent* gdkEvent) { - switch (cast(int)gdkEvent.type) { - case OS.GDK_BUTTON_PRESS: { - if (widget !is eventHandle ()) break; - /* - * Pop up the context menu in the event_after signal to allow - * the widget to process the button press. This allows widgets - * such as GtkTreeView to select items before a menu is shown. - */ - if ((state & MENU) is 0) { - GdkEventButton* gdkEventButton = cast(GdkEventButton*)gdkEvent; - if (gdkEventButton.button is 3) { - showMenu (cast(int) gdkEventButton.x_root, cast(int) gdkEventButton.y_root); - } - } - break; - } - case OS.GDK_FOCUS_CHANGE: { - if (widget !is focusHandle ()) break; - GdkEventFocus* gdkEventFocus = cast(GdkEventFocus*)gdkEvent; - - /* - * Feature in GTK. The GTK combo box popup under some window managers - * is implemented as a GTK_MENU. When it pops up, it causes the combo - * box to lose focus when focus is received for the menu. The - * fix is to check the current grab handle and see if it is a GTK_MENU - * and ignore the focus event when the menu is both shown and hidden. - */ - Display display = this.display; - if (gdkEventFocus.in_ !is 0) { - if (display.ignoreFocus) { - display.ignoreFocus = false; - break; - } - } else { - display.ignoreFocus = false; - auto grabHandle = OS.gtk_grab_get_current (); - if (grabHandle !is null) { - if (OS.G_OBJECT_TYPE ( cast(GTypeInstance*)grabHandle) is OS.GTK_TYPE_MENU ()) { - display.ignoreFocus = true; - break; - } - } - } - - sendFocusEvent (gdkEventFocus.in_ !is 0 ? SWT.FocusIn : SWT.FocusOut); - break; + switch (cast(int)gdkEvent.type) { + case OS.GDK_BUTTON_PRESS: { + if (widget !is eventHandle ()) break; + /* + * Pop up the context menu in the event_after signal to allow + * the widget to process the button press. This allows widgets + * such as GtkTreeView to select items before a menu is shown. + */ + if ((state & MENU) is 0) { + GdkEventButton* gdkEventButton = cast(GdkEventButton*)gdkEvent; + if (gdkEventButton.button is 3) { + showMenu (cast(int) gdkEventButton.x_root, cast(int) gdkEventButton.y_root); + } + } + break; + } + case OS.GDK_FOCUS_CHANGE: { + if (widget !is focusHandle ()) break; + GdkEventFocus* gdkEventFocus = cast(GdkEventFocus*)gdkEvent; + + /* + * Feature in GTK. The GTK combo box popup under some window managers + * is implemented as a GTK_MENU. When it pops up, it causes the combo + * box to lose focus when focus is received for the menu. The + * fix is to check the current grab handle and see if it is a GTK_MENU + * and ignore the focus event when the menu is both shown and hidden. + */ + Display display = this.display; + if (gdkEventFocus.in_ !is 0) { + if (display.ignoreFocus) { + display.ignoreFocus = false; + break; + } + } else { + display.ignoreFocus = false; + auto grabHandle = OS.gtk_grab_get_current (); + if (grabHandle !is null) { + if (OS.G_OBJECT_TYPE ( cast(GTypeInstance*)grabHandle) is OS.GTK_TYPE_MENU ()) { + display.ignoreFocus = true; + break; + } + } + } + + sendFocusEvent (gdkEventFocus.in_ !is 0 ? SWT.FocusIn : SWT.FocusOut); + break; default: - } - } - return 0; + } + } + return 0; } override int /*long*/ gtk_expose_event (GtkWidget* widget, GdkEventExpose* gdkEvent) { - if ((state & OBSCURED) !is 0) return 0; - if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return 0; - Event event = new Event (); - event.count = gdkEvent.count; - event.x = gdkEvent.area.x; - event.y = gdkEvent.area.y; - event.width = gdkEvent.area.width; - event.height = gdkEvent.area.height; - GCData data = new GCData (); - data.damageRgn = gdkEvent.region; - GC gc = event.gc = GC.gtk_new (this, data); - OS.gdk_gc_set_clip_region (gc.handle, gdkEvent.region); - sendEvent (SWT.Paint, event); - gc.dispose (); - event.gc = null; - return 0; + if ((state & OBSCURED) !is 0) return 0; + if (!hooks (SWT.Paint) && !filters (SWT.Paint)) return 0; + Event event = new Event (); + event.count = gdkEvent.count; + event.x = gdkEvent.area.x; + event.y = gdkEvent.area.y; + event.width = gdkEvent.area.width; + event.height = gdkEvent.area.height; + GCData data = new GCData (); + data.damageRgn = gdkEvent.region; + GC gc = event.gc = GC.gtk_new (this, data); + OS.gdk_gc_set_clip_region (gc.handle, gdkEvent.region); + sendEvent (SWT.Paint, event); + gc.dispose (); + event.gc = null; + return 0; } override int /*long*/ gtk_focus (GtkWidget* widget, int directionType) { - /* Stop GTK traversal for every widget */ - return 1; + /* Stop GTK traversal for every widget */ + return 1; } override int /*long*/ gtk_focus_in_event (GtkWidget* widget, GdkEventFocus* event) { - // widget could be disposed at this point - if (handle !is null) { - Control oldControl = display.imControl; - if (oldControl !is this) { - if (oldControl !is null && !oldControl.isDisposed ()) { - auto oldIMHandle = oldControl.imHandle (); - if (oldIMHandle !is null) OS.gtk_im_context_reset (oldIMHandle); - } - } - if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { - auto imHandle = imHandle (); - if (imHandle !is null) OS.gtk_im_context_focus_in (imHandle); - } - } - return 0; + // widget could be disposed at this point + if (handle !is null) { + Control oldControl = display.imControl; + if (oldControl !is this) { + if (oldControl !is null && !oldControl.isDisposed ()) { + auto oldIMHandle = oldControl.imHandle (); + if (oldIMHandle !is null) OS.gtk_im_context_reset (oldIMHandle); + } + } + if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { + auto imHandle = imHandle (); + if (imHandle !is null) OS.gtk_im_context_focus_in (imHandle); + } + } + return 0; } override int /*long*/ gtk_focus_out_event (GtkWidget* widget, GdkEventFocus* event) { - // widget could be disposed at this point - if (handle !is null) { - if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { - auto imHandle = imHandle (); - if (imHandle !is null) { - OS.gtk_im_context_focus_out (imHandle); - } - } - } - return 0; + // widget could be disposed at this point + if (handle !is null) { + if (hooks (SWT.KeyDown) || hooks (SWT.KeyUp)) { + auto imHandle = imHandle (); + if (imHandle !is null) { + OS.gtk_im_context_focus_out (imHandle); + } + } + } + return 0; } override int /*long*/ gtk_key_press_event (GtkWidget* widget, GdkEventKey* gdkEvent) { - if (!hasFocus ()) return 0; - - if (translateMnemonic (gdkEvent.keyval, gdkEvent)) return 1; - // widget could be disposed at this point - if (isDisposed ()) return 0; - - if (filterKey (gdkEvent.keyval, gdkEvent)) return 1; - // widget could be disposed at this point - if (isDisposed ()) return 0; - - if (translateTraversal (gdkEvent)) return 1; - // widget could be disposed at this point - if (isDisposed ()) return 0; - return super.gtk_key_press_event (widget, gdkEvent); + if (!hasFocus ()) return 0; + + if (translateMnemonic (gdkEvent.keyval, gdkEvent)) return 1; + // widget could be disposed at this point + if (isDisposed ()) return 0; + + if (filterKey (gdkEvent.keyval, gdkEvent)) return 1; + // widget could be disposed at this point + if (isDisposed ()) return 0; + + if (translateTraversal (gdkEvent)) return 1; + // widget could be disposed at this point + if (isDisposed ()) return 0; + return super.gtk_key_press_event (widget, gdkEvent); } override int /*long*/ gtk_key_release_event (GtkWidget* widget, GdkEventKey* event) { - if (!hasFocus ()) return 0; - auto imHandle = imHandle (); - if (imHandle !is null) { - if (OS.gtk_im_context_filter_keypress (imHandle, event)) return 1; - } - return super.gtk_key_release_event (widget, event); + if (!hasFocus ()) return 0; + auto imHandle = imHandle (); + if (imHandle !is null) { + if (OS.gtk_im_context_filter_keypress (imHandle, event)) return 1; + } + return super.gtk_key_release_event (widget, event); } override int /*long*/ gtk_leave_notify_event (GtkWidget* widget, GdkEventCrossing* gdkEvent) { - if (display.currentControl !is this) return 0; - display.removeMouseHoverTimeout (handle); - int result = 0; - if (sendLeaveNotify () || display.getCursorControl () is null) { - if (gdkEvent.mode !is OS.GDK_CROSSING_NORMAL && gdkEvent.mode !is OS.GDK_CROSSING_UNGRAB) return 0; - if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) !is 0) return 0; - result = sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - display.currentControl = null; - } - return result; + if (display.currentControl !is this) return 0; + display.removeMouseHoverTimeout (handle); + int result = 0; + if (sendLeaveNotify () || display.getCursorControl () is null) { + if (gdkEvent.mode !is OS.GDK_CROSSING_NORMAL && gdkEvent.mode !is OS.GDK_CROSSING_UNGRAB) return 0; + if ((gdkEvent.state & (OS.GDK_BUTTON1_MASK | OS.GDK_BUTTON2_MASK | OS.GDK_BUTTON3_MASK)) !is 0) return 0; + result = sendMouseEvent (SWT.MouseExit, 0, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + display.currentControl = null; + } + return result; } override int /*long*/ gtk_mnemonic_activate (GtkWidget* widget, int /*long*/ arg1) { - int result = 0; - auto eventPtr = OS.gtk_get_current_event (); - if (eventPtr !is null) { - GdkEventKey* keyEvent = cast(GdkEventKey*)eventPtr; - if (keyEvent.type is OS.GDK_KEY_PRESS) { - Control focusControl = display.getFocusControl (); - auto focusHandle = focusControl !is null ? focusControl.focusHandle () : null; - if (focusHandle !is null) { - display.mnemonicControl = this; - OS.gtk_widget_event (focusHandle, eventPtr); - display.mnemonicControl = null; - } - result = 1; - } - OS.gdk_event_free (eventPtr); - } - return result; + int result = 0; + auto eventPtr = OS.gtk_get_current_event (); + if (eventPtr !is null) { + GdkEventKey* keyEvent = cast(GdkEventKey*)eventPtr; + if (keyEvent.type is OS.GDK_KEY_PRESS) { + Control focusControl = display.getFocusControl (); + auto focusHandle = focusControl !is null ? focusControl.focusHandle () : null; + if (focusHandle !is null) { + display.mnemonicControl = this; + OS.gtk_widget_event (focusHandle, eventPtr); + display.mnemonicControl = null; + } + result = 1; + } + OS.gdk_event_free (eventPtr); + } + return result; } override int /*long*/ gtk_motion_notify_event (GtkWidget* widget, GdkEventMotion* gdkEvent) { - if (this is display.currentControl && (hooks (SWT.MouseHover) || filters (SWT.MouseHover))) { - display.addMouseHoverTimeout (handle); - } - double x = gdkEvent.x_root, y = gdkEvent.y_root; - int state = gdkEvent.state; - if (gdkEvent.is_hint !is 0) { - int pointer_x, pointer_y; + if (this is display.currentControl && (hooks (SWT.MouseHover) || filters (SWT.MouseHover))) { + display.addMouseHoverTimeout (handle); + } + double x = gdkEvent.x_root, y = gdkEvent.y_root; + int state = gdkEvent.state; + if (gdkEvent.is_hint !is 0) { + int pointer_x, pointer_y; int mask; - auto window = eventWindow (); - OS.gdk_window_get_pointer (window, &pointer_x, &pointer_y, &mask); - x = pointer_x; - y = pointer_y; - state = mask; - } - int result = sendMouseEvent (SWT.MouseMove, 0, gdkEvent.time, x, y, gdkEvent.is_hint !is 0, state) ? 0 : 1; - return result; + auto window = eventWindow (); + OS.gdk_window_get_pointer (window, &pointer_x, &pointer_y, &mask); + x = pointer_x; + y = pointer_y; + state = mask; + } + int result = sendMouseEvent (SWT.MouseMove, 0, gdkEvent.time, x, y, gdkEvent.is_hint !is 0, state) ? 0 : 1; + return result; } override int /*long*/ gtk_popup_menu (GtkWidget* widget) { - if (!hasFocus()) return 0; - int x, y ; - OS.gdk_window_get_pointer (null, &x, &y, null); - return showMenu (x, y) ? 1 : 0; + if (!hasFocus()) return 0; + int x, y ; + OS.gdk_window_get_pointer (null, &x, &y, null); + return showMenu (x, y) ? 1 : 0; } override int /*long*/ gtk_preedit_changed (GtkIMContext* imcontext) { - display.showIMWindow (this); - return 0; + display.showIMWindow (this); + return 0; } override int /*long*/ gtk_realize (GtkWidget* widget) { - auto imHandle = imHandle (); - if (imHandle !is null) { - auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); - OS.gtk_im_context_set_client_window (imHandle, window); - } - if (backgroundImage !is null) { - auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); - if (window !is null) OS.gdk_window_set_back_pixmap (window, cast(GdkPixmap*)backgroundImage.pixmap, false); - } - return 0; + auto imHandle = imHandle (); + if (imHandle !is null) { + auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); + OS.gtk_im_context_set_client_window (imHandle, window); + } + if (backgroundImage !is null) { + auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); + if (window !is null) OS.gdk_window_set_back_pixmap (window, cast(GdkPixmap*)backgroundImage.pixmap, false); + } + return 0; } override int /*long*/ gtk_scroll_event (GtkWidget* widget, GdkEventScroll* gdkEvent) { - switch (cast(int)gdkEvent.direction) { - case OS.GDK_SCROLL_UP: - return sendMouseEvent (SWT.MouseWheel, 0, 3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - case OS.GDK_SCROLL_DOWN: - return sendMouseEvent (SWT.MouseWheel, 0, -3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - case OS.GDK_SCROLL_LEFT: - return sendMouseEvent (SWT.MouseDown, 4, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; - case OS.GDK_SCROLL_RIGHT: - return sendMouseEvent (SWT.MouseDown, 5, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + switch (cast(int)gdkEvent.direction) { + case OS.GDK_SCROLL_UP: + return sendMouseEvent (SWT.MouseWheel, 0, 3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + case OS.GDK_SCROLL_DOWN: + return sendMouseEvent (SWT.MouseWheel, 0, -3, SWT.SCROLL_LINE, true, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + case OS.GDK_SCROLL_LEFT: + return sendMouseEvent (SWT.MouseDown, 4, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; + case OS.GDK_SCROLL_RIGHT: + return sendMouseEvent (SWT.MouseDown, 5, gdkEvent.time, gdkEvent.x_root, gdkEvent.y_root, false, gdkEvent.state) ? 0 : 1; default: - } - return 0; + } + return 0; } override int /*long*/ gtk_show_help (GtkWidget* widget, int /*long*/ helpType) { - if (!hasFocus ()) return 0; - return sendHelpEvent (helpType) ? 1 : 0; + if (!hasFocus ()) return 0; + return sendHelpEvent (helpType) ? 1 : 0; } override int /*long*/ gtk_style_set (GtkWidget* widget, int /*long*/ previousStyle) { - if (backgroundImage !is null) { - setBackgroundPixmap (backgroundImage.pixmap); - } - return 0; + if (backgroundImage !is null) { + setBackgroundPixmap (backgroundImage.pixmap); + } + return 0; } override int /*long*/ gtk_unrealize (GtkWidget* widget) { - auto imHandle = imHandle (); - if (imHandle !is null) OS.gtk_im_context_set_client_window (imHandle, null); - return 0; + auto imHandle = imHandle (); + if (imHandle !is null) OS.gtk_im_context_set_client_window (imHandle, null); + return 0; } override int /*long*/ gtk_visibility_notify_event (GtkWidget* widget, GdkEventVisibility* gdkEvent) { - auto paintWindow = paintWindow(); - auto window = gdkEvent.window; - if (window is paintWindow) { - if (gdkEvent.state is OS.GDK_VISIBILITY_FULLY_OBSCURED) { - state |= OBSCURED; - } else { - if ((state & OBSCURED) !is 0) { - int width, height; - OS.gdk_drawable_get_size (cast(GdkDrawable*)window, &width, &height); - GdkRectangle rect; - rect.width = width; - rect.height = height; - OS.gdk_window_invalidate_rect (window, &rect, false); - } - state &= ~OBSCURED; - } - } - return 0; + auto paintWindow = paintWindow(); + auto window = gdkEvent.window; + if (window is paintWindow) { + if (gdkEvent.state is OS.GDK_VISIBILITY_FULLY_OBSCURED) { + state |= OBSCURED; + } else { + if ((state & OBSCURED) !is 0) { + int width, height; + OS.gdk_drawable_get_size (cast(GdkDrawable*)window, &width, &height); + GdkRectangle rect; + rect.width = width; + rect.height = height; + OS.gdk_window_invalidate_rect (window, &rect, false); + } + state &= ~OBSCURED; + } + } + return 0; } /*no override*/ void gtk_widget_size_request (GtkWidget* widget, GtkRequisition* requisition) { - OS.gtk_widget_size_request (widget, requisition); + OS.gtk_widget_size_request (widget, requisition); } /** @@ -2717,29 +2717,29 @@ * @return the platform specific GC handle */ public GdkGC* internal_new_GC (GCData data) { - checkWidget (); - auto window = paintWindow (); - if (window is null) SWT.error (SWT.ERROR_NO_HANDLES); - auto gdkGC = OS.gdk_gc_new (cast(GdkDrawable*)window); - if (gdkGC is null) error (SWT.ERROR_NO_HANDLES); - if (data !is null) { - int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; - if ((data.style & mask) is 0) { - data.style |= style & (mask | SWT.MIRRORED); - } - data.drawable = cast(GdkDrawable*)window; - data.device = display; - data.foreground = getForegroundColor (); - Control control = findBackgroundControl (); - if (control is null) control = this; - data.background = control.getBackgroundColor (); - data.font = font !is null ? font.handle : defaultFont (); - } - return gdkGC; + checkWidget (); + auto window = paintWindow (); + if (window is null) SWT.error (SWT.ERROR_NO_HANDLES); + auto gdkGC = OS.gdk_gc_new (cast(GdkDrawable*)window); + if (gdkGC is null) error (SWT.ERROR_NO_HANDLES); + if (data !is null) { + int mask = SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT; + if ((data.style & mask) is 0) { + data.style |= style & (mask | SWT.MIRRORED); + } + data.drawable = cast(GdkDrawable*)window; + data.device = display; + data.foreground = getForegroundColor (); + Control control = findBackgroundControl (); + if (control is null) control = this; + data.background = control.getBackgroundColor (); + data.font = font !is null ? font.handle : defaultFont (); + } + return gdkGC; } GtkIMContext* imHandle () { - return null; + return null; } /** @@ -2756,8 +2756,8 @@ * @param data the platform specific GC data */ public void internal_dispose_GC (GdkGC* gdkGC, GCData data) { - checkWidget (); - OS.g_object_unref (gdkGC); + checkWidget (); + OS.g_object_unref (gdkGC); } /** @@ -2772,45 +2772,45 @@ * */ public bool isReparentable () { - checkWidget(); - return true; + checkWidget(); + return true; } bool isShowing () { - /* - * This is not complete. Need to check if the - * widget is obscurred by a parent or sibling. - */ - if (!isVisible ()) return false; - Control control = this; - while (control !is null) { - Point size = control.getSize (); - if (size.x is 0 || size.y is 0) { - return false; - } - control = control.parent; - } - return true; + /* + * This is not complete. Need to check if the + * widget is obscurred by a parent or sibling. + */ + if (!isVisible ()) return false; + Control control = this; + while (control !is null) { + Point size = control.getSize (); + if (size.x is 0 || size.y is 0) { + return false; + } + control = control.parent; + } + return true; } bool isTabGroup () { - Control [] tabList = parent._getTabList (); - if (tabList !is null) { - for (int i=0; i */ public bool isFocusControl () { - checkWidget(); - Control focusControl = display.focusControl; - if (focusControl !is null && !focusControl.isDisposed ()) { - return this is focusControl; - } - return hasFocus (); + checkWidget(); + Control focusControl = display.focusControl; + if (focusControl !is null && !focusControl.isDisposed ()) { + return this is focusControl; + } + return hasFocus (); } /** @@ -2876,29 +2876,29 @@ * @see #getVisible */ public bool isVisible () { - checkWidget(); - return getVisible () && parent.isVisible (); + checkWidget(); + return getVisible () && parent.isVisible (); } Decorations menuShell () { - return parent.menuShell (); + return parent.menuShell (); } alias Widget.mnemonicHit mnemonicHit; bool mnemonicHit (char key) { - return false; + return false; } alias Widget.mnemonicMatch mnemonicMatch; bool mnemonicMatch (char key) { - return false; + return false; } override void register () { - super.register (); - if (fixedHandle !is null) display.addWidget (fixedHandle, this); - auto imHandle = imHandle (); - if (imHandle !is null) display.addWidget (cast(GtkWidget*)imHandle, this); + super.register (); + if (fixedHandle !is null) display.addWidget (fixedHandle, this); + auto imHandle = imHandle (); + if (imHandle !is null) display.addWidget (cast(GtkWidget*)imHandle, this); } /** @@ -2921,14 +2921,14 @@ * @see SWT#DOUBLE_BUFFERED */ public void redraw () { - checkWidget(); - redraw (false); + checkWidget(); + redraw (false); } void redraw (bool all) { -// checkWidget(); - if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; - redrawWidget (0, 0, 0, 0, true, all, false); +// checkWidget(); + if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; + redrawWidget (0, 0, 0, 0, true, all, false); } /** @@ -2962,185 +2962,185 @@ * @see SWT#DOUBLE_BUFFERED */ public void redraw (int x, int y, int width, int height, bool all) { - checkWidget(); - if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; - redrawWidget (x, y, width, height, false, all, false); + checkWidget(); + if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; + redrawWidget (x, y, width, height, false, all, false); } void redrawChildren () { } void redrawWidget (int x, int y, int width, int height, bool redrawAll, bool all, bool trim) { - if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) is 0) return; - auto window = paintWindow (); - GdkRectangle rect; - if (redrawAll) { - int w, h; - OS.gdk_drawable_get_size (cast(GdkDrawable*)window, &w, &h); - rect.width = w; - rect.height = h; - } else { - rect.x = x; - rect.y = y; - rect.width = width; - rect.height = height; - } - OS.gdk_window_invalidate_rect (window, &rect, all); + if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) is 0) return; + auto window = paintWindow (); + GdkRectangle rect; + if (redrawAll) { + int w, h; + OS.gdk_drawable_get_size (cast(GdkDrawable*)window, &w, &h); + rect.width = w; + rect.height = h; + } else { + rect.x = x; + rect.y = y; + rect.width = width; + rect.height = height; + } + OS.gdk_window_invalidate_rect (window, &rect, all); } override void release (bool destroy) { - Control next = null, previous = null; - if (destroy && parent !is null) { - Control[] children = parent._getChildren (); - int index = 0; - while (index < children.length) { - if (children [index] is this) break; - index++; - } - if (0 < index && (index + 1) < children.length) { - next = children [index + 1]; - previous = children [index - 1]; - } - } - super.release (destroy); - if (destroy) { - if (previous !is null) previous.addRelation (next); - } + Control next = null, previous = null; + if (destroy && parent !is null) { + Control[] children = parent._getChildren (); + int index = 0; + while (index < children.length) { + if (children [index] is this) break; + index++; + } + if (0 < index && (index + 1) < children.length) { + next = children [index + 1]; + previous = children [index - 1]; + } + } + super.release (destroy); + if (destroy) { + if (previous !is null) previous.addRelation (next); + } } override void releaseHandle () { - super.releaseHandle (); - fixedHandle = null; - parent = null; + super.releaseHandle (); + fixedHandle = null; + parent = null; } override void releaseParent () { - parent.removeControl (this); + parent.removeControl (this); } override void releaseWidget () { - super.releaseWidget (); - if (display.currentControl is this) display.currentControl = null; - display.removeMouseHoverTimeout (handle); - auto imHandle = imHandle (); - if (imHandle !is null) { - OS.gtk_im_context_reset (imHandle); - OS.gtk_im_context_set_client_window (imHandle, null); - } - if (enableWindow !is null) { - OS.gdk_window_set_user_data (enableWindow, null); - OS.gdk_window_destroy (enableWindow); - enableWindow = null; - } - redrawWindow = null; - if (menu !is null && !menu.isDisposed ()) { - menu.dispose (); - } - menu = null; - cursor = null; - toolTipText = null; - layoutData = null; - accessible = null; + super.releaseWidget (); + if (display.currentControl is this) display.currentControl = null; + display.removeMouseHoverTimeout (handle); + auto imHandle = imHandle (); + if (imHandle !is null) { + OS.gtk_im_context_reset (imHandle); + OS.gtk_im_context_set_client_window (imHandle, null); + } + if (enableWindow !is null) { + OS.gdk_window_set_user_data (enableWindow, null); + OS.gdk_window_destroy (enableWindow); + enableWindow = null; + } + redrawWindow = null; + if (menu !is null && !menu.isDisposed ()) { + menu.dispose (); + } + menu = null; + cursor = null; + toolTipText = null; + layoutData = null; + accessible = null; } bool sendDragEvent (int button, int stateMask, int x, int y, bool isStateMask) { - Event event = new Event (); - event.button = button; - event.x = x; - event.y = y; - if (isStateMask) { - event.stateMask = stateMask; - } else { - setInputState (event, stateMask); - } - postEvent (SWT.DragDetect, event); - if (isDisposed ()) return false; - return event.doit; + Event event = new Event (); + event.button = button; + event.x = x; + event.y = y; + if (isStateMask) { + event.stateMask = stateMask; + } else { + setInputState (event, stateMask); + } + postEvent (SWT.DragDetect, event); + if (isDisposed ()) return false; + return event.doit; } void sendFocusEvent (int type) { - Shell shell = _getShell (); - Display display = this.display; - display.focusControl = this; - display.focusEvent = type; - sendEvent (type); - display.focusControl = null; - display.focusEvent = SWT.None; - /* - * It is possible that the shell may be - * disposed at this point. If this happens - * don't send the activate and deactivate - * events. - */ - if (!shell.isDisposed ()) { - switch (type) { - case SWT.FocusIn: - shell.setActiveControl (this); - break; - case SWT.FocusOut: - if (shell !is display.activeShell) { - shell.setActiveControl (null); - } - break; + Shell shell = _getShell (); + Display display = this.display; + display.focusControl = this; + display.focusEvent = type; + sendEvent (type); + display.focusControl = null; + display.focusEvent = SWT.None; + /* + * It is possible that the shell may be + * disposed at this point. If this happens + * don't send the activate and deactivate + * events. + */ + if (!shell.isDisposed ()) { + switch (type) { + case SWT.FocusIn: + shell.setActiveControl (this); + break; + case SWT.FocusOut: + if (shell !is display.activeShell) { + shell.setActiveControl (null); + } + break; default: - } - } + } + } } bool sendHelpEvent (int /*long*/ helpType) { - Control control = this; - while (control !is null) { - if (control.hooks (SWT.Help)) { - control.postEvent (SWT.Help); - return true; - } - control = control.parent; - } - return false; + Control control = this; + while (control !is null) { + if (control.hooks (SWT.Help)) { + control.postEvent (SWT.Help); + return true; + } + control = control.parent; + } + return false; } bool sendLeaveNotify() { - return false; + return false; } bool sendMouseEvent (int type, int button, int time, double x, double y, bool is_hint, int state) { - return sendMouseEvent (type, button, 0, 0, false, time, x, y, is_hint, state); + return sendMouseEvent (type, button, 0, 0, false, time, x, y, is_hint, state); } bool sendMouseEvent (int type, int button, int count, int detail, bool send, int time, double x, double y, bool is_hint, int state) { - if (!hooks (type) && !filters (type)) return true; - Event event = new Event (); - event.time = time; - event.button = button; - event.detail = detail; - event.count = count; - if (is_hint) { - event.x = cast(int)x; - event.y = cast(int)y; - } else { - auto window = eventWindow (); - int origin_x, origin_y; - OS.gdk_window_get_origin (window, &origin_x, &origin_y); - event.x = cast(int)x - origin_x; - event.y = cast(int)y - origin_y; - } - setInputState (event, state); - if (send) { - sendEvent (type, event); - if (isDisposed ()) return false; - } else { - postEvent (type, event); - } - return event.doit; + if (!hooks (type) && !filters (type)) return true; + Event event = new Event (); + event.time = time; + event.button = button; + event.detail = detail; + event.count = count; + if (is_hint) { + event.x = cast(int)x; + event.y = cast(int)y; + } else { + auto window = eventWindow (); + int origin_x, origin_y; + OS.gdk_window_get_origin (window, &origin_x, &origin_y); + event.x = cast(int)x - origin_x; + event.y = cast(int)y - origin_y; + } + setInputState (event, state); + if (send) { + sendEvent (type, event); + if (isDisposed ()) return false; + } else { + postEvent (type, event); + } + return event.doit; } void setBackground () { - if ((state & PARENT_BACKGROUND) !is 0 && (state & BACKGROUND) is 0 && backgroundImage is null) { - setParentBackground (); - } else { - setWidgetBackground (); - } - redrawWidget (0, 0, 0, 0, true, false, false); + if ((state & PARENT_BACKGROUND) !is 0 && (state & BACKGROUND) is 0 && backgroundImage is null) { + setParentBackground (); + } else { + setWidgetBackground (); + } + redrawWidget (0, 0, 0, 0, true, false, false); } /** @@ -3162,51 +3162,51 @@ * */ public void setBackground (Color color) { - checkWidget(); - if (((state & BACKGROUND) is 0) && color is null) return; - GdkColor* gdkColor = null; - if (color !is null) { - if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - gdkColor = color.handle; - } - bool set = false; - if (gdkColor is null) { - auto style = OS.gtk_widget_get_modifier_style (handle); - set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_BG) !is 0; - } else { - GdkColor* oldColor = getBackgroundColor (); - set = oldColor.pixel !is gdkColor.pixel; - } - if (set) { - if (color is null) { - state &= ~BACKGROUND; - } else { - state |= BACKGROUND; - } - setBackgroundColor (gdkColor); - redrawChildren (); - } + checkWidget(); + if (((state & BACKGROUND) is 0) && color is null) return; + GdkColor* gdkColor = null; + if (color !is null) { + if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + gdkColor = color.handle; + } + bool set = false; + if (gdkColor is null) { + auto style = OS.gtk_widget_get_modifier_style (handle); + set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_BG) !is 0; + } else { + GdkColor* oldColor = getBackgroundColor (); + set = oldColor.pixel !is gdkColor.pixel; + } + if (set) { + if (color is null) { + state &= ~BACKGROUND; + } else { + state |= BACKGROUND; + } + setBackgroundColor (gdkColor); + redrawChildren (); + } } void setBackgroundColor (GtkWidget* handle, GdkColor* color) { - int index = OS.GTK_STATE_NORMAL; - auto style = OS.gtk_widget_get_modifier_style (handle); - auto ptr = OS.gtk_rc_style_get_bg_pixmap_name (style, index); - if (ptr !is null) OS.g_free (ptr); - char[] name = color is null ? "" : "" ; - ptr = cast(char*)OS.g_malloc (name.length+1); + int index = OS.GTK_STATE_NORMAL; + auto style = OS.gtk_widget_get_modifier_style (handle); + auto ptr = OS.gtk_rc_style_get_bg_pixmap_name (style, index); + if (ptr !is null) OS.g_free (ptr); + char[] name = color is null ? "" : "" ; + ptr = cast(char*)OS.g_malloc (name.length+1); ptr[ 0 .. name.length ] = name; ptr[ name.length ] = '\0'; - OS.gtk_rc_style_set_bg_pixmap_name (style, index, ptr); - OS.gtk_rc_style_set_bg (style, index, color); - int flags = OS.gtk_rc_style_get_color_flags (style, index); - flags = (color is null) ? flags & ~OS.GTK_RC_BG : flags | OS.GTK_RC_BG; - OS.gtk_rc_style_set_color_flags (style, index, flags); - OS.gtk_widget_modify_style (handle, style); + OS.gtk_rc_style_set_bg_pixmap_name (style, index, ptr); + OS.gtk_rc_style_set_bg (style, index, color); + int flags = OS.gtk_rc_style_get_color_flags (style, index); + flags = (color is null) ? flags & ~OS.GTK_RC_BG : flags | OS.GTK_RC_BG; + OS.gtk_rc_style_set_color_flags (style, index, flags); + OS.gtk_widget_modify_style (handle, style); } void setBackgroundColor (GdkColor* color) { - setBackgroundColor (handle, color); + setBackgroundColor (handle, color); } /** @@ -3232,22 +3232,22 @@ * @since 3.2 */ public void setBackgroundImage (Image image) { - checkWidget (); - if (image !is null && image.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - if (image is backgroundImage) return; - this.backgroundImage = image; - if (backgroundImage !is null) { - setBackgroundPixmap (backgroundImage.pixmap); - redrawWidget (0, 0, 0, 0, true, false, false); - } else { - setWidgetBackground (); - } - redrawChildren (); + checkWidget (); + if (image !is null && image.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + if (image is backgroundImage) return; + this.backgroundImage = image; + if (backgroundImage !is null) { + setBackgroundPixmap (backgroundImage.pixmap); + redrawWidget (0, 0, 0, 0, true, false, false); + } else { + setWidgetBackground (); + } + redrawChildren (); } void setBackgroundPixmap (GdkDrawable* pixmap) { - auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); - if (window !is null) OS.gdk_window_set_back_pixmap (window, cast(GdkPixmap*)backgroundImage.pixmap, false); + auto window = OS.GTK_WIDGET_WINDOW (paintHandle ()); + if (window !is null) OS.gdk_window_set_back_pixmap (window, cast(GdkPixmap*)backgroundImage.pixmap, false); } /** @@ -3263,15 +3263,15 @@ * */ public void setCapture (bool capture) { - checkWidget(); - /* FIXME !!!!! */ - /* - if (capture) { - OS.gtk_widget_grab_focus (handle); - } else { - OS.gtk_widget_grab_default (handle); - } - */ + checkWidget(); + /* FIXME !!!!! */ + /* + if (capture) { + OS.gtk_widget_grab_focus (handle); + } else { + OS.gtk_widget_grab_default (handle); + } + */ } /** * Sets the receiver's cursor to the cursor specified by the @@ -3293,23 +3293,23 @@ * */ public void setCursor (Cursor cursor) { - checkWidget(); - if (cursor !is null && cursor.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); - this.cursor = cursor; - setCursor (cursor !is null ? cursor.handle : null); + checkWidget(); + if (cursor !is null && cursor.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); + this.cursor = cursor; + setCursor (cursor !is null ? cursor.handle : null); } void setCursor (GdkCursor* cursor) { - auto window = eventWindow (); - if (window !is null) { - OS.gdk_window_set_cursor (window, cursor); - if (!OS.GDK_WINDOWING_X11 ()) { - OS.gdk_flush (); - } else { - auto xDisplay = OS.GDK_DISPLAY (); - OS.XFlush (xDisplay); - } - } + auto window = eventWindow (); + if (window !is null) { + OS.gdk_window_set_cursor (window, cursor); + if (!OS.GDK_WINDOWING_X11 ()) { + OS.gdk_flush (); + } else { + auto xDisplay = OS.GDK_DISPLAY (); + OS.XFlush (xDisplay); + } + } } /** @@ -3327,12 +3327,12 @@ * @since 3.3 */ public void setDragDetect (bool dragDetect) { - checkWidget (); - if (dragDetect) { - state |= DRAG_DETECT; - } else { - state &= ~DRAG_DETECT; - } + checkWidget (); + if (dragDetect) { + state |= DRAG_DETECT; + } else { + state &= ~DRAG_DETECT; + } } /** @@ -3349,63 +3349,63 @@ * */ public void setEnabled (bool enabled) { - checkWidget(); - if (((state & DISABLED) is 0) is enabled) return; - Control control = null; - bool fixFocus_ = false; - if (!enabled) { - if (display.focusEvent !is SWT.FocusOut) { - control = display.getFocusControl (); - fixFocus_ = isFocusAncestor (control); - } - } - if (enabled) { - state &= ~DISABLED; - } else { - state |= DISABLED; - } - enableWidget (enabled); - if (isDisposed ()) return; - if (enabled) { - if (enableWindow !is null) { - OS.gdk_window_set_user_data (enableWindow, null); - OS.gdk_window_destroy (enableWindow); - enableWindow = null; - } - } else { - OS.gtk_widget_realize (handle); - auto parentHandle = parent.parentingHandle (); - auto window = OS.GTK_WIDGET_WINDOW (parentHandle); - Rectangle rect = getBounds (); - GdkWindowAttr attributes; - attributes.x = rect.x; - attributes.y = rect.y; - attributes.width = rect.width; - attributes.height = rect.height; - attributes.event_mask = (0xFFFFFFFF & ~OS.ExposureMask); - attributes.wclass = OS.GDK_INPUT_ONLY; - attributes.window_type = OS.GDK_WINDOW_CHILD; - enableWindow = OS.gdk_window_new (window, &attributes, OS.GDK_WA_X | OS.GDK_WA_Y); - if (enableWindow !is null) { - auto topHandle = topHandle (); - OS.gdk_window_set_user_data (enableWindow, parentHandle); - if (!OS.GDK_WINDOWING_X11 ()) { - OS.gdk_window_raise (enableWindow); - } else { - auto topWindow = OS.GTK_WIDGET_WINDOW (topHandle); - auto xDisplay = OS.gdk_x11_drawable_get_xdisplay (cast(GdkDrawable*)topWindow); - auto xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)enableWindow); - int xScreen = OS.XDefaultScreen (xDisplay); - int flags = OS.CWStackMode | OS.CWSibling; - XWindowChanges changes; - changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)topWindow); - changes.stack_mode = OS.Above; - OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); - } - if (OS.GTK_WIDGET_VISIBLE (topHandle)) OS.gdk_window_show_unraised (enableWindow); - } - } - if (fixFocus_) fixFocus (control); + checkWidget(); + if (((state & DISABLED) is 0) is enabled) return; + Control control = null; + bool fixFocus_ = false; + if (!enabled) { + if (display.focusEvent !is SWT.FocusOut) { + control = display.getFocusControl (); + fixFocus_ = isFocusAncestor (control); + } + } + if (enabled) { + state &= ~DISABLED; + } else { + state |= DISABLED; + } + enableWidget (enabled); + if (isDisposed ()) return; + if (enabled) { + if (enableWindow !is null) { + OS.gdk_window_set_user_data (enableWindow, null); + OS.gdk_window_destroy (enableWindow); + enableWindow = null; + } + } else { + OS.gtk_widget_realize (handle); + auto parentHandle = parent.parentingHandle (); + auto window = OS.GTK_WIDGET_WINDOW (parentHandle); + Rectangle rect = getBounds (); + GdkWindowAttr attributes; + attributes.x = rect.x; + attributes.y = rect.y; + attributes.width = rect.width; + attributes.height = rect.height; + attributes.event_mask = (0xFFFFFFFF & ~OS.ExposureMask); + attributes.wclass = OS.GDK_INPUT_ONLY; + attributes.window_type = OS.GDK_WINDOW_CHILD; + enableWindow = OS.gdk_window_new (window, &attributes, OS.GDK_WA_X | OS.GDK_WA_Y); + if (enableWindow !is null) { + auto topHandle = topHandle (); + OS.gdk_window_set_user_data (enableWindow, parentHandle); + if (!OS.GDK_WINDOWING_X11 ()) { + OS.gdk_window_raise (enableWindow); + } else { + auto topWindow = OS.GTK_WIDGET_WINDOW (topHandle); + auto xDisplay = OS.gdk_x11_drawable_get_xdisplay (cast(GdkDrawable*)topWindow); + auto xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)enableWindow); + int xScreen = OS.XDefaultScreen (xDisplay); + int flags = OS.CWStackMode | OS.CWSibling; + XWindowChanges changes; + changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)topWindow); + changes.stack_mode = OS.Above; + OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); + } + if (OS.GTK_WIDGET_VISIBLE (topHandle)) OS.gdk_window_show_unraised (enableWindow); + } + } + if (fixFocus_) fixFocus (control); } /** @@ -3423,9 +3423,9 @@ * @see #forceFocus */ public bool setFocus () { - checkWidget(); - if ((style & SWT.NO_FOCUS) !is 0) return false; - return forceFocus (); + checkWidget(); + if ((style & SWT.NO_FOCUS) !is 0) return false; + return forceFocus (); } /** @@ -3444,26 +3444,26 @@ * */ public void setFont (Font font) { - checkWidget(); - if (((state & FONT) is 0) && font is null) return; - this.font = font; - PangoFontDescription* fontDesc; - if (font is null) { - fontDesc = defaultFont (); - } else { - if (font.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - fontDesc = font.handle; - } - if (font is null) { - state &= ~FONT; - } else { - state |= FONT; - } - setFontDescription (fontDesc); + checkWidget(); + if (((state & FONT) is 0) && font is null) return; + this.font = font; + PangoFontDescription* fontDesc; + if (font is null) { + fontDesc = defaultFont (); + } else { + if (font.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + fontDesc = font.handle; + } + if (font is null) { + state &= ~FONT; + } else { + state |= FONT; + } + setFontDescription (fontDesc); } void setFontDescription (PangoFontDescription* font) { - OS.gtk_widget_modify_font (handle, font); + OS.gtk_widget_modify_font (handle, font); } /** @@ -3484,51 +3484,51 @@ * */ public void setForeground (Color color) { - checkWidget(); - if (((state & FOREGROUND) is 0) && color is null) return; - GdkColor* gdkColor = null; - if (color !is null) { - if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); - gdkColor = color.handle; - } - bool set = false; - if (gdkColor is null) { - auto style = OS.gtk_widget_get_modifier_style (handle); - set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_FG) !is 0; - } else { - GdkColor* oldColor = getForegroundColor (); - set = oldColor.pixel !is gdkColor.pixel; - } - if (set) { - if (color is null) { - state &= ~FOREGROUND; - } else { - state |= FOREGROUND; - } - setForegroundColor (gdkColor); - } + checkWidget(); + if (((state & FOREGROUND) is 0) && color is null) return; + GdkColor* gdkColor = null; + if (color !is null) { + if (color.isDisposed ()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); + gdkColor = color.handle; + } + bool set = false; + if (gdkColor is null) { + auto style = OS.gtk_widget_get_modifier_style (handle); + set = (OS.gtk_rc_style_get_color_flags (style, OS.GTK_STATE_NORMAL) & OS.GTK_RC_FG) !is 0; + } else { + GdkColor* oldColor = getForegroundColor (); + set = oldColor.pixel !is gdkColor.pixel; + } + if (set) { + if (color is null) { + state &= ~FOREGROUND; + } else { + state |= FOREGROUND; + } + setForegroundColor (gdkColor); + } } alias Widget.setForegroundColor setForegroundColor; void setForegroundColor (GdkColor* color) { - setForegroundColor (handle, color); + setForegroundColor (handle, color); } void setInitialBounds () { - if ((state & ZERO_WIDTH) !is 0 && (state & ZERO_HEIGHT) !is 0) { - /* - * Feature in GTK. On creation, each widget's allocation is - * initialized to a position of (-1, -1) until the widget is - * first sized. The fix is to set the value to (0, 0) as - * expected by SWT. - */ - auto topHandle = topHandle (); - OS.GTK_WIDGET_SET_X (topHandle, 0); - OS.GTK_WIDGET_SET_Y (topHandle, 0); - } else { - resizeHandle (1, 1); - forceResize (); - } + if ((state & ZERO_WIDTH) !is 0 && (state & ZERO_HEIGHT) !is 0) { + /* + * Feature in GTK. On creation, each widget's allocation is + * initialized to a position of (-1, -1) until the widget is + * first sized. The fix is to set the value to (0, 0) as + * expected by SWT. + */ + auto topHandle = topHandle (); + OS.GTK_WIDGET_SET_X (topHandle, 0); + OS.GTK_WIDGET_SET_Y (topHandle, 0); + } else { + resizeHandle (1, 1); + forceResize (); + } Stdout.formatln( "{}: setInitialBounds gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); } @@ -3559,23 +3559,23 @@ * */ public void setMenu (Menu menu) { - checkWidget(); - if (menu !is null) { - if ((menu.style & SWT.POP_UP) is 0) { - error (SWT.ERROR_MENU_NOT_POP_UP); - } - if (menu.parent !is menuShell ()) { - error (SWT.ERROR_INVALID_PARENT); - } - } - this.menu = menu; + checkWidget(); + if (menu !is null) { + if ((menu.style & SWT.POP_UP) is 0) { + error (SWT.ERROR_MENU_NOT_POP_UP); + } + if (menu.parent !is menuShell ()) { + error (SWT.ERROR_INVALID_PARENT); + } + } + this.menu = menu; } override void setOrientation () { - if ((style & SWT.RIGHT_TO_LEFT) !is 0) { - if (handle !is null) OS.gtk_widget_set_direction (handle, OS.GTK_TEXT_DIR_RTL); - if (fixedHandle !is null) OS.gtk_widget_set_direction (fixedHandle, OS.GTK_TEXT_DIR_RTL); - } + if ((style & SWT.RIGHT_TO_LEFT) !is 0) { + if (handle !is null) OS.gtk_widget_set_direction (handle, OS.GTK_TEXT_DIR_RTL); + if (fixedHandle !is null) OS.gtk_widget_set_direction (fixedHandle, OS.GTK_TEXT_DIR_RTL); + } } /** @@ -3593,44 +3593,44 @@ * @exception SWTException
      *
    • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
    • *
    • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
    • - *
    + * */ public bool setParent (Composite parent) { - checkWidget (); - if (parent is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); - if (parent.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); - if (this.parent is parent) return true; - if (!isReparentable ()) return false; - releaseParent (); - Shell newShell = parent.getShell (), oldShell = getShell (); - Decorations newDecorations = parent.menuShell (), oldDecorations = menuShell (); - Menu [] menus = oldShell.findMenus (this); - if (oldShell !is newShell || oldDecorations !is newDecorations) { - fixChildren (newShell, oldShell, newDecorations, oldDecorations, menus); - newDecorations.fixAccelGroup (); - oldDecorations.fixAccelGroup (); - } - auto topHandle = topHandle (); - auto newParent = parent.parentingHandle(); - int x = OS.GTK_WIDGET_X (topHandle); - int y = OS.GTK_WIDGET_Y (topHandle); - OS.gtk_widget_reparent (topHandle, newParent); - OS.gtk_fixed_move (cast(GtkFixed*)newParent, topHandle, x, y); - this.parent = parent; - setZOrder (null, false, true); - return true; + checkWidget (); + if (parent is null) SWT.error (SWT.ERROR_NULL_ARGUMENT); + if (parent.isDisposed()) SWT.error (SWT.ERROR_INVALID_ARGUMENT); + if (this.parent is parent) return true; + if (!isReparentable ()) return false; + releaseParent (); + Shell newShell = parent.getShell (), oldShell = getShell (); + Decorations newDecorations = parent.menuShell (), oldDecorations = menuShell (); + Menu [] menus = oldShell.findMenus (this); + if (oldShell !is newShell || oldDecorations !is newDecorations) { + fixChildren (newShell, oldShell, newDecorations, oldDecorations, menus); + newDecorations.fixAccelGroup (); + oldDecorations.fixAccelGroup (); + } + auto topHandle = topHandle (); + auto newParent = parent.parentingHandle(); + int x = OS.GTK_WIDGET_X (topHandle); + int y = OS.GTK_WIDGET_Y (topHandle); + OS.gtk_widget_reparent (topHandle, newParent); + OS.gtk_fixed_move (cast(GtkFixed*)newParent, topHandle, x, y); + this.parent = parent; + setZOrder (null, false, true); + return true; } void setParentBackground () { - setBackgroundColor (handle, null); - if (fixedHandle !is null) setBackgroundColor (fixedHandle, null); + setBackgroundColor (handle, null); + if (fixedHandle !is null) setBackgroundColor (fixedHandle, null); } void setParentWindow (GtkWidget* widget) { } bool setRadioSelection (bool value) { - return false; + return false; } /** @@ -3657,50 +3657,50 @@ * @see #update() */ public void setRedraw (bool redraw) { - checkWidget(); - if (redraw) { - if (--drawCount is 0) { - if (redrawWindow !is null) { - auto window = paintWindow (); - /* Explicitly hiding the window avoids flicker on GTK+ >= 2.6 */ - OS.gdk_window_hide (redrawWindow); - OS.gdk_window_destroy (redrawWindow); - OS.gdk_window_set_events (window, OS.gtk_widget_get_events (paintHandle ())); - redrawWindow = null; - } - } - } else { - if (drawCount++ is 0) { - if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) !is 0) { - auto window = paintWindow (); - Rectangle rect = getBounds (); - GdkWindowAttr attributes; - attributes.width = rect.width; - attributes.height = rect.height; - attributes.event_mask = OS.GDK_EXPOSURE_MASK; - attributes.window_type = OS.GDK_WINDOW_CHILD; - redrawWindow = OS.gdk_window_new (window, &attributes, 0); - if (redrawWindow !is null) { - int mouseMask = OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | - OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK | - OS.GDK_POINTER_MOTION_MASK | OS.GDK_POINTER_MOTION_HINT_MASK | - OS.GDK_BUTTON_MOTION_MASK | OS.GDK_BUTTON1_MOTION_MASK | - OS.GDK_BUTTON2_MOTION_MASK | OS.GDK_BUTTON3_MOTION_MASK; - OS.gdk_window_set_events (window, OS.gdk_window_get_events (window) & ~mouseMask); - OS.gdk_window_set_back_pixmap (redrawWindow, null, false); - OS.gdk_window_show (redrawWindow); - } - } - } - } + checkWidget(); + if (redraw) { + if (--drawCount is 0) { + if (redrawWindow !is null) { + auto window = paintWindow (); + /* Explicitly hiding the window avoids flicker on GTK+ >= 2.6 */ + OS.gdk_window_hide (redrawWindow); + OS.gdk_window_destroy (redrawWindow); + OS.gdk_window_set_events (window, OS.gtk_widget_get_events (paintHandle ())); + redrawWindow = null; + } + } + } else { + if (drawCount++ is 0) { + if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) !is 0) { + auto window = paintWindow (); + Rectangle rect = getBounds (); + GdkWindowAttr attributes; + attributes.width = rect.width; + attributes.height = rect.height; + attributes.event_mask = OS.GDK_EXPOSURE_MASK; + attributes.window_type = OS.GDK_WINDOW_CHILD; + redrawWindow = OS.gdk_window_new (window, &attributes, 0); + if (redrawWindow !is null) { + int mouseMask = OS.GDK_BUTTON_PRESS_MASK | OS.GDK_BUTTON_RELEASE_MASK | + OS.GDK_ENTER_NOTIFY_MASK | OS.GDK_LEAVE_NOTIFY_MASK | + OS.GDK_POINTER_MOTION_MASK | OS.GDK_POINTER_MOTION_HINT_MASK | + OS.GDK_BUTTON_MOTION_MASK | OS.GDK_BUTTON1_MOTION_MASK | + OS.GDK_BUTTON2_MOTION_MASK | OS.GDK_BUTTON3_MOTION_MASK; + OS.gdk_window_set_events (window, OS.gdk_window_get_events (window) & ~mouseMask); + OS.gdk_window_set_back_pixmap (redrawWindow, null, false); + OS.gdk_window_show (redrawWindow); + } + } + } + } } bool setTabGroupFocus (bool next) { - return setTabItemFocus (next); + return setTabItemFocus (next); } bool setTabItemFocus (bool next) { - if (!isShowing ()) return false; - return forceFocus (); + if (!isShowing ()) return false; + return forceFocus (); } /** @@ -3715,13 +3715,13 @@ * */ public void setToolTipText (char[] str) { - checkWidget(); - setToolTipText (_getShell (), str); - toolTipText = str; + checkWidget(); + setToolTipText (_getShell (), str); + toolTipText = str; } void setToolTipText (Shell shell, char[] newString) { - shell.setToolTipText (eventHandle (), newString); + shell.setToolTipText (eventHandle (), newString); } /** @@ -3741,251 +3741,251 @@ * */ public void setVisible (bool visible) { - checkWidget(); - if (((state & HIDDEN) is 0) is visible) return; - auto topHandle = topHandle(); - if (visible) { - /* - * It is possible (but unlikely), that application - * code could have disposed the widget in the show - * event. If this happens, just return. - */ - sendEvent (SWT.Show); - if (isDisposed ()) return; - state &= ~HIDDEN; - if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) is 0) { - if (enableWindow !is null) OS.gdk_window_show_unraised (enableWindow); - OS.gtk_widget_show (topHandle); - } - } else { - /* - * Bug in GTK. Invoking gtk_widget_hide() on a widget that has - * focus causes a focus_out_event to be sent. If the client disposes - * the widget inside the event, GTK GP's. The fix is to reassign focus - * before hiding the widget. - * - * NOTE: In order to stop the same widget from taking focus, - * temporarily clear and set the GTK_VISIBLE flag. - */ - Control control = null; - bool fixFocus_ = false; - if (display.focusEvent !is SWT.FocusOut) { - control = display.getFocusControl (); - fixFocus_ = isFocusAncestor (control); - } - state |= HIDDEN; - if (fixFocus_) { - OS.GTK_WIDGET_UNSET_FLAGS (topHandle, OS.GTK_VISIBLE); - fixFocus (control); - if (isDisposed ()) return; - OS.GTK_WIDGET_SET_FLAGS (topHandle, OS.GTK_VISIBLE); - } - OS.gtk_widget_hide (topHandle); - if (isDisposed ()) return; - if (enableWindow !is null) OS.gdk_window_hide (enableWindow); - sendEvent (SWT.Hide); - } + checkWidget(); + if (((state & HIDDEN) is 0) is visible) return; + auto topHandle = topHandle(); + if (visible) { + /* + * It is possible (but unlikely), that application + * code could have disposed the widget in the show + * event. If this happens, just return. + */ + sendEvent (SWT.Show); + if (isDisposed ()) return; + state &= ~HIDDEN; + if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) is 0) { + if (enableWindow !is null) OS.gdk_window_show_unraised (enableWindow); + OS.gtk_widget_show (topHandle); + } + } else { + /* + * Bug in GTK. Invoking gtk_widget_hide() on a widget that has + * focus causes a focus_out_event to be sent. If the client disposes + * the widget inside the event, GTK GP's. The fix is to reassign focus + * before hiding the widget. + * + * NOTE: In order to stop the same widget from taking focus, + * temporarily clear and set the GTK_VISIBLE flag. + */ + Control control = null; + bool fixFocus_ = false; + if (display.focusEvent !is SWT.FocusOut) { + control = display.getFocusControl (); + fixFocus_ = isFocusAncestor (control); + } + state |= HIDDEN; + if (fixFocus_) { + OS.GTK_WIDGET_UNSET_FLAGS (topHandle, OS.GTK_VISIBLE); + fixFocus (control); + if (isDisposed ()) return; + OS.GTK_WIDGET_SET_FLAGS (topHandle, OS.GTK_VISIBLE); + } + OS.gtk_widget_hide (topHandle); + if (isDisposed ()) return; + if (enableWindow !is null) OS.gdk_window_hide (enableWindow); + sendEvent (SWT.Hide); + } } void setZOrder (Control sibling, bool above, bool fixRelations) { - setZOrder (sibling, above, fixRelations, true); + setZOrder (sibling, above, fixRelations, true); } void setZOrder (Control sibling, bool above, bool fixRelations, bool fixChildren) { - int index = 0, siblingIndex = 0, oldNextIndex = -1; - Control[] children = null; - if (fixRelations) { - /* determine the receiver's and sibling's indexes in the parent */ - children = parent._getChildren (); - while (index < children.length) { - if (children [index] is this) break; - index++; - } - if (sibling !is null) { - while (siblingIndex < children.length) { - if (children [siblingIndex] is sibling) break; - siblingIndex++; - } - } - /* remove "Labelled by" relationships that will no longer be valid */ - removeRelation (); - if (index + 1 < children.length) { - oldNextIndex = index + 1; - children [oldNextIndex].removeRelation (); - } - if (sibling !is null) { - if (above) { - sibling.removeRelation (); - } else { - if (siblingIndex + 1 < children.length) { - children [siblingIndex + 1].removeRelation (); - } - } - } - } - - auto topHandle = topHandle (); - auto siblingHandle = sibling !is null ? sibling.topHandle () : null; - auto window = OS.GTK_WIDGET_WINDOW (topHandle); - if (window !is null) { - GdkWindow* siblingWindow; - if (sibling !is null) { - if (above && sibling.enableWindow !is null) { - siblingWindow = enableWindow; - } else { - siblingWindow = OS.GTK_WIDGET_WINDOW (siblingHandle); - } - } - auto redrawWindow = fixChildren ? parent.redrawWindow : null; - if (!OS.GDK_WINDOWING_X11 () || (siblingWindow is null && (!above || redrawWindow is null))) { - if (above) { - OS.gdk_window_raise (window); - if (redrawWindow !is null) OS.gdk_window_raise (redrawWindow); - if (enableWindow !is null) OS.gdk_window_raise (enableWindow); - } else { - if (enableWindow !is null) OS.gdk_window_lower (enableWindow); - OS.gdk_window_lower (window); - } - } else { - XWindowChanges changes; - changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)(siblingWindow !is null ? siblingWindow : redrawWindow)); - changes.stack_mode = above ? OS.Above : OS.Below; - if (redrawWindow !is null && siblingWindow is null) changes.stack_mode = OS.Below; - auto xDisplay = OS.gdk_x11_drawable_get_xdisplay (cast(GdkDrawable*)window); - auto xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)window); - int xScreen = OS.XDefaultScreen (xDisplay); - int flags = OS.CWStackMode | OS.CWSibling; - /* - * Feature in X. If the receiver is a top level, XConfigureWindow () - * will fail (with a BadMatch error) for top level shells because top - * level shells are reparented by the window manager and do not share - * the same X window parent. This is the correct behavior but it is - * unexpected. The fix is to use XReconfigureWMWindow () instead. - * When the receiver is not a top level shell, XReconfigureWMWindow () - * behaves the same as XConfigureWindow (). - */ - OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); - if (enableWindow !is null) { - changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)window); - changes.stack_mode = OS.Above; - xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)enableWindow); - OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); - } - } - } + int index = 0, siblingIndex = 0, oldNextIndex = -1; + Control[] children = null; + if (fixRelations) { + /* determine the receiver's and sibling's indexes in the parent */ + children = parent._getChildren (); + while (index < children.length) { + if (children [index] is this) break; + index++; + } + if (sibling !is null) { + while (siblingIndex < children.length) { + if (children [siblingIndex] is sibling) break; + siblingIndex++; + } + } + /* remove "Labelled by" relationships that will no longer be valid */ + removeRelation (); + if (index + 1 < children.length) { + oldNextIndex = index + 1; + children [oldNextIndex].removeRelation (); + } + if (sibling !is null) { + if (above) { + sibling.removeRelation (); + } else { + if (siblingIndex + 1 < children.length) { + children [siblingIndex + 1].removeRelation (); + } + } + } + } + + auto topHandle = topHandle (); + auto siblingHandle = sibling !is null ? sibling.topHandle () : null; + auto window = OS.GTK_WIDGET_WINDOW (topHandle); + if (window !is null) { + GdkWindow* siblingWindow; + if (sibling !is null) { + if (above && sibling.enableWindow !is null) { + siblingWindow = enableWindow; + } else { + siblingWindow = OS.GTK_WIDGET_WINDOW (siblingHandle); + } + } + auto redrawWindow = fixChildren ? parent.redrawWindow : null; + if (!OS.GDK_WINDOWING_X11 () || (siblingWindow is null && (!above || redrawWindow is null))) { + if (above) { + OS.gdk_window_raise (window); + if (redrawWindow !is null) OS.gdk_window_raise (redrawWindow); + if (enableWindow !is null) OS.gdk_window_raise (enableWindow); + } else { + if (enableWindow !is null) OS.gdk_window_lower (enableWindow); + OS.gdk_window_lower (window); + } + } else { + XWindowChanges changes; + changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)(siblingWindow !is null ? siblingWindow : redrawWindow)); + changes.stack_mode = above ? OS.Above : OS.Below; + if (redrawWindow !is null && siblingWindow is null) changes.stack_mode = OS.Below; + auto xDisplay = OS.gdk_x11_drawable_get_xdisplay (cast(GdkDrawable*)window); + auto xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)window); + int xScreen = OS.XDefaultScreen (xDisplay); + int flags = OS.CWStackMode | OS.CWSibling; + /* + * Feature in X. If the receiver is a top level, XConfigureWindow () + * will fail (with a BadMatch error) for top level shells because top + * level shells are reparented by the window manager and do not share + * the same X window parent. This is the correct behavior but it is + * unexpected. The fix is to use XReconfigureWMWindow () instead. + * When the receiver is not a top level shell, XReconfigureWMWindow () + * behaves the same as XConfigureWindow (). + */ + OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); + if (enableWindow !is null) { + changes.sibling = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)window); + changes.stack_mode = OS.Above; + xWindow = OS.gdk_x11_drawable_get_xid (cast(GdkDrawable*)enableWindow); + OS.XReconfigureWMWindow (xDisplay, xWindow, xScreen, flags, &changes); + } + } + } Stdout.formatln( "{}: setZOrder gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); - if (fixChildren) { - if (above) { + if (fixChildren) { + if (above) { Stdout.formatln( "{}: setZOrder gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); - parent.moveAbove (topHandle, siblingHandle); - } else { + parent.moveAbove (topHandle, siblingHandle); + } else { Stdout.formatln( "{}: setZOrder gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); - parent.moveBelow (topHandle, siblingHandle); - } - } + parent.moveBelow (topHandle, siblingHandle); + } + } Stdout.formatln( "{}: setZOrder gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); - /* Make sure that the parent internal windows are on the bottom of the stack */ - if (!above && fixChildren) parent.fixZOrder (); + /* Make sure that the parent internal windows are on the bottom of the stack */ + if (!above && fixChildren) parent.fixZOrder (); Stdout.formatln( "{}: setZOrder gtk_container_get_children {:x}", __LINE__, parent.parentingHandle() ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parent.parentingHandle()) ); - if (fixRelations) { - /* determine the receiver's new index in the parent */ - if (sibling !is null) { - if (above) { - index = siblingIndex - (index < siblingIndex ? 1 : 0); - } else { - index = siblingIndex + (siblingIndex < index ? 1 : 0); - } - } else { - if (above) { - index = 0; - } else { - index = children.length - 1; - } - } - - /* add new "Labelled by" relations as needed */ - children = parent._getChildren (); - if (0 < index) { - children [index - 1].addRelation (this); - } - if (index + 1 < children.length) { - addRelation (children [index + 1]); - } - if (oldNextIndex !is -1) { - if (oldNextIndex <= index) oldNextIndex--; - /* the last two conditions below ensure that duplicate relations are not hooked */ - if (0 < oldNextIndex && oldNextIndex !is index && oldNextIndex !is index + 1) { - children [oldNextIndex - 1].addRelation (children [oldNextIndex]); - } - } - } + if (fixRelations) { + /* determine the receiver's new index in the parent */ + if (sibling !is null) { + if (above) { + index = siblingIndex - (index < siblingIndex ? 1 : 0); + } else { + index = siblingIndex + (siblingIndex < index ? 1 : 0); + } + } else { + if (above) { + index = 0; + } else { + index = children.length - 1; + } + } + + /* add new "Labelled by" relations as needed */ + children = parent._getChildren (); + if (0 < index) { + children [index - 1].addRelation (this); + } + if (index + 1 < children.length) { + addRelation (children [index + 1]); + } + if (oldNextIndex !is -1) { + if (oldNextIndex <= index) oldNextIndex--; + /* the last two conditions below ensure that duplicate relations are not hooked */ + if (0 < oldNextIndex && oldNextIndex !is index && oldNextIndex !is index + 1) { + children [oldNextIndex - 1].addRelation (children [oldNextIndex]); + } + } + } } void setWidgetBackground () { - if (fixedHandle !is null) { - auto style = OS.gtk_widget_get_modifier_style (fixedHandle); - OS.gtk_widget_modify_style (fixedHandle, style); - } - auto style = OS.gtk_widget_get_modifier_style (handle); - OS.gtk_widget_modify_style (handle, style); + if (fixedHandle !is null) { + auto style = OS.gtk_widget_get_modifier_style (fixedHandle); + OS.gtk_widget_modify_style (fixedHandle, style); + } + auto style = OS.gtk_widget_get_modifier_style (handle); + OS.gtk_widget_modify_style (handle, style); } bool showMenu (int x, int y) { - Event event = new Event (); - event.x = x; - event.y = y; - sendEvent (SWT.MenuDetect, event); - if (event.doit) { - if (menu !is null && !menu.isDisposed ()) { - bool hooksKeys = hooks (SWT.KeyDown) || hooks (SWT.KeyUp); - menu.createIMMenu (hooksKeys ? imHandle() : null); - if (event.x !is x || event.y !is y) { - menu.setLocation (event.x, event.y); - } - menu.setVisible (true); - return true; - } - } - return false; + Event event = new Event (); + event.x = x; + event.y = y; + sendEvent (SWT.MenuDetect, event); + if (event.doit) { + if (menu !is null && !menu.isDisposed ()) { + bool hooksKeys = hooks (SWT.KeyDown) || hooks (SWT.KeyUp); + menu.createIMMenu (hooksKeys ? imHandle() : null); + if (event.x !is x || event.y !is y) { + menu.setLocation (event.x, event.y); + } + menu.setVisible (true); + return true; + } + } + return false; } void showWidget () { - // Comment this line to disable zero-sized widgets - state |= ZERO_WIDTH | ZERO_HEIGHT; - auto topHandle = topHandle (); - auto parentHandle = parent.parentingHandle (); - parent.setParentWindow (topHandle); + // Comment this line to disable zero-sized widgets + state |= ZERO_WIDTH | ZERO_HEIGHT; + auto topHandle = topHandle (); + auto parentHandle = parent.parentingHandle (); + parent.setParentWindow (topHandle); Stdout.formatln( "showWidget {:x} {}", parentHandle, topHandle ); Stdout.formatln( "showWidget gtk_container_get_children {:x}", parentHandle ); Stdout.formatln( "=> {}", OS.gtk_container_get_children (cast(GtkContainer*)parentHandle) ); - OS.gtk_container_add (cast(GtkContainer*)parentHandle, topHandle); + OS.gtk_container_add (cast(GtkContainer*)parentHandle, topHandle); if (handle !is null && handle !is topHandle) OS.gtk_widget_show (handle); - if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) is 0) { - if (fixedHandle !is null) OS.gtk_widget_show (fixedHandle); - } - if (fixedHandle !is null) fixStyle (fixedHandle); + if ((state & (ZERO_WIDTH | ZERO_HEIGHT)) is 0) { + if (fixedHandle !is null) OS.gtk_widget_show (fixedHandle); + } + if (fixedHandle !is null) fixStyle (fixedHandle); } void sort (int [] items) { - /* Shell Sort from K&R, pg 108 */ - int length = items.length; - for (int gap=length/2; gap>0; gap/=2) { - for (int i=gap; i=0; j-=gap) { - if (items [j] <= items [j + gap]) { - int swap = items [j]; - items [j] = items [j + gap]; - items [j + gap] = swap; - } - } - } - } + /* Shell Sort from K&R, pg 108 */ + int length = items.length; + for (int gap=length/2; gap>0; gap/=2) { + for (int i=gap; i=0; j-=gap) { + if (items [j] <= items [j + gap]) { + int swap = items [j]; + items [j] = items [j + gap]; + items [j + gap] = swap; + } + } + } + } } /** @@ -4004,199 +4004,199 @@ * */ public bool traverse (int traversal) { - checkWidget (); - Event event = new Event (); - event.doit = true; - event.detail = traversal; - return traverse (event); + checkWidget (); + Event event = new Event (); + event.doit = true; + event.detail = traversal; + return traverse (event); } bool translateMnemonic (Event event, Control control) { - if (control is this) return false; - if (!isVisible () || !isEnabled ()) return false; - event.doit = this is display.mnemonicControl || mnemonicMatch (event.character); - return traverse (event); + if (control is this) return false; + if (!isVisible () || !isEnabled ()) return false; + event.doit = this is display.mnemonicControl || mnemonicMatch (event.character); + return traverse (event); } bool translateMnemonic (int keyval, GdkEventKey* gdkEvent) { - int key = OS.gdk_keyval_to_unicode (keyval); - if (key < 0x20) return false; - if (gdkEvent.state is 0) { - int code = traversalCode (keyval, gdkEvent); - if ((code & SWT.TRAVERSE_MNEMONIC) is 0) return false; - } else { - Shell shell = _getShell (); - int mask = OS.GDK_CONTROL_MASK | OS.GDK_SHIFT_MASK | OS.GDK_MOD1_MASK; - if ((gdkEvent.state & mask) !is OS.gtk_window_get_mnemonic_modifier (cast(GtkWindow*)shell.shellHandle)) return false; - } - Decorations shell = menuShell (); - if (shell.isVisible () && shell.isEnabled ()) { - Event event = new Event (); - event.detail = SWT.TRAVERSE_MNEMONIC; - if (setKeyState (event, gdkEvent)) { - return translateMnemonic (event, null) || shell.translateMnemonic (event, this); - } - } - return false; + int key = OS.gdk_keyval_to_unicode (keyval); + if (key < 0x20) return false; + if (gdkEvent.state is 0) { + int code = traversalCode (keyval, gdkEvent); + if ((code & SWT.TRAVERSE_MNEMONIC) is 0) return false; + } else { + Shell shell = _getShell (); + int mask = OS.GDK_CONTROL_MASK | OS.GDK_SHIFT_MASK | OS.GDK_MOD1_MASK; + if ((gdkEvent.state & mask) !is OS.gtk_window_get_mnemonic_modifier (cast(GtkWindow*)shell.shellHandle)) return false; + } + Decorations shell = menuShell (); + if (shell.isVisible () && shell.isEnabled ()) { + Event event = new Event (); + event.detail = SWT.TRAVERSE_MNEMONIC; + if (setKeyState (event, gdkEvent)) { + return translateMnemonic (event, null) || shell.translateMnemonic (event, this); + } + } + return false; } bool translateTraversal (GdkEventKey* keyEvent) { - int detail = SWT.TRAVERSE_NONE; - int key = keyEvent.keyval; - int code = traversalCode (key, keyEvent); - bool all = false; - switch (key) { - case OS.GDK_Escape: { - all = true; - detail = SWT.TRAVERSE_ESCAPE; - break; - } - case OS.GDK_KP_Enter: - case OS.GDK_Return: { - all = true; - detail = SWT.TRAVERSE_RETURN; - break; - } - case OS.GDK_ISO_Left_Tab: - case OS.GDK_Tab: { - bool next = (keyEvent.state & OS.GDK_SHIFT_MASK) is 0; - detail = next ? SWT.TRAVERSE_TAB_NEXT : SWT.TRAVERSE_TAB_PREVIOUS; - break; - } - case OS.GDK_Up: - case OS.GDK_Left: - case OS.GDK_Down: - case OS.GDK_Right: { - bool next = key is OS.GDK_Down || key is OS.GDK_Right; - detail = next ? SWT.TRAVERSE_ARROW_NEXT : SWT.TRAVERSE_ARROW_PREVIOUS; - break; - } - case OS.GDK_Page_Up: - case OS.GDK_Page_Down: { - all = true; - if ((keyEvent.state & OS.GDK_CONTROL_MASK) is 0) return false; - detail = key is OS.GDK_Page_Down ? SWT.TRAVERSE_PAGE_NEXT : SWT.TRAVERSE_PAGE_PREVIOUS; - break; - } - default: - return false; - } - Event event = new Event (); - event.doit = (code & detail) !is 0; - event.detail = detail; - event.time = keyEvent.time; - if (!setKeyState (event, keyEvent)) return false; - Shell shell = getShell (); - Control control = this; - do { - if (control.traverse (event)) return true; - if (!event.doit && control.hooks (SWT.Traverse)) return false; - if (control is shell) return false; - control = control.parent; - } while (all && control !is null); - return false; + int detail = SWT.TRAVERSE_NONE; + int key = keyEvent.keyval; + int code = traversalCode (key, keyEvent); + bool all = false; + switch (key) { + case OS.GDK_Escape: { + all = true; + detail = SWT.TRAVERSE_ESCAPE; + break; + } + case OS.GDK_KP_Enter: + case OS.GDK_Return: { + all = true; + detail = SWT.TRAVERSE_RETURN; + break; + } + case OS.GDK_ISO_Left_Tab: + case OS.GDK_Tab: { + bool next = (keyEvent.state & OS.GDK_SHIFT_MASK) is 0; + detail = next ? SWT.TRAVERSE_TAB_NEXT : SWT.TRAVERSE_TAB_PREVIOUS; + break; + } + case OS.GDK_Up: + case OS.GDK_Left: + case OS.GDK_Down: + case OS.GDK_Right: { + bool next = key is OS.GDK_Down || key is OS.GDK_Right; + detail = next ? SWT.TRAVERSE_ARROW_NEXT : SWT.TRAVERSE_ARROW_PREVIOUS; + break; + } + case OS.GDK_Page_Up: + case OS.GDK_Page_Down: { + all = true; + if ((keyEvent.state & OS.GDK_CONTROL_MASK) is 0) return false; + detail = key is OS.GDK_Page_Down ? SWT.TRAVERSE_PAGE_NEXT : SWT.TRAVERSE_PAGE_PREVIOUS; + break; + } + default: + return false; + } + Event event = new Event (); + event.doit = (code & detail) !is 0; + event.detail = detail; + event.time = keyEvent.time; + if (!setKeyState (event, keyEvent)) return false; + Shell shell = getShell (); + Control control = this; + do { + if (control.traverse (event)) return true; + if (!event.doit && control.hooks (SWT.Traverse)) return false; + if (control is shell) return false; + control = control.parent; + } while (all && control !is null); + return false; } int traversalCode (int key, GdkEventKey* event) { - int code = SWT.TRAVERSE_RETURN | SWT.TRAVERSE_TAB_NEXT | SWT.TRAVERSE_TAB_PREVIOUS | SWT.TRAVERSE_PAGE_NEXT | SWT.TRAVERSE_PAGE_PREVIOUS; - Shell shell = getShell (); - if (shell.parent !is null) code |= SWT.TRAVERSE_ESCAPE; - return code; + int code = SWT.TRAVERSE_RETURN | SWT.TRAVERSE_TAB_NEXT | SWT.TRAVERSE_TAB_PREVIOUS | SWT.TRAVERSE_PAGE_NEXT | SWT.TRAVERSE_PAGE_PREVIOUS; + Shell shell = getShell (); + if (shell.parent !is null) code |= SWT.TRAVERSE_ESCAPE; + return code; } bool traverse (Event event) { - /* - * It is possible (but unlikely), that application - * code could have disposed the widget in the traverse - * event. If this happens, return true to stop further - * event processing. - */ - sendEvent (SWT.Traverse, event); - if (isDisposed ()) return true; - if (!event.doit) return false; - switch (event.detail) { - case SWT.TRAVERSE_NONE: return true; - case SWT.TRAVERSE_ESCAPE: return traverseEscape (); - case SWT.TRAVERSE_RETURN: return traverseReturn (); - case SWT.TRAVERSE_TAB_NEXT: return traverseGroup (true); - case SWT.TRAVERSE_TAB_PREVIOUS: return traverseGroup (false); - case SWT.TRAVERSE_ARROW_NEXT: return traverseItem (true); - case SWT.TRAVERSE_ARROW_PREVIOUS: return traverseItem (false); - case SWT.TRAVERSE_MNEMONIC: return traverseMnemonic (event.character); - case SWT.TRAVERSE_PAGE_NEXT: return traversePage (true); - case SWT.TRAVERSE_PAGE_PREVIOUS: return traversePage (false); + /* + * It is possible (but unlikely), that application + * code could have disposed the widget in the traverse + * event. If this happens, return true to stop further + * event processing. + */ + sendEvent (SWT.Traverse, event); + if (isDisposed ()) return true; + if (!event.doit) return false; + switch (event.detail) { + case SWT.TRAVERSE_NONE: return true; + case SWT.TRAVERSE_ESCAPE: return traverseEscape (); + case SWT.TRAVERSE_RETURN: return traverseReturn (); + case SWT.TRAVERSE_TAB_NEXT: return traverseGroup (true); + case SWT.TRAVERSE_TAB_PREVIOUS: return traverseGroup (false); + case SWT.TRAVERSE_ARROW_NEXT: return traverseItem (true); + case SWT.TRAVERSE_ARROW_PREVIOUS: return traverseItem (false); + case SWT.TRAVERSE_MNEMONIC: return traverseMnemonic (event.character); + case SWT.TRAVERSE_PAGE_NEXT: return traversePage (true); + case SWT.TRAVERSE_PAGE_PREVIOUS: return traversePage (false); default: - } - return false; + } + return false; } bool traverseEscape () { - return false; + return false; } bool traverseGroup (bool next) { - Control root = computeTabRoot (); - Control group = computeTabGroup (); - Control [] list = root.computeTabList (); - int length = list.length; - int index = 0; - while (index < length) { - if (list [index] is group) break; - index++; - } - /* - * It is possible (but unlikely), that application - * code could have disposed the widget in focus in - * or out events. Ensure that a disposed widget is - * not accessed. - */ - if (index is length) return false; - int start = index, offset = (next) ? 1 : -1; - while ((index = ((index + offset + length) % length)) !is start) { - Control control = list [index]; - if (!control.isDisposed () && control.setTabGroupFocus (next)) { - return true; - } - } - if (group.isDisposed ()) return false; - return group.setTabGroupFocus (next); + Control root = computeTabRoot (); + Control group = computeTabGroup (); + Control [] list = root.computeTabList (); + int length = list.length; + int index = 0; + while (index < length) { + if (list [index] is group) break; + index++; + } + /* + * It is possible (but unlikely), that application + * code could have disposed the widget in focus in + * or out events. Ensure that a disposed widget is + * not accessed. + */ + if (index is length) return false; + int start = index, offset = (next) ? 1 : -1; + while ((index = ((index + offset + length) % length)) !is start) { + Control control = list [index]; + if (!control.isDisposed () && control.setTabGroupFocus (next)) { + return true; + } + } + if (group.isDisposed ()) return false; + return group.setTabGroupFocus (next); } bool traverseItem (bool next) { - Control [] children = parent._getChildren (); - int length = children.length; - int index = 0; - while (index < length) { - if (children [index] is this) break; - index++; - } - /* - * It is possible (but unlikely), that application - * code could have disposed the widget in focus in - * or out events. Ensure that a disposed widget is - * not accessed. - */ - if (index is length) return false; - int start = index, offset = (next) ? 1 : -1; - while ((index = (index + offset + length) % length) !is start) { - Control child = children [index]; - if (!child.isDisposed () && child.isTabItem ()) { - if (child.setTabItemFocus (next)) return true; - } - } - return false; + Control [] children = parent._getChildren (); + int length = children.length; + int index = 0; + while (index < length) { + if (children [index] is this) break; + index++; + } + /* + * It is possible (but unlikely), that application + * code could have disposed the widget in focus in + * or out events. Ensure that a disposed widget is + * not accessed. + */ + if (index is length) return false; + int start = index, offset = (next) ? 1 : -1; + while ((index = (index + offset + length) % length) !is start) { + Control child = children [index]; + if (!child.isDisposed () && child.isTabItem ()) { + if (child.setTabItemFocus (next)) return true; + } + } + return false; } bool traverseReturn () { - return false; + return false; } bool traversePage (bool next) { - return false; + return false; } bool traverseMnemonic (char key) { - return mnemonicHit (key); + return mnemonicHit (key); } /** @@ -4219,57 +4219,57 @@ * @see SWT#Paint */ public void update () { - checkWidget (); - update (false, true); + checkWidget (); + update (false, true); } void update (bool all, bool flush) { -// checkWidget(); - if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; - if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) is 0) return; - auto window = paintWindow (); - if (flush) display.flushExposes (window, all); - OS.gdk_window_process_updates (window, all); - OS.gdk_flush (); +// checkWidget(); + if (!OS.GTK_WIDGET_VISIBLE (topHandle ())) return; + if ((OS.GTK_WIDGET_FLAGS (handle) & OS.GTK_REALIZED) is 0) return; + auto window = paintWindow (); + if (flush) display.flushExposes (window, all); + OS.gdk_window_process_updates (window, all); + OS.gdk_flush (); } void updateBackgroundMode () { - int oldState = state & PARENT_BACKGROUND; - checkBackground (); - if (oldState !is (state & PARENT_BACKGROUND)) { - setBackground (); - } + int oldState = state & PARENT_BACKGROUND; + checkBackground (); + if (oldState !is (state & PARENT_BACKGROUND)) { + setBackground (); + } } void updateLayout (bool all) { - /* Do nothing */ + /* Do nothing */ } override int /*long*/ windowProc (GtkWidget* handle, int /*long*/ arg0, int /*long*/ user_data) { - switch (cast(int)/*64*/user_data) { - case EXPOSE_EVENT_INVERSE: { - if ((OS.GTK_VERSION < OS.buildVERSION (2, 8, 0)) && ((state & OBSCURED) is 0)) { - Control control = findBackgroundControl (); - if (control !is null && control.backgroundImage !is null) { - GdkEventExpose* gdkEvent = cast(GdkEventExpose*)arg0; - auto paintWindow = paintWindow(); - auto window = gdkEvent.window; - if (window !is paintWindow) break; - auto gdkGC = OS.gdk_gc_new (cast(GdkDrawable*)window); - OS.gdk_gc_set_clip_region (gdkGC, gdkEvent.region); - int dest_x, dest_y; - OS.gtk_widget_translate_coordinates (paintHandle (), control.paintHandle (), 0, 0, &dest_x, &dest_y); - OS.gdk_gc_set_fill (gdkGC, OS.GDK_TILED); - OS.gdk_gc_set_ts_origin (gdkGC, -dest_x, -dest_y); - OS.gdk_gc_set_tile (gdkGC, cast(GdkPixmap*)control.backgroundImage.pixmap); - OS.gdk_draw_rectangle (cast(GdkDrawable*)window, gdkGC, 1, gdkEvent.area.x, gdkEvent.area.y, gdkEvent.area.width, gdkEvent.area.height); - OS.g_object_unref (gdkGC); - } - } - break; + switch (cast(int)/*64*/user_data) { + case EXPOSE_EVENT_INVERSE: { + if ((OS.GTK_VERSION < OS.buildVERSION (2, 8, 0)) && ((state & OBSCURED) is 0)) { + Control control = findBackgroundControl (); + if (control !is null && control.backgroundImage !is null) { + GdkEventExpose* gdkEvent = cast(GdkEventExpose*)arg0; + auto paintWindow = paintWindow(); + auto window = gdkEvent.window; + if (window !is paintWindow) break; + auto gdkGC = OS.gdk_gc_new (cast(GdkDrawable*)window); + OS.gdk_gc_set_clip_region (gdkGC, gdkEvent.region); + int dest_x, dest_y; + OS.gtk_widget_translate_coordinates (paintHandle (), control.paintHandle (), 0, 0, &dest_x, &dest_y); + OS.gdk_gc_set_fill (gdkGC, OS.GDK_TILED); + OS.gdk_gc_set_ts_origin (gdkGC, -dest_x, -dest_y); + OS.gdk_gc_set_tile (gdkGC, cast(GdkPixmap*)control.backgroundImage.pixmap); + OS.gdk_draw_rectangle (cast(GdkDrawable*)window, gdkGC, 1, gdkEvent.area.x, gdkEvent.area.y, gdkEvent.area.width, gdkEvent.area.height); + OS.g_object_unref (gdkGC); + } + } + break; default: - } - } - return super.windowProc (handle, arg0, user_data); + } + } + return super.windowProc (handle, arg0, user_data); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/widgets/Decorations.d --- a/dwt/widgets/Decorations.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/widgets/Decorations.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -103,19 +103,19 @@ * @see SWT */ public class Decorations : Canvas { - char[] text; - Image image; - Image [] images; - bool minimized, maximized; - Menu menuBar; - Menu [] menus; - Control savedFocus; - Button defaultButton, saveDefault; - GtkAccelGroup* accelGroup; + char[] text; + Image image; + Image [] images; + bool minimized, maximized; + Menu menuBar; + Menu [] menus; + Control savedFocus; + Button defaultButton, saveDefault; + GtkAccelGroup* accelGroup; GtkWidget* vboxHandle; this () { - /* Do nothing */ + /* Do nothing */ } /** @@ -157,134 +157,134 @@ * @see Widget#getStyle */ public this (Composite parent, int style) { - super (parent, checkStyle (style)); + super (parent, checkStyle (style)); } static int checkStyle (int style) { - if ((style & SWT.NO_TRIM) !is 0) { - style &= ~(SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.BORDER); - } - if ((style & (SWT.MENU | SWT.MIN | SWT.MAX | SWT.CLOSE)) !is 0) { - style |= SWT.TITLE; - } - return style; + if ((style & SWT.NO_TRIM) !is 0) { + style &= ~(SWT.CLOSE | SWT.TITLE | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.BORDER); + } + if ((style & (SWT.MENU | SWT.MIN | SWT.MAX | SWT.CLOSE)) !is 0) { + style |= SWT.TITLE; + } + return style; } override protected void checkSubclass () { - if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS); + if (!isValidSubclass ()) error (SWT.ERROR_INVALID_SUBCLASS); } void _setImages (Image [] images) { - if (images !is null && images.length > 1) { - Image [] bestImages = new Image [images.length]; - System.arraycopy (images, 0, bestImages, 0, images.length); - sort (bestImages); - images = bestImages; - } - GList* pixbufs; - if (images !is null) { - for (int i = 0; i < images.length; i++) { - Image image = images [i]; - auto pixbuf = Display.createPixbuf (image); - pixbufs = OS.g_list_append (pixbufs, pixbuf); - } - } - OS.gtk_window_set_icon_list (cast(GtkWindow*)topHandle (), pixbufs); - GList* data; - auto temp = pixbufs; - while (temp !is null) { - data = temp; - OS.g_object_unref (data); - temp = cast(GList*)OS.g_list_next (temp); - } - if (pixbufs !is null) OS.g_list_free (pixbufs); + if (images !is null && images.length > 1) { + Image [] bestImages = new Image [images.length]; + System.arraycopy (images, 0, bestImages, 0, images.length); + sort (bestImages); + images = bestImages; + } + GList* pixbufs; + if (images !is null) { + for (int i = 0; i < images.length; i++) { + Image image = images [i]; + auto pixbuf = Display.createPixbuf (image); + pixbufs = OS.g_list_append (pixbufs, pixbuf); + } + } + OS.gtk_window_set_icon_list (cast(GtkWindow*)topHandle (), pixbufs); + GList* data; + auto temp = pixbufs; + while (temp !is null) { + data = temp; + OS.g_object_unref (data); + temp = cast(GList*)OS.g_list_next (temp); + } + if (pixbufs !is null) OS.g_list_free (pixbufs); } void addMenu (Menu menu) { - if (menus is null) menus = new Menu [4]; - for (int i=0; i data2.width || data1.height > data2.height ? -1 : 1; + if (data1.width is data2.width && data1.height is data2.height) { + int transparent1 = data1.getTransparencyType (); + int transparent2 = data2.getTransparencyType (); + if (transparent1 is SWT.TRANSPARENCY_ALPHA) return -1; + if (transparent2 is SWT.TRANSPARENCY_ALPHA) return 1; + if (transparent1 is SWT.TRANSPARENCY_MASK) return -1; + if (transparent2 is SWT.TRANSPARENCY_MASK) return 1; + if (transparent1 is SWT.TRANSPARENCY_PIXEL) return -1; + if (transparent2 is SWT.TRANSPARENCY_PIXEL) return 1; + return 0; + } + return data1.width > data2.width || data1.height > data2.height ? -1 : 1; } override Control computeTabGroup () { - return this; + return this; } override Control computeTabRoot () { - return this; + return this; } void createAccelGroup () { - if (accelGroup !is null) return; - accelGroup = OS.gtk_accel_group_new (); - if (accelGroup is null) SWT.error (SWT.ERROR_NO_HANDLES); - //FIXME - what should we do for Decorations - auto shellHandle = topHandle (); - OS.gtk_window_add_accel_group (cast(GtkWindow*)shellHandle, accelGroup); + if (accelGroup !is null) return; + accelGroup = OS.gtk_accel_group_new (); + if (accelGroup is null) SWT.error (SWT.ERROR_NO_HANDLES); + //FIXME - what should we do for Decorations + auto shellHandle = topHandle (); + OS.gtk_window_add_accel_group (cast(GtkWindow*)shellHandle, accelGroup); } override void createWidget (int index) { - super.createWidget (index); - text = ""; + super.createWidget (index); + text = ""; } void destroyAccelGroup () { - if (accelGroup is null) return; - auto shellHandle = topHandle (); - OS.gtk_window_remove_accel_group (cast(GtkWindow*)shellHandle, accelGroup); - //TEMPORARY CODE -// OS.g_object_unref (accelGroup); - accelGroup = null; + if (accelGroup is null) return; + auto shellHandle = topHandle (); + OS.gtk_window_remove_accel_group (cast(GtkWindow*)shellHandle, accelGroup); + //TEMPORARY CODE +// OS.g_object_unref (accelGroup); + accelGroup = null; } void fixAccelGroup () { - if (menuBar is null) return; - destroyAccelGroup (); - createAccelGroup (); - menuBar.addAccelerators (accelGroup); + if (menuBar is null) return; + destroyAccelGroup (); + createAccelGroup (); + menuBar.addAccelerators (accelGroup); } void fixDecorations (Decorations newDecorations, Control control, Menu [] menus) { - if (this is newDecorations) return; - if (control is savedFocus) savedFocus = null; - if (control is defaultButton) defaultButton = null; - if (control is saveDefault) saveDefault = null; - if (menus is null) return; - Menu menu = control.menu; - if (menu !is null) { - int index = 0; - while (index */ public Image getImage () { - checkWidget (); - return image; + checkWidget (); + return image; } /** @@ -359,11 +359,11 @@ * @since 3.0 */ public Image [] getImages () { - checkWidget (); - if (images is null) return new Image [0]; - Image [] result = new Image [images.length]; - System.arraycopy (images, 0, result, 0, images.length); - return result; + checkWidget (); + if (images is null) return new Image [0]; + Image [] result = new Image [images.length]; + System.arraycopy (images, 0, result, 0, images.length); + return result; } /** @@ -381,8 +381,8 @@ * @see #setMaximized */ public bool getMaximized () { - checkWidget(); - return maximized; + checkWidget(); + return maximized; } /** @@ -397,8 +397,8 @@ * */ public Menu getMenuBar () { - checkWidget(); - return menuBar; + checkWidget(); + return menuBar; } /** @@ -416,12 +416,12 @@ * @see #setMinimized */ public bool getMinimized () { - checkWidget(); - return minimized; + checkWidget(); + return minimized; } override char[] getNameText () { - return getText (); + return getText (); } /** @@ -438,82 +438,82 @@ * */ public char[] getText () { - checkWidget(); - return text; + checkWidget(); + return text; } override public bool isReparentable () { - checkWidget (); - return false; + checkWidget (); + return false; } override bool isTabGroup () { - return true; + return true; } override bool isTabItem () { - return false; + return false; } override Decorations menuShell () { - return this; + return this; } void removeMenu (Menu menu) { - if (menus is null) return; - for (int i=0; i */ public void setDefaultButton (Button button) { - checkWidget(); - GtkWidget* buttonHandle; - if (button !is null) { - if (button.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); - if (button.menuShell () !is this) error (SWT.ERROR_INVALID_PARENT); - buttonHandle = button.handle; - } - saveDefault = defaultButton = button; - OS.gtk_window_set_default (cast(GtkWindow*)topHandle (), buttonHandle); + checkWidget(); + GtkWidget* buttonHandle; + if (button !is null) { + if (button.isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); + if (button.menuShell () !is this) error (SWT.ERROR_INVALID_PARENT); + buttonHandle = button.handle; + } + saveDefault = defaultButton = button; + OS.gtk_window_set_default (cast(GtkWindow*)topHandle (), buttonHandle); } /** @@ -571,9 +571,9 @@ * */ public void setImage (Image image) { - checkWidget (); - this.image = image; - _setImages (image !is null ? [image] : null); + checkWidget (); + this.image = image; + _setImages (image !is null ? [image] : null); } /** @@ -601,13 +601,13 @@ * @since 3.0 */ public void setImages (Image [] images) { - checkWidget (); - if (images is null) error (SWT.ERROR_INVALID_ARGUMENT); - for (int i = 0; i < images.length; i++) { - if (images [i] is null || images [i].isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); - } - this.images = images; - _setImages (images); + checkWidget (); + if (images is null) error (SWT.ERROR_INVALID_ARGUMENT); + for (int i = 0; i < images.length; i++) { + if (images [i] is null || images [i].isDisposed ()) error (SWT.ERROR_INVALID_ARGUMENT); + } + this.images = images; + _setImages (images); } /** @@ -634,8 +634,8 @@ * @see #setMinimized */ public void setMaximized (bool maximized) { - checkWidget(); - this.maximized = maximized; + checkWidget(); + this.maximized = maximized; } /** @@ -654,13 +654,13 @@ * */ public void setMenuBar (Menu menu) { - checkWidget(); - if (menuBar is menu) return; - if (menu !is null) { - if ((menu.style & SWT.BAR) is 0) error (SWT.ERROR_MENU_NOT_BAR); - if (menu.parent !is this) error (SWT.ERROR_INVALID_PARENT); - } - menuBar = menu; + checkWidget(); + if (menuBar is menu) return; + if (menu !is null) { + if ((menu.style & SWT.BAR) is 0) error (SWT.ERROR_MENU_NOT_BAR); + if (menu.parent !is this) error (SWT.ERROR_INVALID_PARENT); + } + menuBar = menu; } /** @@ -687,13 +687,13 @@ * @see #setMaximized */ public void setMinimized (bool minimized) { - checkWidget(); - this.minimized = minimized; + checkWidget(); + this.minimized = minimized; } void setSavedFocus (Control control) { - if (this is control) return; - savedFocus = control; + if (this is control) return; + savedFocus = control; } /** @@ -712,51 +712,51 @@ * */ public void setText (char[] string) { - checkWidget(); - if (string is null) error (SWT.ERROR_NULL_ARGUMENT); - text = string; + checkWidget(); + if (string is null) error (SWT.ERROR_NULL_ARGUMENT); + text = string; } void sort (Image [] images) { - /* Shell Sort from K&R, pg 108 */ - int length = images.length; - if (length <= 1) return; - ImageData [] datas = new ImageData [length]; - for (int i = 0; i < length; i++) { - datas [i] = images [i].getImageData (); - } - for (int gap=length/2; gap>0; gap/=2) { - for (int i=gap; i=0; j-=gap) { - if (compare (datas [j], datas [j + gap]) >= 0) { - Image swap = images [j]; - images [j] = images [j + gap]; - images [j + gap] = swap; - ImageData swapData = datas [j]; - datas [j] = datas [j + gap]; - datas [j + gap] = swapData; - } - } - } - } + /* Shell Sort from K&R, pg 108 */ + int length = images.length; + if (length <= 1) return; + ImageData [] datas = new ImageData [length]; + for (int i = 0; i < length; i++) { + datas [i] = images [i].getImageData (); + } + for (int gap=length/2; gap>0; gap/=2) { + for (int i=gap; i=0; j-=gap) { + if (compare (datas [j], datas [j + gap]) >= 0) { + Image swap = images [j]; + images [j] = images [j + gap]; + images [j + gap] = swap; + ImageData swapData = datas [j]; + datas [j] = datas [j + gap]; + datas [j + gap] = swapData; + } + } + } + } } override bool traverseItem (bool next) { - return false; + return false; } override bool traverseReturn () { - Button button = defaultButton !is null ? defaultButton: saveDefault; - if (button is null || button.isDisposed ()) return false; - /* - * Bug in GTK. When a default button that is disabled is - * activated using the Enter key, GTK GP's. The fix is to - * detect this case and stop GTK from processing the Enter - * key. - */ - if (!button.isVisible () || !button.isEnabled ()) return true; - auto shellHandle = _getShell ().topHandle (); - return cast(bool)OS.gtk_window_activate_default (cast(GtkWindow*)shellHandle); + Button button = defaultButton !is null ? defaultButton: saveDefault; + if (button is null || button.isDisposed ()) return false; + /* + * Bug in GTK. When a default button that is disabled is + * activated using the Enter key, GTK GP's. The fix is to + * detect this case and stop GTK from processing the Enter + * key. + */ + if (!button.isVisible () || !button.isEnabled ()) return true; + auto shellHandle = _getShell ().topHandle (); + return cast(bool)OS.gtk_window_activate_default (cast(GtkWindow*)shellHandle); } } diff -r a5c274fa5af9 -r 8cec8f536af3 dwt/widgets/Display.d --- a/dwt/widgets/Display.d Sat Jan 12 07:02:08 2008 +0100 +++ b/dwt/widgets/Display.d Sat Jan 12 08:44:23 2008 +0100 @@ -1,4 +1,4 @@ -/******************************************************************************* +/******************************************************************************* * Copyright (c) 2000, 2007 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 @@ -125,272 +125,272 @@ */ public class Display : Device { - /* Events Dispatching and Callback */ - int gdkEventCount; - GdkEvent* [] gdkEvents; - Widget [] gdkEventWidgets; - int [] dispatchEvents; - Event [] eventQueue; - GPollFD[] fds; - int allocated_nfds; - bool wake_state; - int max_priority, timeout; - void*/*Callback*/ eventCallback, filterCallback; + /* Events Dispatching and Callback */ + int gdkEventCount; + GdkEvent* [] gdkEvents; + Widget [] gdkEventWidgets; + int [] dispatchEvents; + Event [] eventQueue; + GPollFD[] fds; + int allocated_nfds; + bool wake_state; + int max_priority, timeout; + void*/*Callback*/ eventCallback, filterCallback; CallbackData*[] windowProcCallbackDatas; // to prevent GC from collect CallbackData filterProcCallbackData; - EventTable eventTable, filterTable; - static char[] APP_NAME = "SWT"; - static const char[] DISPATCH_EVENT_KEY = "dwt.internal.gtk.dispatchEvent"; - static const char[] ADD_WIDGET_KEY = "dwt.internal.addWidget"; - GClosure*[] closures; - int [] signalIds; - - /* Widget Table */ - int [] indexTable; - int freeSlot; - GtkWidget* lastHandle; - Widget lastWidget; - Widget [] widgetTable; - const static int GROW_SIZE = 1024; - static int SWT_OBJECT_INDEX; - static int SWT_OBJECT_INDEX1; - static int SWT_OBJECT_INDEX2; - - /* Focus */ - int focusEvent; - Control focusControl; - Shell activeShell; - bool activePending; - bool ignoreActivate, ignoreFocus; - - /* Input method resources */ - Control imControl; - GtkWindow* preeditWindow; + EventTable eventTable, filterTable; + static char[] APP_NAME = "SWT"; + static const char[] DISPATCH_EVENT_KEY = "dwt.internal.gtk.dispatchEvent"; + static const char[] ADD_WIDGET_KEY = "dwt.internal.addWidget"; + GClosure*[] closures; + int [] signalIds; + + /* Widget Table */ + int [] indexTable; + int freeSlot; + GtkWidget* lastHandle; + Widget lastWidget; + Widget [] widgetTable; + const static int GROW_SIZE = 1024; + static int SWT_OBJECT_INDEX; + static int SWT_OBJECT_INDEX1; + static int SWT_OBJECT_INDEX2; + + /* Focus */ + int focusEvent; + Control focusControl; + Shell activeShell; + bool activePending; + bool ignoreActivate, ignoreFocus; + + /* Input method resources */ + Control imControl; + GtkWindow* preeditWindow; GtkLabel* preeditLabel; - /* Sync/Async Widget Communication */ - Synchronizer synchronizer; - Thread thread; - - /* Display Shutdown */ - Runnable [] disposeList; - - /* System Tray */ - Tray tray; - - /* Timers */ - int [] timerIds; - Runnable [] timerList; + /* Sync/Async Widget Communication */ + Synchronizer synchronizer; + Thread thread; + + /* Display Shutdown */ + Runnable [] disposeList; + + /* System Tray */ + Tray tray; + + /* Timers */ + int [] timerIds; + Runnable [] timerList; CallbackData timerProcCallbackData; - /* Caret */ - Caret currentCaret; - int caretId; + /* Caret */ + Caret currentCaret; + int caretId; CallbackData caretProcCallbackData; - /* Mnemonics */ - Control mnemonicControl; - - /* Mouse hover */ - int mouseHoverId; + /* Mnemonics */ + Control mnemonicControl; + + /* Mouse hover */ + int mouseHoverId; GtkWidget* mouseHoverHandle; CallbackData mouseHoverProcCallbackData; /* Menu position callback */ - /* Tooltip size allocate callback */ - - /* Shell map callback */ + /* Tooltip size allocate callback */ + + /* Shell map callback */ CallbackData shellMapProcCallbackData; GClosure* shellMapProcClosure; - /* Idle proc callback */ + /* Idle proc callback */ CallbackData idleProcCallbackData; - int idleHandle; - static const char[] ADD_IDLE_PROC_KEY = "dwt.internal.gtk2.addIdleProc"; - static const char[] REMOVE_IDLE_PROC_KEY = "dwt.internal.gtk2.removeIdleProc"; + int idleHandle; + static const char[] ADD_IDLE_PROC_KEY = "dwt.internal.gtk2.addIdleProc"; + static const char[] REMOVE_IDLE_PROC_KEY = "dwt.internal.gtk2.removeIdleProc"; Object idleLock; - bool idleNeeded; - - /* GtkTreeView callbacks */ - int[] treeSelection; - int treeSelectionLength; - - /* Set direction callback */ + bool idleNeeded; + + /* GtkTreeView callbacks */ + int[] treeSelection; + int treeSelectionLength; + + /* Set direction callback */ CallbackData setDirectionCallbackData; - /* Get all children callback */ + /* Get all children callback */ CallbackData allChildrenProcCallbackData; GList* allChildren; - /* Settings callbacks */ - GtkWidget* shellHandle; - bool settingsChanged, runSettingsFld; + /* Settings callbacks */ + GtkWidget* shellHandle; + bool settingsChanged, runSettingsFld; CallbackData styleSetProcCallbackData; - /* Entry focus behaviour */ - bool entrySelectOnFocus; - - /* Enter/Exit events */ - Control currentControl; - - /* Flush exposes */ - int /*long*/ checkIfEventProc; - void*/*Callback*/ checkIfEventCallback; - GdkWindow* flushWindow; - bool flushAll; - GdkRectangle* flushRect; - XExposeEvent* exposeEvent; - XVisibilityEvent* visibilityEvent; - //int /*long*/ [] flushData = new int /*long*/ [1]; - - /* System Resources */ - Font systemFont; - Image errorImage, infoImage, questionImage, warningImage; - Cursor [] cursors; - Resource [] resources; - static const int RESOURCE_SIZE = 1 + 4 + SWT.CURSOR_HAND + 1; - - /* Colors */ - GdkColor* COLOR_WIDGET_DARK_SHADOW, COLOR_WIDGET_NORMAL_SHADOW, COLOR_WIDGET_LIGHT_SHADOW; - GdkColor* COLOR_WIDGET_HIGHLIGHT_SHADOW, COLOR_WIDGET_BACKGROUND, COLOR_WIDGET_FOREGROUND, COLOR_WIDGET_BORDER; - GdkColor* COLOR_LIST_FOREGROUND, COLOR_LIST_BACKGROUND, COLOR_LIST_SELECTION, COLOR_LIST_SELECTION_TEXT; - GdkColor* COLOR_INFO_BACKGROUND, COLOR_INFO_FOREGROUND; - GdkColor* COLOR_TITLE_FOREGROUND, COLOR_TITLE_BACKGROUND, COLOR_TITLE_BACKGROUND_GRADIENT; - GdkColor* COLOR_TITLE_INACTIVE_FOREGROUND, COLOR_TITLE_INACTIVE_BACKGROUND, COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT; - - /* Popup Menus */ - Menu [] popups; - - /* Click count*/ - int clickCount = 1; - - /* Timestamp of the Last Received Events */ - int lastEventTime, lastUserEventTime; - - /* Fixed Subclass */ - static int /*long*/ fixed_type; - static int /*long*/ fixed_info_ptr; - - /* Renderer Subclass */ - static int /*long*/ text_renderer_type, pixbuf_renderer_type, toggle_renderer_type; - static int /*long*/ text_renderer_info_ptr, pixbuf_renderer_info_ptr, toggle_renderer_info_ptr; - - /* Key Mappings */ - static const int [] [] KeyTable = [ - - /* Keyboard and Mouse Masks */ - [OS.GDK_Alt_L, SWT.ALT], - [OS.GDK_Alt_R, SWT.ALT], - [OS.GDK_Meta_L, SWT.ALT], - [OS.GDK_Meta_R, SWT.ALT], - [OS.GDK_Shift_L, SWT.SHIFT], - [OS.GDK_Shift_R, SWT.SHIFT], - [OS.GDK_Control_L, SWT.CONTROL], - [OS.GDK_Control_R, SWT.CONTROL], -// [OS.GDK_????, SWT.COMMAND], -// [OS.GDK_????, SWT.COMMAND], - - /* Non-Numeric Keypad Keys */ - [OS.GDK_Up, SWT.ARROW_UP], - [OS.GDK_KP_Up, SWT.ARROW_UP], - [OS.GDK_Down, SWT.ARROW_DOWN], - [OS.GDK_KP_Down, SWT.ARROW_DOWN], - [OS.GDK_Left, SWT.ARROW_LEFT], - [OS.GDK_KP_Left, SWT.ARROW_LEFT], - [OS.GDK_Right, SWT.ARROW_RIGHT], - [OS.GDK_KP_Right, SWT.ARROW_RIGHT], - [OS.GDK_Page_Up, SWT.PAGE_UP], - [OS.GDK_KP_Page_Up, SWT.PAGE_UP], - [OS.GDK_Page_Down, SWT.PAGE_DOWN], - [OS.GDK_KP_Page_Down, SWT.PAGE_DOWN], - [OS.GDK_Home, SWT.HOME], - [OS.GDK_KP_Home, SWT.HOME], - [OS.GDK_End, SWT.END], - [OS.GDK_KP_End, SWT.END], - [OS.GDK_Insert, SWT.INSERT], - [OS.GDK_KP_Insert, SWT.INSERT], - - /* Virtual and Ascii Keys */ - [OS.GDK_BackSpace, SWT.BS], - [OS.GDK_Return, SWT.CR], - [OS.GDK_Delete, SWT.DEL], - [OS.GDK_KP_Delete, SWT.DEL], - [OS.GDK_Escape, SWT.ESC], - [OS.GDK_Linefeed, SWT.LF], - [OS.GDK_Tab, SWT.TAB], - [OS.GDK_ISO_Left_Tab, SWT.TAB], - - /* Functions Keys */ - [OS.GDK_F1, SWT.F1], - [OS.GDK_F2, SWT.F2], - [OS.GDK_F3, SWT.F3], - [OS.GDK_F4, SWT.F4], - [OS.GDK_F5, SWT.F5], - [OS.GDK_F6, SWT.F6], - [OS.GDK_F7, SWT.F7], - [OS.GDK_F8, SWT.F8], - [OS.GDK_F9, SWT.F9], - [OS.GDK_F10, SWT.F10], - [OS.GDK_F11, SWT.F11], - [OS.GDK_F12, SWT.F12], - [OS.GDK_F13, SWT.F13], - [OS.GDK_F14, SWT.F14], - [OS.GDK_F15, SWT.F15], - - /* Numeric Keypad Keys */ - [OS.GDK_KP_Multiply, SWT.KEYPAD_MULTIPLY], - [OS.GDK_KP_Add, SWT.KEYPAD_ADD], - [OS.GDK_KP_Enter, SWT.KEYPAD_CR], - [OS.GDK_KP_Subtract, SWT.KEYPAD_SUBTRACT], - [OS.GDK_KP_Decimal, SWT.KEYPAD_DECIMAL], - [OS.GDK_KP_Divide, SWT.KEYPAD_DIVIDE], - [OS.GDK_KP_0, SWT.KEYPAD_0], - [OS.GDK_KP_1, SWT.KEYPAD_1], - [OS.GDK_KP_2, SWT.KEYPAD_2], - [OS.GDK_KP_3, SWT.KEYPAD_3], - [OS.GDK_KP_4, SWT.KEYPAD_4], - [OS.GDK_KP_5, SWT.KEYPAD_5], - [OS.GDK_KP_6, SWT.KEYPAD_6], - [OS.GDK_KP_7, SWT.KEYPAD_7], - [OS.GDK_KP_8, SWT.KEYPAD_8], - [OS.GDK_KP_9, SWT.KEYPAD_9], - [OS.GDK_KP_Equal, SWT.KEYPAD_EQUAL], - - /* Other keys */ - [OS.GDK_Caps_Lock, SWT.CAPS_LOCK], - [OS.GDK_Num_Lock, SWT.NUM_LOCK], - [OS.GDK_Scroll_Lock, SWT.SCROLL_LOCK], - [OS.GDK_Pause, SWT.PAUSE], - [OS.GDK_Break, SWT.BREAK], - [OS.GDK_Print, SWT.PRINT_SCREEN], - [OS.GDK_Help, SWT.HELP], - - ]; - - /* Multiple Displays. */ - static Display Default; - static Display [] Displays; - - /* Package name */ - static const char[] PACKAGE_PREFIX = "dwt.widgets."; - /* This code is intentionally commented. - * ".class" can not be used on CLDC. - */ -// static { -// char[] name = Display.class.getName (); -// int index = name.lastIndexOf ('.'); -// PACKAGE_NAME = name.substring (0, index + 1); -// } - - /* - * In order to support CLDC, .class cannot be used because - * it does not compile on some Java compilers when they are - * targeted for CLDC. Use Class.forName() instead. - */ + /* Entry focus behaviour */ + bool entrySelectOnFocus; + + /* Enter/Exit events */ + Control currentControl; + + /* Flush exposes */ + int /*long*/ checkIfEventProc; + void*/*Callback*/ checkIfEventCallback; + GdkWindow* flushWindow; + bool flushAll; + GdkRectangle* flushRect; + XExposeEvent* exposeEvent; + XVisibilityEvent* visibilityEvent; + //int /*long*/ [] flushData = new int /*long*/ [1]; + + /* System Resources */ + Font systemFont; + Image errorImage, infoImage, questionImage, warningImage; + Cursor [] cursors; + Resource [] resources; + static const int RESOURCE_SIZE = 1 + 4 + SWT.CURSOR_HAND + 1; + + /* Colors */ + GdkColor* COLOR_WIDGET_DARK_SHADOW, COLOR_WIDGET_NORMAL_SHADOW, COLOR_WIDGET_LIGHT_SHADOW; + GdkColor* COLOR_WIDGET_HIGHLIGHT_SHADOW, COLOR_WIDGET_BACKGROUND, COLOR_WIDGET_FOREGROUND, COLOR_WIDGET_BORDER; + GdkColor* COLOR_LIST_FOREGROUND, COLOR_LIST_BACKGROUND, COLOR_LIST_SELECTION, COLOR_LIST_SELECTION_TEXT; + GdkColor* COLOR_INFO_BACKGROUND, COLOR_INFO_FOREGROUND; + GdkColor* COLOR_TITLE_FOREGROUND, COLOR_TITLE_BACKGROUND, COLOR_TITLE_BACKGROUND_GRADIENT; + GdkColor* COLOR_TITLE_INACTIVE_FOREGROUND, COLOR_TITLE_INACTIVE_BACKGROUND, COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT; + + /* Popup Menus */ + Menu [] popups; + + /* Click count*/ + int clickCount = 1; + + /* Timestamp of the Last Received Events */ + int lastEventTime, lastUserEventTime; + + /* Fixed Subclass */ + static int /*long*/ fixed_type; + static int /*long*/ fixed_info_ptr; + + /* Renderer Subclass */ + static int /*long*/ text_renderer_type, pixbuf_renderer_type, toggle_renderer_type; + static int /*long*/ text_renderer_info_ptr, pixbuf_renderer_info_ptr, toggle_renderer_info_ptr; + + /* Key Mappings */ + static const int [] [] KeyTable = [ + + /* Keyboard and Mouse Masks */ + [OS.GDK_Alt_L, SWT.ALT], + [OS.GDK_Alt_R, SWT.ALT], + [OS.GDK_Meta_L, SWT.ALT], + [OS.GDK_Meta_R, SWT.ALT], + [OS.GDK_Shift_L, SWT.SHIFT], + [OS.GDK_Shift_R, SWT.SHIFT], + [OS.GDK_Control_L, SWT.CONTROL], + [OS.GDK_Control_R, SWT.CONTROL], +// [OS.GDK_????, SWT.COMMAND], +// [OS.GDK_????, SWT.COMMAND], + + /* Non-Numeric Keypad Keys */ + [OS.GDK_Up, SWT.ARROW_UP], + [OS.GDK_KP_Up, SWT.ARROW_UP], + [OS.GDK_Down, SWT.ARROW_DOWN], + [OS.GDK_KP_Down, SWT.ARROW_DOWN], + [OS.GDK_Left, SWT.ARROW_LEFT], + [OS.GDK_KP_Left, SWT.ARROW_LEFT], + [OS.GDK_Right, SWT.ARROW_RIGHT], + [OS.GDK_KP_Right, SWT.ARROW_RIGHT], + [OS.GDK_Page_Up, SWT.PAGE_UP], + [OS.GDK_KP_Page_Up, SWT.PAGE_UP], + [OS.GDK_Page_Down, SWT.PAGE_DOWN], + [OS.GDK_KP_Page_Down, SWT.PAGE_DOWN], + [OS.GDK_Home, SWT.HOME], + [OS.GDK_KP_Home, SWT.HOME], + [OS.GDK_End, SWT.END], + [OS.GDK_KP_End, SWT.END], + [OS.GDK_Insert, SWT.INSERT], + [OS.GDK_KP_Insert, SWT.INSERT], + + /* Virtual and Ascii Keys */ + [OS.GDK_BackSpace, SWT.BS], + [OS.GDK_Return, SWT.CR], + [OS.GDK_Delete, SWT.DEL], + [OS.GDK_KP_Delete, SWT.DEL], + [OS.GDK_Escape, SWT.ESC], + [OS.GDK_Linefeed, SWT.LF], + [OS.GDK_Tab, SWT.TAB], + [OS.GDK_ISO_Left_Tab, SWT.TAB], + + /* Functions Keys */ + [OS.GDK_F1, SWT.F1], + [OS.GDK_F2, SWT.F2], + [OS.GDK_F3, SWT.F3], + [OS.GDK_F4, SWT.F4], + [OS.GDK_F5, SWT.F5], + [OS.GDK_F6, SWT.F6], + [OS.GDK_F7, SWT.F7], + [OS.GDK_F8, SWT.F8], + [OS.GDK_F9, SWT.F9], + [OS.GDK_F10, SWT.F10], + [OS.GDK_F11, SWT.F11], + [OS.GDK_F12, SWT.F12], + [OS.GDK_F13, SWT.F13], + [OS.GDK_F14, SWT.F14], + [OS.GDK_F15, SWT.F15], + + /* Numeric Keypad Keys */ + [OS.GDK_KP_Multiply, SWT.KEYPAD_MULTIPLY], + [OS.GDK_KP_Add, SWT.KEYPAD_ADD], + [OS.GDK_KP_Enter, SWT.KEYPAD_CR], + [OS.GDK_KP_Subtract, SWT.KEYPAD_SUBTRACT], + [OS.GDK_KP_Decimal, SWT.KEYPAD_DECIMAL], + [OS.GDK_KP_Divide, SWT.KEYPAD_DIVIDE], + [OS.GDK_KP_0, SWT.KEYPAD_0], + [OS.GDK_KP_1, SWT.KEYPAD_1], + [OS.GDK_KP_2, SWT.KEYPAD_2], + [OS.GDK_KP_3, SWT.KEYPAD_3], + [OS.GDK_KP_4, SWT.KEYPAD_4], + [OS.GDK_KP_5, SWT.KEYPAD_5], + [OS.GDK_KP_6, SWT.KEYPAD_6], + [OS.GDK_KP_7, SWT.KEYPAD_7], + [OS.GDK_KP_8, SWT.KEYPAD_8], + [OS.GDK_KP_9, SWT.KEYPAD_9], + [OS.GDK_KP_Equal, SWT.KEYPAD_EQUAL], + + /* Other keys */ + [OS.GDK_Caps_Lock, SWT.CAPS_LOCK], + [OS.GDK_Num_Lock, SWT.NUM_LOCK], + [OS.GDK_Scroll_Lock, SWT.SCROLL_LOCK], + [OS.GDK_Pause, SWT.PAUSE], + [OS.GDK_Break, SWT.BREAK], + [OS.GDK_Print, SWT.PRINT_SCREEN], + [OS.GDK_Help, SWT.HELP], + + ]; + + /* Multiple Displays. */ + static Display Default; + static Display [] Displays; + + /* Package name */ + static const char[] PACKAGE_PREFIX = "dwt.widgets."; + /* This code is intentionally commented. + * ".class" can not be used on CLDC. + */ +// static { +// char[] name = Display.class.getName (); +// int index = name.lastIndexOf ('.'); +// PACKAGE_NAME = name.substring (0, index + 1); +// } + + /* + * In order to support CLDC, .class cannot be used because + * it does not compile on some Java compilers when they are + * targeted for CLDC. Use Class.forName() instead. + */ synchronized static void static_this() { Displays = new Display [4]; initDeviceFinder(); @@ -399,49 +399,49 @@ SWT_OBJECT_INDEX2 = OS.g_quark_from_string ("SWT_OBJECT_INDEX2"); } - /* GTK Version */ - static const int MAJOR = 2; - static const int MINOR = 0; - static const int MICRO = 6; - - /* Display Data */ - Object data; - char[] [] keys; - Object [] values; - - /* Initial Guesses for Shell Trimmings. */ - int borderTrimWidth = 4, borderTrimHeight = 4; - int resizeTrimWidth = 6, resizeTrimHeight = 6; - int titleBorderTrimWidth = 5, titleBorderTrimHeight = 28; - int titleResizeTrimWidth = 6, titleResizeTrimHeight = 29; - int titleTrimWidth = 0, titleTrimHeight = 23; - bool ignoreTrim; - - /* Window Manager */ - char[] windowManager; - - /* - * TEMPORARY CODE. Install the runnable that - * gets the current display. This code will - * be removed in the future. - */ - private static void initDeviceFinder(){ - DeviceFinder = new class() Runnable { - public void run () { - Device device = getCurrent (); - if (device is null) { - device = getDefault (); - } - setDevice (device); - } - }; - } + /* GTK Version */ + static const int MAJOR = 2; + static const int MINOR = 0; + static const int MICRO = 6; + + /* Display Data */ + Object data; + char[] [] keys; + Object [] values; + + /* Initial Guesses for Shell Trimmings. */ + int borderTrimWidth = 4, borderTrimHeight = 4; + int resizeTrimWidth = 6, resizeTrimHeight = 6; + int titleBorderTrimWidth = 5, titleBorderTrimHeight = 28; + int titleResizeTrimWidth = 6, titleResizeTrimHeight = 29; + int titleTrimWidth = 0, titleTrimHeight = 23; + bool ignoreTrim; + + /* Window Manager */ + char[] windowManager; + + /* + * TEMPORARY CODE. Install the runnable that + * gets the current display. This code will + * be removed in the future. + */ + private static void initDeviceFinder(){ + DeviceFinder = new class() Runnable { + public void run () { + Device device = getCurrent (); + if (device is null) { + device = getDefault (); + } + setDevice (device); + } + }; + } /* * TEMPORARY CODE. */ static void setDevice (Device device) { - CurrentDevice = device; + CurrentDevice = device; } /** @@ -464,7 +464,7 @@ * @see Shell */ public this () { - this (null); + this (null); } /** @@ -473,7 +473,7 @@ * @param data the device data */ public this (DeviceData data) { - super (data); + super (data); synchronizer = new Synchronizer (this); idleLock = new Object(); flushRect = new GdkRectangle (); @@ -519,49 +519,49 @@ * @since 3.0 */ public void addFilter (int eventType, Listener listener) { - checkDevice (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (filterTable is null) filterTable = new EventTable (); - filterTable.hook (eventType, listener); + checkDevice (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (filterTable is null) filterTable = new EventTable (); + filterTable.hook (eventType, listener); } void addGdkEvent (GdkEvent* event) { - if (gdkEvents is null) { - int length = GROW_SIZE; - gdkEvents.length = length; - gdkEventWidgets.length = length; - gdkEventCount = 0; - } - if (gdkEventCount is gdkEvents.length) { - int length = gdkEventCount + GROW_SIZE; - GdkEvent* [] newEvents = new GdkEvent* [length]; - SimpleType!(GdkEvent*).arraycopy (gdkEvents, 0, newEvents, 0, gdkEventCount); - gdkEvents = newEvents; - Widget [] newWidgets = new Widget [length]; - System.arraycopy (gdkEventWidgets, 0, newWidgets, 0, gdkEventCount); - gdkEventWidgets = newWidgets; - } - Widget widget = null; - GtkWidget* handle = OS.gtk_get_event_widget (event); - if (handle !is null) { - do { - widget = getWidget (handle); - } while (widget is null && (handle = OS.gtk_widget_get_parent (handle)) !is null); - } - gdkEvents [gdkEventCount] = event; - gdkEventWidgets [gdkEventCount] = widget; - gdkEventCount++; + if (gdkEvents is null) { + int length = GROW_SIZE; + gdkEvents.length = length; + gdkEventWidgets.length = length; + gdkEventCount = 0; + } + if (gdkEventCount is gdkEvents.length) { + int length = gdkEventCount + GROW_SIZE; + GdkEvent* [] newEvents = new GdkEvent* [length]; + SimpleType!(GdkEvent*).arraycopy (gdkEvents, 0, newEvents, 0, gdkEventCount); + gdkEvents = newEvents; + Widget [] newWidgets = new Widget [length]; + System.arraycopy (gdkEventWidgets, 0, newWidgets, 0, gdkEventCount); + gdkEventWidgets = newWidgets; + } + Widget widget = null; + GtkWidget* handle = OS.gtk_get_event_widget (event); + if (handle !is null) { + do { + widget = getWidget (handle); + } while (widget is null && (handle = OS.gtk_widget_get_parent (handle)) !is null); + } + gdkEvents [gdkEventCount] = event; + gdkEventWidgets [gdkEventCount] = widget; + gdkEventCount++; } void addIdleProc() { - synchronized (idleLock){ - this.idleNeeded = true; - if (idleHandle is 0) { + synchronized (idleLock){ + this.idleNeeded = true; + if (idleHandle is 0) { idleProcCallbackData.display = this; idleProcCallbackData.data = null; - idleHandle = OS.g_idle_add ( &idleProcFunc, &idleProcCallbackData ); - } - } + idleHandle = OS.g_idle_add ( &idleProcFunc, &idleProcCallbackData ); + } + } } /** @@ -589,10 +589,10 @@ * @since 2.0 */ public void addListener (int eventType, Listener listener) { - checkDevice (); - if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); - if (eventTable is null) eventTable = new EventTable (); - eventTable.hook (eventType, listener); + checkDevice (); + if (listener is null) error (SWT.ERROR_NULL_ARGUMENT); + if (eventTable is null) eventTable = new EventTable (); + eventTable.hook (eventType, listener); } private static extern(C) int /*long*/ allChildrenProcFunc (GtkWidget* handle, void* user_data) { @@ -600,63 +600,63 @@ return cbdata.display.allChildrenProc( cast(GtkWidget*)handle, cast(int)cbdata.data ); } int /*long*/ allChildrenProc (GtkWidget* widget, int /*long*/ recurse) { - allChildren = OS.g_list_append (allChildren, widget); - if (recurse !is 0 && OS.GTK_IS_CONTAINER (cast(GTypeInstance*)widget)) { + allChildren = OS.g_list_append (allChildren, widget); + if (recurse !is 0 && OS.GTK_IS_CONTAINER (cast(GTypeInstance*)widget)) { allChildrenProcCallbackData.display = this; allChildrenProcCallbackData.data = cast(void*)recurse; - OS.gtk_container_forall (cast(GtkContainer*)widget, cast(GtkCallback)&allChildrenProcFunc, &allChildrenProcCallbackData); - } - return 0; + OS.gtk_container_forall (cast(GtkContainer*)widget, cast(GtkCallback)&allChildrenProcFunc, &allChildrenProcCallbackData); + } + return 0; } void addMouseHoverTimeout (GtkWidget* handle) { - if (mouseHoverId !is 0) OS.gtk_timeout_remove (mouseHoverId); + if (mouseHoverId !is 0) OS.gtk_timeout_remove (mouseHoverId); mouseHoverProcCallbackData.display = this; mouseHoverProcCallbackData.data = cast(void*)handle; - mouseHoverId = OS.gtk_timeout_add (400, &mouseHoverProcFunc, &mouseHoverProcCallbackData); - mouseHoverHandle = handle; + mouseHoverId = OS.gtk_timeout_add (400, &mouseHoverProcFunc, &mouseHoverProcCallbackData); + mouseHoverHandle = handle; } void addPopup (Menu menu) { - if (popups is null) popups = new Menu [4]; - int length = popups.length; - for (int i=0; i */ public void beep () { - if (!isValidThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); - OS.gdk_beep(); - if (!OS.GDK_WINDOWING_X11 ()) { - OS.gdk_flush (); - } else { - void* xDisplay = OS.GDK_DISPLAY (); - OS.XFlush (xDisplay); - } + if (!isValidThread ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); + OS.gdk_beep(); + if (!OS.GDK_WINDOWING_X11 ()) { + OS.gdk_flush (); + } else { + void* xDisplay = OS.GDK_DISPLAY (); + OS.XFlush (xDisplay); + } } int /*long*/ cellDataProc (int /*long*/ tree_column, int /*long*/ cell, int /*long*/ tree_model, int /*long*/ iter, GtkWidget* data) { - Widget widget = getWidget (data); - if (widget is null) return 0; - return widget.cellDataProc (tree_column, cell, tree_model, iter, data); + Widget widget = getWidget (data); + if (widget is null) return 0; + return widget.cellDataProc (tree_column, cell, tree_model, iter, data); } protected void checkDevice () { - if (thread is null) error (SWT.ERROR_WIDGET_DISPOSED); - if (thread !is Thread.getThis ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); - if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED); + if (thread is null) error (SWT.ERROR_WIDGET_DISPOSED); + if (thread !is Thread.getThis ()) error (SWT.ERROR_THREAD_INVALID_ACCESS); + if (isDisposed ()) error (SWT.ERROR_DEVICE_DISPOSED); } static synchronized void checkDisplay (Thread thread, bool multiple) { - for (int i=0; i