view dwt/widgets/Tree.d @ 123:63a09873578e

Fixed compile errors
author Jacob Carlborg <doob@me.com>
date Thu, 15 Jan 2009 23:08:54 +0100
parents c7f7f4d7091a
children 1a0129cab08e
line wrap: on
line source

/*******************************************************************************
 * Copyright (c) 2000, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     
 * Port to the D programming language:
 *     Jacob Carlborg <doob@me.com>
 *******************************************************************************/
module dwt.widgets.Tree;

import dwt.dwthelper.utils;

import dwt.DWT;
import dwt.DWTException;
import dwt.accessibility.ACC;
import dwt.events.SelectionEvent;
import dwt.events.SelectionListener;
import dwt.events.TreeListener;
import dwt.graphics.Color;
import dwt.graphics.Font;
import dwt.graphics.GC;
import dwt.graphics.GCData;
import dwt.graphics.Image;
import dwt.graphics.Point;
import dwt.graphics.Rectangle;
import dwt.internal.cocoa.NSArray;
import dwt.internal.cocoa.NSBezierPath;
import dwt.internal.cocoa.NSBrowserCell;
import dwt.internal.cocoa.NSButtonCell;
import dwt.internal.cocoa.NSColor;
import dwt.internal.cocoa.NSColorSpace;
import dwt.internal.cocoa.NSDictionary;
import dwt.internal.cocoa.NSEvent;
import dwt.internal.cocoa.NSFont;
import dwt.internal.cocoa.NSGraphicsContext;
import dwt.internal.cocoa.NSIndexSet;
import dwt.internal.cocoa.NSMutableIndexSet;
import dwt.internal.cocoa.NSNotification;
import dwt.internal.cocoa.NSNumber;
import dwt.internal.cocoa.NSOutlineView;
import dwt.internal.cocoa.NSPoint;
import dwt.internal.cocoa.NSRange;
import dwt.internal.cocoa.NSRect;
import dwt.internal.cocoa.NSScrollView;
import dwt.internal.cocoa.NSSize;
import dwt.internal.cocoa.NSString;
import dwt.internal.cocoa.NSTableColumn;
import dwt.internal.cocoa.NSTableHeaderCell;
import dwt.internal.cocoa.NSTableHeaderView;
import dwt.internal.cocoa.NSTableView;
import dwt.internal.cocoa.NSView;
import dwt.internal.cocoa.OS;
import dwt.internal.cocoa.SWTBrowserCell;
import dwt.internal.cocoa.SWTOutlineView;
import dwt.internal.cocoa.SWTScrollView;
import dwt.internal.cocoa.SWTTableHeaderCell;
import dwt.internal.cocoa.SWTTableHeaderView;
import dwt.internal.cocoa.SWTTreeItem;
import cocoa = dwt.internal.cocoa.id;

import Carbon = dwt.internal.c.Carbon;
import dwt.internal.objc.cocoa.Cocoa;
import objc = dwt.internal.objc.runtime;
import dwt.widgets.Composite;
import dwt.widgets.Event;
import dwt.widgets.TreeColumn;
import dwt.widgets.TreeItem;
import dwt.widgets.TypedListener;
import dwt.widgets.Widget;

/**
 * Instances of this class provide a selectable user interface object
 * that displays a hierarchy of items and issues notification when an
 * item in the hierarchy is selected.
 * <p>
 * The item children that may be added to instances of this class
 * must be of type <code>TreeItem</code>.
 * </p><p>
 * Style <code>VIRTUAL</code> is used to create a <code>Tree</code> whose
 * <code>TreeItem</code>s are to be populated by the client on an on-demand basis
 * instead of up-front.  This can provide significant performance improvements for
 * trees that are very large or for which <code>TreeItem</code> population is
 * expensive (for example, retrieving values from an external source).
 * </p><p>
 * Here is an example of using a <code>Tree</code> with style <code>VIRTUAL</code>:
 * <code><pre>
 *  final Tree tree = new Tree(parent, DWT.VIRTUAL | DWT.BORDER);
 *  tree.setItemCount(20);
 *  tree.addListener(DWT.SetData, new Listener() {
 *      public void handleEvent(Event event) {
 *          TreeItem item = cast(TreeItem)event.item;
 *          TreeItem parentItem = item.getParentItem();
 *          String text = null;
 *          if (parentItem is null) {
 *              text = "node " + tree.indexOf(item);
 *          } else {
 *              text = parentItem.getText() + " - " + parentItem.indexOf(item);
 *          }
 *          item.setText(text);
 *          System.out.println(text);
 *          item.setItemCount(10);
 *      }
 *  });
 * </pre></code>
 * </p><p>
 * Note that although this class is a subclass of <code>Composite</code>,
 * it does not normally make sense to add <code>Control</code> children to
 * it, or set a layout on it, unless implementing something like a cell
 * editor.
 * </p><p>
 * <dl>
 * <dt><b>Styles:</b></dt>
 * <dd>SINGLE, MULTI, CHECK, FULL_SELECTION, VIRTUAL, NO_SCROLL</dd>
 * <dt><b>Events:</b></dt>
 * <dd>Selection, DefaultSelection, Collapse, Expand, SetData, MeasureItem, EraseItem, PaintItem</dd>
 * </dl>
 * </p><p>
 * Note: Only one of the styles SINGLE and MULTI may be specified.
 * </p><p>
 * IMPORTANT: This class is <em>not</em> intended to be subclassed.
 * </p>
 *
 * @see <a href="http://www.eclipse.org/swt/snippets/#tree">Tree, TreeItem, TreeColumn snippets</a>
 * @see <a href="http://www.eclipse.org/swt/examples.php">DWT Example: ControlExample</a>
 * @see <a href="http://www.eclipse.org/swt/">Sample code and further information</a>
 */
public class Tree : Composite {
    NSTableColumn firstColumn, checkColumn;
    NSBrowserCell dataCell;
    NSTableHeaderView headerView;
    TreeItem [] items;
    int itemCount;
    TreeColumn [] columns;
    TreeColumn sortColumn;
    int columnCount;
    int sortDirection;
    Carbon.CGFloat levelIndent;
    bool ignoreExpand, ignoreSelect;
    
/**
 * Constructs a new instance of this class given its parent
 * and a style value describing its behavior and appearance.
 * <p>
 * The style value is either one of the style constants defined in
 * class <code>DWT</code> which is applicable to instances of this
 * class, or must be built by <em>bitwise OR</em>'ing together 
 * (that is, using the <code>int</code> "|" operator) two or more
 * of those <code>DWT</code> style constants. The class description
 * lists the style constants that are applicable to the class.
 * Style bits are also inherited from superclasses.
 * </p>
 *
 * @param parent a composite control which will be the parent of the new instance (cannot be null)
 * @param style the style of control to construct
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the parent is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the parent</li>
 *    <li>ERROR_INVALID_SUBCLASS - if this class is not an allowed subclass</li>
 * </ul>
 *
 * @see DWT#SINGLE
 * @see DWT#MULTI
 * @see DWT#CHECK
 * @see DWT#FULL_SELECTION
 * @see DWT#VIRTUAL
 * @see DWT#NO_SCROLL
 * @see Widget#checkSubclass
 * @see Widget#getStyle
 */
public this (Composite parent, int style) {
    super (parent, checkStyle (style));
}

TreeItem _getItem (TreeItem parentItem, int index, bool create) {
    int count;
    TreeItem[] items;
    if (parentItem !is null) {
        count = parentItem.itemCount;
        items = parentItem.items;
    } else {
        count = this.itemCount;
        items = this.items;
    }
    if (index < 0 || index >= count) return null;
    TreeItem item = items [index]; 
    if (item !is null || (style & DWT.VIRTUAL) is 0 || !create) return item;
    item = new TreeItem (this, parentItem, DWT.NONE, index, false);
    items [index] = item;
    return item;
}

objc.id accessibilityAttributeValue (objc.id id, objc.SEL sel, objc.id arg0) {
    
    if (accessible !is null) {
        NSString attribute = new NSString(arg0);
        cocoa.id returnValue = accessible.internal_accessibilityAttributeValue(attribute, ACC.CHILDID_SELF);
        if (returnValue !is null) return returnValue.id;
    }
    
    NSString attributeName = new NSString(arg0);
    
    // Accessibility Verifier queries for a title or description.  NSOutlineView doesn't
    // seem to return either, so we return a default description value here.
    if (attributeName.isEqualToString (OS.NSAccessibilityDescriptionAttribute)) {
        return NSString.stringWith("").id;
    }
    
    return super.accessibilityAttributeValue(id, sel, arg0);
}


/**
 * Adds the listener to the collection of listeners who will
 * be notified when the user changes the receiver's selection, by sending
 * it one of the messages defined in the <code>SelectionListener</code>
 * interface.
 * <p>
 * When <code>widgetSelected</code> is called, the item field of the event object is valid.
 * If the receiver has the <code>DWT.CHECK</code> style and the check selection changes,
 * the event object detail field contains the value <code>DWT.CHECK</code>.
 * <code>widgetDefaultSelected</code> is typically called when an item is double-clicked.
 * The item field of the event object is valid for default selection, but the detail field is not used.
 * </p>
 *
 * @param listener the listener which should be notified when the user changes the receiver's selection
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see SelectionListener
 * @see #removeSelectionListener
 * @see SelectionEvent
 */
public void addSelectionListener(SelectionListener listener) {
    checkWidget ();
    if (listener is null) error (DWT.ERROR_NULL_ARGUMENT);
    TypedListener typedListener = new TypedListener (listener);
    addListener (DWT.Selection, typedListener);
    addListener (DWT.DefaultSelection, typedListener);
}

/**
 * Adds the listener to the collection of listeners who will
 * be notified when an item in the receiver is expanded or collapsed
 * by sending it one of the messages defined in the <code>TreeListener</code>
 * interface.
 *
 * @param listener the listener which should be notified
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see TreeListener
 * @see #removeTreeListener
 */
public void addTreeListener(TreeListener listener) {
    checkWidget ();
    if (listener is null) error (DWT.ERROR_NULL_ARGUMENT);
    TypedListener typedListener = new TypedListener (listener);
    addListener (DWT.Expand, typedListener);
    addListener (DWT.Collapse, typedListener);
}

bool checkData (TreeItem item, bool redraw) {
    if (item.cached) return true;
    if ((style & DWT.VIRTUAL) !is 0) {
        item.cached = true;
        Event event = new Event ();
        TreeItem parentItem = item.getParentItem ();
        event.item = item;
        event.index = parentItem is null ? indexOf (item) : parentItem.indexOf (item);
        //      ignoreRedraw = true;
        sendEvent (DWT.SetData, event);
        //widget could be disposed at this point
        //      ignoreRedraw = false;
        if (isDisposed () || item.isDisposed ()) return false;
        if (redraw) {
            //          if (!setScrollWidth (item)) item.redraw (OS.kDataBrowserNoItem);
        }
    }
    return true;
}

static int checkStyle (int style) {
    /*
     * Feature in Windows.  Even when WS_HSCROLL or
     * WS_VSCROLL is not specified, Windows creates
     * trees and tables with scroll bars.  The fix
     * is to set H_SCROLL and V_SCROLL.
     * 
     * NOTE: This code appears on all platforms so that
     * applications have consistent scroll bar behavior.
     */
    if ((style & DWT.NO_SCROLL) is 0) {
        style |= DWT.H_SCROLL | DWT.V_SCROLL;
    }
    return checkBits (style, DWT.SINGLE, DWT.MULTI, 0, 0, 0, 0);
}

protected void checkSubclass () {
    if (!isValidSubclass ()) error (DWT.ERROR_INVALID_SUBCLASS);
}

void clear (TreeItem parentItem, int index, bool all) {
    TreeItem item = _getItem (parentItem, index, false);
    if (item !is null) {
        item.clear();
        (cast(NSOutlineView) view).reloadItem (item.handle);
        if (all) {
            clearAll (item, true);
        }
    }
}

void clearAll (TreeItem parentItem, bool all) {
    int count = getItemCount (parentItem);
    if (count is 0) return;
    TreeItem [] children = parentItem is null ? items : parentItem.items; 
    for (int i=0; i<count; i++) {
        TreeItem item = children [i];
        if (item !is null) {
            item.clear ();
            (cast(NSOutlineView) view).reloadItem (item.handle);
            if (all) clearAll (item, true);
        }
    }
}

/**
 * Clears the item at the given zero-relative index in the receiver.
 * The text, icon and other attributes of the item are set to the default
 * value.  If the tree was created with the <code>DWT.VIRTUAL</code> style,
 * these attributes are requested again as needed.
 *
 * @param index the index of the item to clear
 * @param all <code>true</code> if all child items of the indexed item should be
 * cleared recursively, and <code>false</code> otherwise
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see DWT#VIRTUAL
 * @see DWT#SetData
 * 
 * @since 3.2
 */
public void clear (int index, bool all) {
    checkWidget ();
    int count = getItemCount ();
    if (index < 0 || index >= count) error (DWT.ERROR_INVALID_RANGE);
    clear (null, index, all);
}

/**
 * Clears all the items in the receiver. The text, icon and other
 * attributes of the items are set to their default values. If the
 * tree was created with the <code>DWT.VIRTUAL</code> style, these
 * attributes are requested again as needed.
 * 
 * @param all <code>true</code> if all child items should be cleared
 * recursively, and <code>false</code> otherwise
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see DWT#VIRTUAL
 * @see DWT#SetData
 * 
 * @since 3.2
 */
public void clearAll (bool all) {
    checkWidget ();
    clearAll (null, all);
}

void clearCustomWidths (TreeItem item) {
    item.customWidth = -1;
    for (int i = 0; i < item.itemCount; i++) {
        clearCustomWidths (items[i]);
    }
}

public Point computeSize (int wHint, int hHint, bool changed) {
    checkWidget ();
    int width = 0, height = 0;
    if (wHint is DWT.DEFAULT) {
        if (columnCount !is 0) {
            for (int i=0; i<columnCount; i++) {
                width += columns [i].getWidth ();
            }
        } else {
            //          int levelIndent = DISCLOSURE_COLUMN_LEVEL_INDENT;
            //          if (OS.VERSION >= 0x1040) {
            //              float [] metric = new float [1];
            //              OS.DataBrowserGetMetric (handle, OS.kDataBrowserMetricDisclosureColumnPerDepthGap, null, metric);
            //              levelIndent = cast(int) metric [0];
            //          }
            //          GC gc = new GC (this);
            //          width = calculateWidth (childIds, gc, true, 0, levelIndent);
            //          gc.dispose ();
            //          width += getInsetWidth (columnid, true);
        }
        if ((style & DWT.CHECK) !is 0) width += getCheckColumnWidth ();
    } else {
        width = wHint;
    }
    if (hHint is DWT.DEFAULT) {
        height = cast(int)/*64*/(cast(NSOutlineView) view).numberOfRows () * getItemHeight () + getHeaderHeight ();
    } else {
        height = hHint;
    }
    if (width <= 0) width = DEFAULT_WIDTH;
    if (height <= 0) height = DEFAULT_HEIGHT;
    Rectangle rect = computeTrim (0, 0, width, height);
    return new Point (rect.width, rect.height);
}

void createColumn (TreeItem item, int index) {
    if (item.items !is null) {
        for (int i = 0; i < item.items.length; i++) {
            if (item.items[i] !is null) createColumn (item.items[i], index);
        }
    }
    String [] strings = item.strings;
    if (strings !is null) {
        String [] temp = new String [columnCount];
        System.arraycopy (strings, 0, temp, 0, index);
        System.arraycopy (strings, index, temp, index+1, columnCount-index-1);
        temp [index] = "";
        item.strings = temp;
    }
    if (index is 0) item.text = "";
    Image [] images = item.images;
    if (images !is null) {
        Image [] temp = new Image [columnCount];
        System.arraycopy (images, 0, temp, 0, index);
        System.arraycopy (images, index, temp, index+1, columnCount-index-1);
        item.images = temp;
    }
    if (index is 0) item.image = null;
    Color [] cellBackground = item.cellBackground;
    if (cellBackground !is null) {
        Color [] temp = new Color [columnCount];
        System.arraycopy (cellBackground, 0, temp, 0, index);
        System.arraycopy (cellBackground, index, temp, index+1, columnCount-index-1);
        item.cellBackground = temp;
    }
    Color [] cellForeground = item.cellForeground;
    if (cellForeground !is null) {
        Color [] temp = new Color [columnCount];
        System.arraycopy (cellForeground, 0, temp, 0, index);
        System.arraycopy (cellForeground, index, temp, index+1, columnCount-index-1);
        item.cellForeground = temp;
    }
    Font [] cellFont = item.cellFont;
    if (cellFont !is null) {
        Font [] temp = new Font [columnCount];
        System.arraycopy (cellFont, 0, temp, 0, index);
        System.arraycopy (cellFont, index, temp, index+1, columnCount-index-1);
        item.cellFont = temp;
    }
}

void createHandle () {
    NSScrollView scrollWidget = cast(NSScrollView) (new SWTScrollView ()).alloc ();
    scrollWidget.initWithFrame (NSRect ());
    scrollWidget.setHasHorizontalScroller (true);
    scrollWidget.setHasVerticalScroller (true);
    scrollWidget.setAutohidesScrollers (true);
    scrollWidget.setBorderType(hasBorder () ? OS.NSBezelBorder : OS.NSNoBorder);
    
    NSOutlineView widget = cast(NSOutlineView) (new SWTOutlineView ()).alloc ();
    widget.initWithFrame (NSRect ());
    widget.setAllowsMultipleSelection ((style & DWT.MULTI) !is 0);
    widget.setAllowsColumnReordering (false);
    widget.setAutoresizesOutlineColumn (false);
    widget.setAutosaveExpandedItems (true);
    widget.setDataSource (widget);
    widget.setDelegate (widget);
    widget.setDoubleAction (OS.sel_sendDoubleSelection);
    if (!hasBorder ()) widget.setFocusRingType (OS.NSFocusRingTypeNone);
    
    headerView = cast(NSTableHeaderView)(new SWTTableHeaderView ()).alloc ().init ();
    widget.setHeaderView (null);
    
    NSString str = NSString.stringWith ("");
    if ((style & DWT.CHECK) !is 0) {
        checkColumn = cast(NSTableColumn) (new NSTableColumn ()).alloc ();
        checkColumn.initWithIdentifier (checkColumn);
        checkColumn.headerCell ().setTitle (str);
        widget.addTableColumn (checkColumn);
        widget.setOutlineTableColumn (checkColumn);
        NSButtonCell cell = cast(NSButtonCell) (new NSButtonCell ()).alloc ().init ();
        checkColumn.setDataCell (cell);
        cell.setButtonType (OS.NSSwitchButton);
        cell.setImagePosition (OS.NSImageOnly);
        cell.setAllowsMixedState (true);
        checkColumn.setWidth (getCheckColumnWidth ());
        checkColumn.setResizingMask (OS.NSTableColumnNoResizing);
        checkColumn.setEditable (false);
        cell.release ();
    }
    
    firstColumn = cast(NSTableColumn) (new NSTableColumn ()).alloc ();
    firstColumn.initWithIdentifier (firstColumn);
    firstColumn.setMinWidth(0);
    firstColumn.headerCell ().setTitle (str);
    widget.addTableColumn (firstColumn);
    widget.setOutlineTableColumn (firstColumn);
    dataCell = cast(NSBrowserCell)(new SWTBrowserCell ()).alloc ().init ();
    dataCell.setLeaf (true);
    firstColumn.setDataCell (dataCell);
    levelIndent = widget.indentationPerLevel ();
    
    scrollView = scrollWidget;
    view = widget;
}

void createItem (TreeColumn column, int index) {
    if (!(0 <= index && index <= columnCount)) error (DWT.ERROR_INVALID_RANGE);
    if (index is 0) {
        // first column must be left aligned
        column.style &= ~(DWT.LEFT | DWT.RIGHT | DWT.CENTER);
        column.style |= DWT.LEFT;
    }
    if (columnCount is columns.length) {
        TreeColumn [] newColumns = new TreeColumn [columnCount + 4];
        System.arraycopy (columns, 0, newColumns, 0, columns.length);
        columns = newColumns;
    }
    NSTableColumn nsColumn;
    if (columnCount is 0) {
        //TODO - clear attributes, alignment etc.
        nsColumn = firstColumn;
        nsColumn.retain();
        firstColumn = null;
    } else {
        //TODO - set attributes, alignment etc.
        NSOutlineView outlineView = cast(NSOutlineView)view;
        NSString str = NSString.stringWith ("");
        nsColumn = cast(NSTableColumn) (new NSTableColumn ()).alloc ();
        nsColumn.initWithIdentifier (nsColumn);
        nsColumn.setMinWidth(0);
        nsColumn.headerCell ().setTitle (str);
        outlineView.addTableColumn (nsColumn);
        int checkColumn = (style & DWT.CHECK) !is 0 ? 1 : 0;
        outlineView.moveColumn (columnCount + checkColumn, index + checkColumn);
        nsColumn.setDataCell (dataCell);
        if (index is 0) {
            outlineView.setOutlineTableColumn (nsColumn);
        }
    }
    column.createJNIRef ();
    NSTableHeaderCell headerCell = cast(NSTableHeaderCell)(new SWTTableHeaderCell ()).alloc ().init ();
    nsColumn.setHeaderCell (headerCell);
    display.addWidget (headerCell, column);
    column.nsColumn = nsColumn;
    nsColumn.setWidth (0);
    System.arraycopy (columns, index, columns, index + 1, columnCount++ - index);
    columns [index] = column;
    if (columnCount > 1) {
        for (int i=0; i<items.length; i++) {
            TreeItem item = items [i];
            if (item !is null) createColumn (item, index);
        }
    } else {
        for (int i = 0; i < itemCount; i++) {
            clearCustomWidths (items[i]);
        }
    }
}

void createItem (TreeItem item, TreeItem parentItem, int index) {
    int count;
    TreeItem [] items;
    if (parentItem !is null) {
        count = parentItem.itemCount;
        items = parentItem.items;
    } else {
        count = this.itemCount;
        items = this.items;
    }
    if (index is -1) index = count;
    if (!(0 <= index && index <= count)) error (DWT.ERROR_INVALID_RANGE);
    if (count is items.length) {
        TreeItem [] newItems = new TreeItem [items.length + 4];
        System.arraycopy (items, 0, newItems, 0, items.length);
        items = newItems;
        if (parentItem !is null) {
            parentItem.items = items;
        } else {
            this.items = items;
        }
    }
    System.arraycopy (items, index, items, index + 1, count++ - index);
    items [index] = item;
    item.items = new TreeItem [4];
    SWTTreeItem handle = cast(SWTTreeItem) (new SWTTreeItem ()).alloc ().init ();
    item.handle = handle;
    item.createJNIRef ();
    item.register ();
    if (parentItem !is null) {
        parentItem.itemCount = count;
    } else {
        this.itemCount = count;
    }
    ignoreExpand = true;
    NSOutlineView widget = cast(NSOutlineView)view;
    widget.reloadItem(parentItem !is null ? parentItem.handle : null, true);
    ignoreExpand = false;
}

void createWidget () {
    super.createWidget ();
    items = new TreeItem [4];
    columns = new TreeColumn [4];
}

Color defaultBackground () {
    return display.getSystemColor (DWT.COLOR_LIST_BACKGROUND);
}

Color defaultForeground () {
    return display.getSystemColor (DWT.COLOR_LIST_FOREGROUND);
}

/**
 * Deselects all selected items in the receiver.
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void deselectAll () {
    checkWidget ();
    NSTableView widget = cast(NSOutlineView) view;
    ignoreSelect = true;
    widget.deselectAll (null);
    ignoreSelect = false;
}

void deregister () {
    super.deregister ();
    display.removeWidget (headerView);
    display.removeWidget (dataCell);
}

/**
 * Deselects an item in the receiver.  If the item was already
 * deselected, it remains deselected.
 *
 * @param item the item to be deselected
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @since 3.4
 */
public void deselect (TreeItem item) {
    checkWidget ();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    //  ignoreSelect = true;
    //  /*
    //  * Bug in the Macintosh.  When the DataBroswer selection flags includes
    //  * both kDataBrowserNeverEmptySelectionSet and kDataBrowserSelectOnlyOne,
    //  * two items are selected when SetDataBrowserSelectedItems() is called
    //  * with kDataBrowserItemsAssign to assign a new seletion despite the fact
    //  * that kDataBrowserSelectOnlyOne was specified.  The fix is to save and
    //  * restore kDataBrowserNeverEmptySelectionSet around each call to
    //  * SetDataBrowserSelectedItems().
    //  */
    //  int [] selectionFlags = null;
    //  if ((style & DWT.SINGLE) !is 0) {
    //      selectionFlags = new int [1];
    //      OS.GetDataBrowserSelectionFlags (handle, selectionFlags);
    //      OS.SetDataBrowserSelectionFlags (handle, selectionFlags [0] & ~OS.kDataBrowserNeverEmptySelectionSet);
    //  }
    //  OS.SetDataBrowserSelectedItems (handle, 1, new int [] {item.id}, OS.kDataBrowserItemsRemove);
    //  if ((style & DWT.SINGLE) !is 0) {
    //      OS.SetDataBrowserSelectionFlags (handle, selectionFlags [0]);
    //  }
    //  ignoreSelect = false;
}


void destroyItem (TreeColumn column) {
    int index = 0;
    while (index < columnCount) {
        if (columns [index] is column) break;
        index++;
    }
    for (int i=0; i<items.length; i++) {
        TreeItem item = items [i];
        if (item !is null) {
            if (columnCount <= 1) {
                item.strings = null;
                item.images = null;
                item.cellBackground = null;
                item.cellForeground = null;
                item.cellFont = null;
            } else {
                if (item.strings !is null) {
                    String [] strings = item.strings;
                    if (index is 0) {
                        item.text = strings [1] !is null ? strings [1] : "";
                    }
                    String [] temp = new String [columnCount - 1];
                    System.arraycopy (strings, 0, temp, 0, index);
                    System.arraycopy (strings, index + 1, temp, index, columnCount - 1 - index);
                    item.strings = temp;
                } else {
                    if (index is 0) item.text = "";
                }
                if (item.images !is null) {
                    Image [] images = item.images;
                    if (index is 0) item.image = images [1];
                    Image [] temp = new Image [columnCount - 1];
                    System.arraycopy (images, 0, temp, 0, index);
                    System.arraycopy (images, index + 1, temp, index, columnCount - 1 - index);
                    item.images = temp;
                } else {
                    if (index is 0) item.image = null;
                }
                if (item.cellBackground !is null) {
                    Color [] cellBackground = item.cellBackground;
                    Color [] temp = new Color [columnCount - 1];
                    System.arraycopy (cellBackground, 0, temp, 0, index);
                    System.arraycopy (cellBackground, index + 1, temp, index, columnCount - 1 - index);
                    item.cellBackground = temp;
                }
                if (item.cellForeground !is null) {
                    Color [] cellForeground = item.cellForeground;
                    Color [] temp = new Color [columnCount - 1];
                    System.arraycopy (cellForeground, 0, temp, 0, index);
                    System.arraycopy (cellForeground, index + 1, temp, index, columnCount - 1 - index);
                    item.cellForeground = temp;
                }
                if (item.cellFont !is null) {
                    Font [] cellFont = item.cellFont;
                    Font [] temp = new Font [columnCount - 1];
                    System.arraycopy (cellFont, 0, temp, 0, index);
                    System.arraycopy (cellFont, index + 1, temp, index, columnCount - 1 - index);
                    item.cellFont = temp;
                }
            }
        }
    }
    
    NSInteger oldIndex = (cast(NSOutlineView)view).columnWithIdentifier (column.nsColumn);
    
    if (columnCount is 1) {
        //TODO - reset attributes
        firstColumn = column.nsColumn;
        firstColumn.setWidth (0);
    } else {
        if (index is 0) {
            (cast(NSOutlineView)view).setOutlineTableColumn(columns[1].nsColumn);
        }
        (cast(NSOutlineView)view).removeTableColumn(column.nsColumn);
    }
    System.arraycopy (columns, index + 1, columns, index, --columnCount - index);
    columns [columnCount] = null;
    
    NSArray array = (cast(NSOutlineView)view).tableColumns ();
    NSUInteger arraySize = cast(int)/*64*/array.count ();
    for (NSUInteger i = oldIndex; i < arraySize; i++) {
        objc.id columnId = array.objectAtIndex (i).id;
        for (int j = 0; j < columnCount; j++) {
            if (columns[j].nsColumn.id is columnId) {
                columns [j].sendEvent (DWT.Move);
                break;
            }
        }
    }
}

void destroyItem (TreeItem item) {
    int count;
    TreeItem[] items;
    TreeItem parentItem = item.parentItem;
    if (parentItem !is null) {
        count = parentItem.itemCount;
        items = parentItem.items;
    } else {
        count = this.itemCount;
        items = this.items;
    }
    int index = 0;
    while (index < count) {
        if (items [index] is item) break;
        index++;
    }
    //  if (index !is itemCount - 1) fixSelection (index, false); 
    System.arraycopy (items, index + 1, items, index, --count - index);
    items [count] = null;
    if (parentItem !is null) {
        parentItem.itemCount = count;
        (cast(NSOutlineView) view).reloadItem (parentItem.handle, true);
    } else {
        this.itemCount = count;
        (cast(NSOutlineView) view).reloadItem (null);
    }
    
    //noteNumberOfRowsChanged was causing crashes whenever
    //a TreeItem was disposed. 
    //Using reloadItem avoids the crashes.
    //Not sure that this NSTableView function 
    //makes sense in an NSOutlineView.
    
    //(cast(NSTableView)view).noteNumberOfRowsChanged();
    
    //  setScrollWidth (true);
    //  fixScrollBar ();
}

void drawInteriorWithFrame_inView (objc.id id, objc.SEL sel, objc.id cellFrame, objc.id view) {
    NSRect rect = NSRect ();
    OS.memmove (&rect, cellFrame, NSRect.sizeof);
    
    NSOutlineView outlineView = cast(NSOutlineView)this.view;
    NSBrowserCell cell = new NSBrowserCell (id);
    NSRange rowsRange = outlineView.rowsInRect (rect);
    NSUInteger rowIndex = rowsRange.location;
    TreeItem item = cast(TreeItem) display.getWidget (outlineView.itemAtRow (rowIndex).id);
    int columnIndex = 0;
    cocoa.id nsColumn = null;
    NSUInteger nsColumnIndex = 0;
    if (columnCount !is 0) {
        NSIndexSet columnsSet = outlineView.columnIndexesInRect (rect);
        nsColumnIndex = columnsSet.firstIndex ();
        NSArray nsColumns = outlineView.tableColumns ();
        nsColumn = nsColumns.objectAtIndex (nsColumnIndex);
        for (int i = 0; i < columnCount; i++) {
            if (columns[i].nsColumn.id is nsColumn.id) {
                columnIndex = indexOf (columns[i]);
                break;
            }
        }
    }
    
    Color background = item.cellBackground !is null ? item.cellBackground [columnIndex] : null;
    if (background is null) background = item.background;
    bool drawBackground = background !is null;
    bool drawForeground = true;
    bool isSelected = outlineView.isRowSelected (rowIndex);
    bool drawSelection = isSelected;
    
    NSColor nsSelectionBackground = null;
    NSColor nsSelectionForeground = null;
    if (isSelected) {
        if (isFocusControl ()) {
            nsSelectionForeground = NSColor.alternateSelectedControlTextColor ();
        } else {
            nsSelectionForeground = NSColor.selectedControlTextColor ();
        }
        nsSelectionForeground = nsSelectionForeground.colorUsingColorSpace (NSColorSpace.deviceRGBColorSpace ());
        nsSelectionBackground = cell.highlightColorInView (outlineView);
        nsSelectionBackground = nsSelectionBackground.colorUsingColorSpace (NSColorSpace.deviceRGBColorSpace ());
    }
    
    NSRect fullRect = NSRect ();
    fullRect.y = rect.y; fullRect.height = rect.height;
    if (columnCount is 0) {
        fullRect.x = rect.x;
        if (item.customWidth !is -1) {
            fullRect.width = item.customWidth;
        } else {
            NSSize contentSize = cell.cellSizeForBounds (rect);
            fullRect.width = contentSize.width;
        }
    } else {
        NSSize spacing = outlineView.intercellSpacing ();
        if (nsColumn.id is outlineView.outlineTableColumn ().id) {
            NSRect columnRect = outlineView.rectOfColumn (nsColumnIndex);
            fullRect.x = columnRect.x; fullRect.width = columnRect.width + spacing.width;
        } else {
            fullRect.x = rect.x;
            fullRect.width = rect.width + spacing.width;
        }
    }
    
    if (hooks (DWT.EraseItem)) {
        NSRect eraseItemRect;
        // TODO how to handle rearranged columns?  The third clause below ensures that
        // there are either 0 columns or that column 0 is still the first physical column.
        if (columnIndex is 0 && (style & DWT.CHECK) !is 0 && (columnCount is 0 || outlineView.columnWithIdentifier (columns[0].nsColumn) is 1)) {
            eraseItemRect = NSRect ();
            eraseItemRect.y = fullRect.y;
            eraseItemRect.width = fullRect.x + fullRect.width;
            eraseItemRect.height = fullRect.height;
        } else {
            eraseItemRect = fullRect;
        }
        GCData data = new GCData ();
        data.paintRectStruct = eraseItemRect;
        data.paintRect = &data.paintRectStruct;
        GC gc = GC.cocoa_new (this, data);
        gc.setFont (item.getFont (columnIndex));
        if (isSelected) {
            Carbon.CGFloat[] components = new Carbon.CGFloat[nsSelectionForeground.numberOfComponents ()];
            nsSelectionForeground.getComponents (components.ptr);   
            Color selectionForeground = Color.cocoa_new (display, components);
            gc.setForeground (selectionForeground);
            components = new Carbon.CGFloat[nsSelectionBackground.numberOfComponents ()];
            nsSelectionBackground.getComponents (components.ptr);   
            Color selectionBackground = Color.cocoa_new (display, components);
            gc.setBackground (selectionBackground);
        } else {
            gc.setForeground (item.getForeground (columnIndex));
            gc.setBackground (item.getBackground (columnIndex));
        }
        
        Event event = new Event ();
        event.item = item;
        event.gc = gc;
        event.index = columnIndex;
        event.detail = DWT.FOREGROUND;
        if (drawBackground) event.detail |= DWT.BACKGROUND;
        if (isSelected) event.detail |= DWT.SELECTED;
        event.x = cast(int)eraseItemRect.x;
        event.y = cast(int)eraseItemRect.y;
        event.width = cast(int)eraseItemRect.width;
        event.height = cast(int)eraseItemRect.height;
        sendEvent (DWT.EraseItem, event);
        gc.dispose ();
        if (item.isDisposed ()) return;
        if (!event.doit) {
            drawForeground = drawBackground = drawSelection = false; 
        } else {
            drawBackground = drawBackground && (event.detail & DWT.BACKGROUND) !is 0;
            drawForeground = (event.detail & DWT.FOREGROUND) !is 0;
            drawSelection = drawSelection && (event.detail & DWT.SELECTED) !is 0;           
        }
        if (drawSelection) {
            NSRect selectionRect = NSRect ();
            selectionRect.y = rect.y; selectionRect.height = rect.height;
            if (columnCount > 0) {
                NSRect columnRect = outlineView.rectOfColumn (nsColumnIndex);
                selectionRect.x = columnRect.x; selectionRect.width = columnRect.width;
            } else {
                NSRect rowRect = outlineView.rectOfRow (rowIndex);
                if ((style & DWT.CHECK) !is 0) {
                    /* highlighting at this stage draws over the checkbox, so don't include its column */
                    Carbon.CGFloat checkWidth = checkColumn.width ();
                    selectionRect.x = checkWidth;
                    selectionRect.width = rowRect.width - checkWidth;
                } else {
                    selectionRect.width = rowRect.width;
                }
            }
            callSuper (outlineView.id, OS.sel_highlightSelectionInClipRect_, selectionRect);
        }
    }
    
    if (drawBackground && !drawSelection) {
        NSGraphicsContext context = NSGraphicsContext.currentContext ();
        context.saveGraphicsState ();
        Carbon.CGFloat[] colorRGB = background.handle;
        NSColor color = NSColor.colorWithDeviceRed (colorRGB[0], colorRGB[1], colorRGB[2], 1f);
        color.setFill ();
        NSBezierPath.fillRect (fullRect);
        context.restoreGraphicsState ();
    }
    
    if (drawForeground) {
        cell.setHighlighted (false);
        callSuper (id, sel, rect, view);
    }
    
    if (hooks (DWT.PaintItem)) {
        NSRect contentRect = cell.titleRectForBounds (rect);
        NSSize contentSize = cell.cellSizeForBounds (rect);
        
        GCData data = new GCData ();
        // TODO how to handle rearranged columns?  The third clause below ensures that
        // there are either 0 columns or that column 0 is still the first physical column.
        if (columnIndex is 0 && (style & DWT.CHECK) !is 0 && (columnCount is 0 || outlineView.columnWithIdentifier (columns[0].nsColumn) is 1)) {
            NSRect gcRect = NSRect ();
            gcRect.y = fullRect.y;
            gcRect.width = fullRect.x + fullRect.width;
            gcRect.height = fullRect.height;
            data.paintRectStruct = gcRect;
            data.paintRect = &data.paintRectStruct;
        } else {
            data.paintRectStruct = fullRect;
            data.paintRect = &data.paintRectStruct;
        }
        GC gc = GC.cocoa_new (this, data);
        gc.setFont (item.getFont (columnIndex));
        if (isSelected) {
            Carbon.CGFloat[] components = new Carbon.CGFloat[nsSelectionForeground.numberOfComponents ()];
            nsSelectionForeground.getComponents (components.ptr);   
            Color selectionForeground = Color.cocoa_new (display, components);
            gc.setForeground (selectionForeground);
            components = new Carbon.CGFloat[nsSelectionBackground.numberOfComponents ()];
            nsSelectionBackground.getComponents (components.ptr);   
            Color selectionBackground = Color.cocoa_new (display, components);
            gc.setBackground (selectionBackground);
            gc.setBackground (display.getSystemColor (DWT.COLOR_GREEN));
        } else {
            gc.setForeground (item.getForeground (columnIndex));
            gc.setBackground (item.getBackground (columnIndex));
        }
        
        Event event = new Event ();
        event.item = item;
        event.gc = gc;
        event.index = columnIndex;
        if (isSelected) event.detail |= DWT.SELECTED;
        event.x = cast(int)contentRect.x;
        event.y = cast(int)contentRect.y;
        event.width = cast(int)Math.ceil (contentSize.width);
        event.height = cast(int)Math.ceil (fullRect.height);
        sendEvent (DWT.PaintItem, event);
        gc.dispose ();
    }
}

void fixScrollBar () {
    /*
     * Bug in the Macintosh. For some reason, the data browser does not update
     * the vertical scrollbar when it is scrolled to the bottom and items are
     * removed.  The fix is to check if the scrollbar value is bigger the
     * maximum number of visible items and clamp it when needed.
     */
    //  int [] top = new int [1], left = new int [1];
    //  OS.GetDataBrowserScrollPosition (handle, top, left);
    //  int maximum = Math.max (0, getItemHeight () * visibleCount - getClientArea ().height);
    //  if (top [0] > maximum) {
    //      OS.SetDataBrowserScrollPosition (handle, maximum, left [0]);
    //  }
}

int getCheckColumnWidth () {
    return 20; //TODO - compute width
}

TreeColumn getColumn (cocoa.id id) {
    for (int i = 0; i < columnCount; i++) {
        if (columns[i].nsColumn.id is id.id) {
            return columns[i]; 
        }
    }
    return null;
}

/**
 * Returns the column at the given, zero-relative index in the
 * receiver. Throws an exception if the index is out of range.
 * Columns are returned in the order that they were created.
 * If no <code>TreeColumn</code>s were created by the programmer,
 * this method will throw <code>ERROR_INVALID_RANGE</code> despite
 * the fact that a single column of data may be visible in the tree.
 * This occurs when the programmer uses the tree like a list, adding
 * items but never creating a column.
 *
 * @param index the index of the column to return
 * @return the column at the given index
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see Tree#getColumnOrder()
 * @see Tree#setColumnOrder(int[])
 * @see TreeColumn#getMoveable()
 * @see TreeColumn#setMoveable(bool)
 * @see DWT#Move
 * 
 * @since 3.1
 */
public TreeColumn getColumn (int index) {
    checkWidget ();
    if (!(0 <=index && index < columnCount)) error (DWT.ERROR_INVALID_RANGE);
    return columns [index];
}

/**
 * Returns the number of columns contained in the receiver.
 * If no <code>TreeColumn</code>s were created by the programmer,
 * this value is zero, despite the fact that visually, one column
 * of items may be visible. This occurs when the programmer uses
 * the tree like a list, adding items but never creating a column.
 *
 * @return the number of columns
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public int getColumnCount () {
    checkWidget ();
    return columnCount;
}

/**
 * Returns an array of zero-relative integers that map
 * the creation order of the receiver's items to the
 * order in which they are currently being displayed.
 * <p>
 * Specifically, the indices of the returned array represent
 * the current visual order of the items, and the contents
 * of the array represent the creation order of the items.
 * </p><p>
 * Note: This is not the actual structure used by the receiver
 * to maintain its list of items, so modifying the array will
 * not affect the receiver. 
 * </p>
 *
 * @return the current visual order of the receiver's items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see Tree#setColumnOrder(int[])
 * @see TreeColumn#getMoveable()
 * @see TreeColumn#setMoveable(bool)
 * @see DWT#Move
 * 
 * @since 3.2
 */
public int [] getColumnOrder () {
    checkWidget ();
    int [] order = new int [columnCount];
    for (int i = 0; i < columnCount; i++) {
        TreeColumn column = columns [i];
        int index = (cast(NSOutlineView)view).columnWithIdentifier (column.nsColumn);
        if ((style & DWT.CHECK) !is 0) index -= 1;
        order [index] = i;
    }
    return order;
}

/**
 * Returns an array of <code>TreeColumn</code>s which are the
 * columns in the receiver. Columns are returned in the order
 * that they were created.  If no <code>TreeColumn</code>s were
 * created by the programmer, the array is empty, despite the fact
 * that visually, one column of items may be visible. This occurs
 * when the programmer uses the tree like a list, adding items but
 * never creating a column.
 * <p>
 * Note: This is not the actual structure used by the receiver
 * to maintain its list of items, so modifying the array will
 * not affect the receiver. 
 * </p>
 *
 * @return the items in the receiver
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see Tree#getColumnOrder()
 * @see Tree#setColumnOrder(int[])
 * @see TreeColumn#getMoveable()
 * @see TreeColumn#setMoveable(bool)
 * @see DWT#Move
 * 
 * @since 3.1
 */
public TreeColumn [] getColumns () {
    checkWidget ();
    TreeColumn [] result = new TreeColumn [columnCount];
    System.arraycopy (columns, 0, result, 0, columnCount);
    return result;
}

/**
 * Returns the width in pixels of a grid line.
 *
 * @return the width of a grid line in pixels
 * 
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public int getGridLineWidth () {
    checkWidget ();
    return 0;
}

/**
 * Returns the height of the receiver's header 
 *
 * @return the height of the header or zero if the header is not visible
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1 
 */
public int getHeaderHeight () {
    checkWidget ();
    NSTableHeaderView headerView = (cast(NSOutlineView) view).headerView ();
    if (headerView is null) return 0;
    return cast(int) headerView.bounds ().height;
}

/**
 * Returns <code>true</code> if the receiver's header is visible,
 * and <code>false</code> otherwise.
 * <p>
 * If one of the receiver's ancestors is not visible or some
 * other condition makes the receiver not visible, this method
 * may still indicate that it is considered visible even though
 * it may not actually be showing.
 * </p>
 *
 * @return the receiver's header's visibility state
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public bool getHeaderVisible () {
    checkWidget ();
    return (cast(NSOutlineView) view).headerView () !is null;
}

int getInsetWidth () {
    //TODO - wrong
    return 20;
}

/**
 * Returns the item at the given, zero-relative index in the
 * receiver. Throws an exception if the index is out of range.
 *
 * @param index the index of the item to return
 * @return the item at the given index
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_RANGE - if the index is not between 0 and the number of elements in the list minus 1 (inclusive)</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public TreeItem getItem (int index) {
    checkWidget ();
    int count = getItemCount ();
    if (index < 0 || index >= count) error (DWT.ERROR_INVALID_RANGE);
    return _getItem (null, index, true);
}

/**
 * Returns the item at the given point in the receiver
 * or null if no such item exists. The point is in the
 * coordinate system of the receiver.
 * <p>
 * The item that is returned represents an item that could be selected by the user.
 * For example, if selection only occurs in items in the first column, then null is 
 * returned if the point is outside of the item. 
 * Note that the DWT.FULL_SELECTION style hint, which specifies the selection policy,
 * determines the extent of the selection.
 * </p>
 *
 * @param point the point used to locate the item
 * @return the item at the given point, or null if the point is not in a selectable item
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the point is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public TreeItem getItem (Point point) {
    checkWidget ();
    if (point is null) error (DWT.ERROR_NULL_ARGUMENT);
    NSOutlineView widget = cast(NSOutlineView)view;
    NSPoint pt = NSPoint();
    pt.x = point.x;
    pt.y = point.y;
    NSInteger row = widget.rowAtPoint(pt);
    if (row is -1) return null;
    cocoa.id id = widget.itemAtRow(row);
    Widget item = display.getWidget (id.id);
    if (item !is null && cast(TreeItem) item) {
        return cast(TreeItem)item;
    }
    return null;
}

/**
 * Returns the number of items contained in the receiver
 * that are direct item children of the receiver.  The
 * number that is returned is the number of roots in the
 * tree.
 *
 * @return the number of items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public int getItemCount () {
    checkWidget ();
    return itemCount;
}

int getItemCount (TreeItem item) {
    return item is null ? itemCount : item.itemCount;
}

/**
 * Returns the height of the area which would be used to
 * display <em>one</em> of the items in the tree.
 *
 * @return the height of one item
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public int getItemHeight () {
    checkWidget ();
    return cast(int)(cast(NSOutlineView) view).rowHeight ();
}

/**
 * Returns a (possibly empty) array of items contained in the
 * receiver that are direct item children of the receiver.  These
 * are the roots of the tree.
 * <p>
 * Note: This is not the actual structure used by the receiver
 * to maintain its list of items, so modifying the array will
 * not affect the receiver. 
 * </p>
 *
 * @return the items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public TreeItem [] getItems () {
    checkWidget ();
    TreeItem [] result = new TreeItem [itemCount];
    for (int i=0; i<itemCount; i++) {
        result [i] = _getItem (null, i, true);
    }
    return result;
}

/**
 * Returns <code>true</code> if the receiver's lines are visible,
 * and <code>false</code> otherwise.
 * <p>
 * If one of the receiver's ancestors is not visible or some
 * other condition makes the receiver not visible, this method
 * may still indicate that it is considered visible even though
 * it may not actually be showing.
 * </p>
 *
 * @return the visibility state of the lines
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public bool getLinesVisible () {
    checkWidget ();
    return (cast(NSOutlineView) view).usesAlternatingRowBackgroundColors ();
}

/**
 * Returns the receiver's parent item, which must be a
 * <code>TreeItem</code> or null when the receiver is a
 * root.
 *
 * @return the receiver's parent item
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public TreeItem getParentItem () {
    checkWidget ();
    return null;
}

/**
 * Returns an array of <code>TreeItem</code>s that are currently
 * selected in the receiver. The order of the items is unspecified.
 * An empty array indicates that no items are selected. 
 * <p>
 * Note: This is not the actual structure used by the receiver
 * to maintain its selection, so modifying the array will
 * not affect the receiver. 
 * </p>
 * @return an array representing the selection
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public TreeItem [] getSelection () {
    checkWidget ();
    NSOutlineView widget = cast(NSOutlineView) view;
    if (widget.numberOfSelectedRows () is 0) {
        return new TreeItem [0];
    }
    NSIndexSet selection = widget.selectedRowIndexes ();
    NSUInteger count = selection.count ();
    NSUInteger [] indexBuffer = new NSUInteger [count];
    selection.getIndexes (indexBuffer.ptr, count, null);
    TreeItem [] result = new TreeItem [count];
    for (NSUInteger i=0; i<count; i++) {
        cocoa.id id = widget.itemAtRow (indexBuffer [i]);
        Widget item = display.getWidget (id.id);
        if (item !is null && cast(TreeItem) item) {
            //TODO virtual
            result[i] = cast(TreeItem) item;
        }
    }
    return result;
}

/**
 * Returns the number of selected items contained in the receiver.
 *
 * @return the number of selected items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public int getSelectionCount () {
    checkWidget ();
    return cast(int)/*64*/(cast(NSOutlineView) view).numberOfSelectedRows ();
}

/**
 * Returns the column which shows the sort indicator for
 * the receiver. The value may be null if no column shows
 * the sort indicator.
 *
 * @return the sort indicator 
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see #setSortColumn(TreeColumn)
 * 
 * @since 3.2
 */
public TreeColumn getSortColumn () {
    checkWidget ();
    return sortColumn;
}

/**
 * Returns the direction of the sort indicator for the receiver. 
 * The value will be one of <code>UP</code>, <code>DOWN</code> 
 * or <code>NONE</code>.
 *
 * @return the sort direction
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @see #setSortDirection(int)
 * 
 * @since 3.2
 */
public int getSortDirection () {
    checkWidget ();
    return sortDirection;
}

/**
 * Returns the item which is currently at the top of the receiver.
 * This item can change when items are expanded, collapsed, scrolled
 * or new items are added or removed.
 *
 * @return the item at the top of the receiver 
 * 
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 2.1
 */
public TreeItem getTopItem () {
    checkWidget ();
    //  //TODO - optimize
    //  Rect rect = new Rect ();
    //  int y = getBorder () + getHeaderHeight ();
    //  for (int i=0; i<items.length; i++) {
    //      TreeItem item = items [i];
    //      if (item !is null) {
    //          int columnId = (columnCount is 0) ? columnid : columns [0].id;
    //          if (OS.GetDataBrowserItemPartBounds (handle, item.id, columnId, OS.kDataBrowserPropertyEnclosingPart, rect) is OS.noErr) {
    //              if (rect.top <= y && y <= rect.bottom) return item;
    //          }
    //      }
    //  }
    return null;
}

void highlightSelectionInClipRect(objc.id id, objc.SEL sel, objc.id rect) {
    if (!hooks (DWT.EraseItem)) {
        NSRect clipRect = NSRect ();
        OS.memmove (&clipRect, rect, NSRect.sizeof);
        callSuper (id, sel, clipRect);
    }
}

/**
 * Searches the receiver's list starting at the first column
 * (index 0) until a column is found that is equal to the 
 * argument, and returns the index of that column. If no column
 * is found, returns -1.
 *
 * @param column the search column
 * @return the index of the column
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the column is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public int indexOf (TreeColumn column) {
    checkWidget ();
    if (column is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (column.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    for (int i=0; i<columnCount; i++) {
        if (columns [i] is column) return i;
    }
    return -1;
}

/**
 * Searches the receiver's list starting at the first item
 * (index 0) until an item is found that is equal to the 
 * argument, and returns the index of that item. If no item
 * is found, returns -1.
 *
 * @param item the search item
 * @return the index of the item
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public int indexOf (TreeItem item) {
    checkWidget ();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    if (item.parentItem !is null) return -1;
    for (int i = 0; i < itemCount; i++) {
        if (item is items[i]) return i;
    }
    return -1;
}

bool isTrim (NSView view) {
    if (super.isTrim (view)) return true;
    return view.id is headerView.id;
}

objc.id outlineView_child_ofItem (objc.id id, objc.SEL sel, objc.id outlineView, objc.id index, objc.id itemID) {
    TreeItem parent = cast(TreeItem) display.getWidget (itemID);
    TreeItem item = _getItem (parent, cast(int)/*64*/index, true);
    checkData (item, false);
    return item.handle.id;
}

void outlineView_didClickTableColumn (objc.id id, objc.SEL sel, objc.id outlineView, objc.id tableColumn) {
    TreeColumn column = getColumn (new cocoa.id (tableColumn));
    column.postEvent (DWT.Selection);
}

objc.id outlineView_objectValueForTableColumn_byItem (objc.id id, objc.SEL sel, objc.id outlineView, objc.id tableColumn, objc.id itemID) {
    TreeItem item = cast(TreeItem) display.getWidget (itemID);
    if (checkColumn !is null && tableColumn is checkColumn.id) {
        NSNumber value;
        if (item.checked && item.grayed) {
            value = NSNumber.numberWithInt (OS.NSMixedState);
        } else {
            value = NSNumber.numberWithInt (item.checked ? OS.NSOnState : OS.NSOffState);
        }
        return value.id;
    }
    for (int i=0; i<columnCount; i++) {
        if (columns [i].nsColumn.id is tableColumn) {
            return item.createString (i).id;
        }
    }
    return item.createString (0).id;
}

bool outlineView_isItemExpandable (objc.id id, objc.SEL sel, objc.id outlineView, objc.id item) {
    if (item is null) return true;
    return (cast(TreeItem) display.getWidget (item)).itemCount !is 0;
}

int outlineView_numberOfChildrenOfItem (objc.id id, objc.SEL sel, objc.id outlineView, objc.id item) {
    if (item is null) return itemCount;
    return (cast(TreeItem) display.getWidget (item)).itemCount;
}

void outlineView_willDisplayCell_forTableColumn_item (objc.id id, objc.SEL sel, objc.id outlineView, objc.id cell, objc.id tableColumn, objc.id itemID) {
    if (checkColumn !is null && tableColumn is checkColumn.id) return;
    TreeItem item = cast(TreeItem) display.getWidget(itemID);
    Image image = item.image;
    int columnIndex = 0;
    for (int i=0; i<columnCount; i++) {
        if (columns [i].nsColumn.id is tableColumn) {
            image = item.getImage (i);
            columnIndex = i;
        }
    }
    NSBrowserCell browserCell = new NSBrowserCell (cell);
    browserCell.setImage (image !is null ? image.handle : null);
    browserCell.setFont (item.getFont (columnIndex).handle);
    
    if (hooks (DWT.MeasureItem)) {
        NSOutlineView view = cast(NSOutlineView)this.view;
        NSInteger nsColumnIndex = view.columnWithIdentifier (new cocoa.id (tableColumn));
        NSInteger rowIndex = view.rowForItem (new cocoa.id (itemID));
        NSRect rect = view.frameOfCellAtColumn (nsColumnIndex, rowIndex);
        NSRect contentRect = browserCell.titleRectForBounds (rect);
        NSSize contentSize = browserCell.cellSizeForBounds (rect);
        
        GCData data = new GCData ();
        data.paintRectStruct = view.frame ();
        data.paintRect = &data.paintRectStruct;
        GC gc = GC.cocoa_new (this, data);
        gc.setFont (item.getFont (columnIndex));
        int rowHeight = cast(int)view.rowHeight ();
        Event event = new Event ();
        event.item = item;
        event.gc = gc;
        event.index = columnIndex;
        event.x = cast(int)contentRect.x;
        event.y = cast(int)contentRect.y;
        event.width = cast(int)Math.ceil (contentSize.width);
        event.height = rowHeight;
        sendEvent (DWT.MeasureItem, event);
        gc.dispose ();
        if (isDisposed ()) return;
        if (rowHeight < event.height) {
            view.setRowHeight (event.height);
        }
        if (columnCount is 0) {
            int change = event.width - (item.customWidth !is -1 ? item.customWidth : cast(int)Math.ceil (contentSize.width));
            if (item.customWidth !is -1 || event.width !is cast(int)Math.ceil (contentSize.width)) {
                item.customWidth = event.width; 
            }
            if (change !is 0) setScrollWidth (item, false, false);
        }
    }
}

void outlineViewColumnDidMove (objc.id id, objc.SEL sel, objc.id aNotification) {
    NSNotification notification = new NSNotification (aNotification);
    NSDictionary userInfo = notification.userInfo ();
    cocoa.id nsOldIndex = userInfo.valueForKey (NSString.stringWith ("NSOldColumn")); //$NON-NLS-1$
    cocoa.id nsNewIndex = userInfo.valueForKey (NSString.stringWith ("NSNewColumn")); //$NON-NLS-1$
    int oldIndex = (new NSNumber (nsOldIndex)).intValue ();
    int newIndex = (new NSNumber (nsNewIndex)).intValue ();
    int startIndex = Math.min (oldIndex, newIndex);
    int endIndex = Math.max (oldIndex, newIndex);
    NSOutlineView outlineView = cast(NSOutlineView)view;
    NSArray nsColumns = outlineView.tableColumns ();
    for (int i = startIndex; i <= endIndex; i++) {
        cocoa.id columnId = nsColumns.objectAtIndex (i);
        TreeColumn column = getColumn (columnId);
        if (column !is null) {
            column.sendEvent (DWT.Move);
            if (isDisposed ()) return;
        }
    }
}

void outlineViewColumnDidResize (objc.id id, objc.SEL sel, objc.id aNotification) {
    NSNotification notification = new NSNotification (aNotification);
    NSDictionary userInfo = notification.userInfo ();
    cocoa.id columnId = userInfo.valueForKey (NSString.stringWith ("NSTableColumn")); //$NON-NLS-1$
    TreeColumn column = getColumn (columnId);
    if (column is null) return; /* either CHECK column or firstColumn in 0-column Tree */
    
    column.sendEvent (DWT.Resize);
    if (isDisposed ()) return;
    
    NSOutlineView outlineView = cast(NSOutlineView)view;
    NSInteger index = outlineView.columnWithIdentifier (columnId);
    if (index is -1) return; /* column was disposed in Resize callback */
    
    NSArray nsColumns = outlineView.tableColumns ();
    NSInteger columnCount = outlineView.numberOfColumns ();
    for (NSInteger i = index + 1; i < columnCount; i++) {
        columnId = nsColumns.objectAtIndex (i);
        column = getColumn (columnId);
        if (column !is null) {
            column.sendEvent (DWT.Move);
            if (isDisposed ()) return;
        }
    }
}

void outlineViewItemDidExpand (objc.id id, objc.SEL sel, objc.id notification) {
    NSNotification nsNotification = new NSNotification (notification);
    NSDictionary info = nsNotification.userInfo ();
    NSString key = NSString.stringWith ("NSObject"); //$NON-NLS-1$
    objc.id itemHandle = info.objectForKey (key).id;
    TreeItem item = cast(TreeItem)display.getWidget (itemHandle);
    setScrollWidth (item.getItems (), true, true);
}

void outlineViewSelectionDidChange (objc.id id, objc.SEL sel, objc.id notification) {
    if (ignoreSelect) return;
    NSOutlineView widget = cast(NSOutlineView) view;
    NSInteger row = widget.selectedRow ();
    if (row is -1)
        postEvent (DWT.Selection);
    else {
        cocoa.id _id = widget.itemAtRow (row);
        TreeItem item = cast(TreeItem) display.getWidget (_id.id);
        Event event = new Event ();
        event.item = item;
        event.index = row;
        postEvent (DWT.Selection, event);
    }
}

bool outlineView_shouldCollapseItem (objc.id id, objc.SEL sel, objc.id lineView, objc.id itemID) {
    TreeItem item = cast(TreeItem) display.getWidget (itemID);
    if (!ignoreExpand) {
        Event event = new Event ();
        event.item = item;
        sendEvent (DWT.Collapse, event);
        item.expanded = false;
        ignoreExpand = true;
        (cast(NSOutlineView) view).collapseItem (item.handle);
        ignoreExpand = false;
        return false;
    }
    return !item.expanded;
}

bool outlineView_shouldExpandItem (objc.id id, objc.SEL sel, objc.id outlineView, objc.id itemID) {
    final TreeItem item = cast(TreeItem) display.getWidget (itemID);
    if (!ignoreExpand) {
        Event event = new Event ();
        event.item = item;
        sendEvent (DWT.Expand, event);
        item.expanded = true;
        ignoreExpand = true;
        (cast(NSOutlineView) view).expandItem (item.handle);
        ignoreExpand = false;
        return false;
    }
    return item.expanded;
}

void outlineView_setObjectValue_forTableColumn_byItem (objc.id id, objc.SEL sel, objc.id outlineView, objc.id object, objc.id tableColumn, objc.id itemID) {
    if (checkColumn !is null && tableColumn is checkColumn.id)  {
        TreeItem item = cast(TreeItem) display.getWidget (itemID);
        item.checked = !item.checked;
        Event event = new Event ();
        event.detail = DWT.CHECK;
        event.item = item;
        postEvent (DWT.Selection, event);
        NSOutlineView view = cast(NSOutlineView)this.view;
        NSInteger rowIndex = view.rowForItem (new cocoa.id (itemID));
        NSRect rect = view.rectOfRow (rowIndex);
        view.setNeedsDisplayInRect (rect);
    }
}

void register () {
    super.register ();
    display.addWidget (headerView, this);
    display.addWidget (dataCell, this);
}

void releaseChildren (bool destroy) {
    for (int i=0; i<items.length; i++) {
        TreeItem item = items [i];
        if (item !is null && !item.isDisposed ()) {
            item.release (false);
        }
    }
    items = null;
    if (columns !is null) {
        for (int i=0; i<columnCount; i++) {
            TreeColumn column = columns [i];
            if (column !is null && !column.isDisposed ()) {
                column.release (false);
            }
        }
        columns = null;
    }
    super.releaseChildren (destroy);
}

void releaseHandle () {
    super.releaseHandle ();
    if (headerView !is null) headerView.release ();
    headerView = null;
    if (firstColumn !is null) firstColumn.release ();
    firstColumn = null;
    if (checkColumn !is null) checkColumn.release ();
    checkColumn = null;
    if (dataCell !is null) dataCell.release ();
    dataCell = null;
}

void releaseWidget () {
    super.releaseWidget ();
    //release handle
    sortColumn = null;
}

/**
 * Removes all of the items from the receiver.
 * 
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void removeAll () {
    checkWidget ();
    for (int i=0; i<items.length; i++) {
        TreeItem item = items [i];
        if (item !is null && !item.isDisposed ()) item.release (false);
    }
    items = new TreeItem [4];
    itemCount = 0;
    (cast(NSOutlineView) view).reloadItem (null);
}

/**
 * Removes the listener from the collection of listeners who will
 * be notified when the user changes the receiver's selection.
 *
 * @param listener the listener which should no longer be notified
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see SelectionListener
 * @see #addSelectionListener
 */
public void removeSelectionListener (SelectionListener listener) {
    checkWidget ();
    if (listener is null) error (DWT.ERROR_NULL_ARGUMENT);
    eventTable.unhook (DWT.Selection, listener);
    eventTable.unhook (DWT.DefaultSelection, listener); 
}

/**
 * Removes the listener from the collection of listeners who will
 * be notified when items in the receiver are expanded or collapsed.
 *
 * @param listener the listener which should no longer be notified
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the listener is null</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see TreeListener
 * @see #addTreeListener
 */
public void removeTreeListener (TreeListener listener) {
    checkWidget ();
    if (listener is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (eventTable is null) return;
    eventTable.unhook (DWT.Expand, listener);
    eventTable.unhook (DWT.Collapse, listener);
}

/**
 * Display a mark indicating the point at which an item will be inserted.
 * The drop insert item has a visual hint to show where a dragged item 
 * will be inserted when dropped on the tree.
 * 
 * @param item the insert item.  Null will clear the insertion mark.
 * @param before true places the insert mark above 'item'. false places 
 *  the insert mark below 'item'.
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void setInsertMark (TreeItem item, bool before) {
    checkWidget ();
    if (item !is null) {
        if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    }
}

/**
 * Selects all of the items in the receiver.
 * <p>
 * If the receiver is single-select, do nothing.
 * </p>
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 */
public void selectAll () {
    checkWidget ();
    if ((style & DWT.SINGLE) !is 0) return;
    NSOutlineView widget = cast(NSOutlineView) view;
    ignoreSelect = true;
    widget.selectAll (null);
    ignoreSelect = false;
}

/**
 * Selects an item in the receiver.  If the item was already
 * selected, it remains selected.
 *
 * @param item the item to be selected
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @since 3.4
 */
public void select (TreeItem item) {
    checkWidget ();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    showItem (item);
    NSOutlineView outlineView = cast(NSOutlineView) view;
    outlineView.selectRow (outlineView.rowForItem (item.handle), false);
}

void sendDoubleSelection() {
    postEvent (DWT.DefaultSelection);
}

bool sendKeyEvent (NSEvent nsEvent, int type) {
    bool result = super.sendKeyEvent (nsEvent, type);
    if (!result) return result;
    if (type !is DWT.KeyDown) return result;
    ushort keyCode = nsEvent.keyCode ();
    switch (keyCode) {
        case 76: /* KP Enter */
        case 36: { /* Return */
            postEvent (DWT.DefaultSelection);
            break;
        }
    }
    return result;
}

void setBackground (Carbon.CGFloat [] color) {
    super.setBackground (color);
    NSColor nsColor;
    if (color is null) {
        nsColor = null;
    } else {
        nsColor = NSColor.colorWithDeviceRed (color [0], color [1], color [2], 1);
    }
    (cast(NSOutlineView) view).setBackgroundColor (nsColor);
}

/**
 * Sets the order that the items in the receiver should 
 * be displayed in to the given argument which is described
 * in terms of the zero-relative ordering of when the items
 * were added.
 *
 * @param order the new order to display the items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item order is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item order is not the same length as the number of items</li>
 * </ul>
 * 
 * @see Tree#getColumnOrder()
 * @see TreeColumn#getMoveable()
 * @see TreeColumn#setMoveable(bool)
 * @see DWT#Move
 * 
 * @since 3.2
 */
public void setColumnOrder (int [] order) {
    checkWidget ();
    if (order is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (columnCount is 0) {
        if (order.length !is 0) error (DWT.ERROR_INVALID_ARGUMENT);
        return;
    }
    if (order.length !is columnCount) error (DWT.ERROR_INVALID_ARGUMENT);
    int [] oldOrder = getColumnOrder ();
    bool reorder = false;
    bool [] seen = new bool [columnCount];
    for (int i=0; i<order.length; i++) {
        int index = order [i];
        if (index < 0 || index >= columnCount) error (DWT.ERROR_INVALID_ARGUMENT);
        if (seen [index]) error (DWT.ERROR_INVALID_ARGUMENT);
        seen [index] = true;
        if (order [i] !is oldOrder [i]) reorder = true;
    }
    if (reorder) {
        NSOutlineView outlineView = cast(NSOutlineView)view;
        int [] oldX = new int [oldOrder.length];
        int check = (style & DWT.CHECK) !is 0 ? 1 : 0;
        for (int i=0; i<oldOrder.length; i++) {
            int index = oldOrder[i];
            oldX [index] = cast(int)outlineView.rectOfColumn (i + check).x;
        }
        int [] newX = new int [order.length];
        for (int i=0; i<order.length; i++) {
            int index = order [i];
            TreeColumn column = columns[index];
            int oldIndex = outlineView.columnWithIdentifier (column.nsColumn);
            int newIndex = i + check;
            outlineView.moveColumn (oldIndex, newIndex);
            newX [index] = cast(int)outlineView.rectOfColumn (newIndex).x;
        }
        
        TreeColumn[] newColumns = new TreeColumn [columnCount];
        System.arraycopy (columns, 0, newColumns, 0, columnCount);
        for (int i=0; i<columnCount; i++) {
            TreeColumn column = newColumns [i];
            if (!column.isDisposed ()) {
                if (newX [i] !is oldX [i]) {
                    column.sendEvent (DWT.Move);
                }
            }
        }
    }
}

void setFont(NSFont font) {
    super.setFont (font);
    if (!hooks (DWT.MeasureItem)) {
        float ascent = font.ascender ();
        float descent = -font.descender () + font.leading ();
        (cast(NSOutlineView)view).setRowHeight (cast(int)Math.ceil (ascent + descent) + 1);
    } else {
        view.setNeedsDisplay (true);
    }
}

/**
 * Marks the receiver's header as visible if the argument is <code>true</code>,
 * and marks it invisible otherwise. 
 * <p>
 * If one of the receiver's ancestors is not visible or some
 * other condition makes the receiver not visible, marking
 * it visible may not actually cause it to be displayed.
 * </p>
 *
 * @param show the new visibility state
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public void setHeaderVisible (bool show) {
    checkWidget ();
    (cast(NSOutlineView) view).setHeaderView (show ? headerView : null);
}

/**
 * Sets the number of root-level items contained in the receiver.
 *
 * @param count the number of items
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @since 3.2
 */
public void setItemCount (int count) {
    checkWidget ();
    count = Math.max (0, count);
    setItemCount (null, count);
}

void setItemCount (TreeItem parentItem, int count) {
    int itemCount = getItemCount (parentItem);
    if (count is itemCount) return;
    TreeItem [] children = parentItem is null ? items : parentItem.items;
    if (count < itemCount) {
        for (int index = count; index < itemCount; index ++) {
            TreeItem item = children [index];
            if (item !is null && !item.isDisposed()) item.release (false);
        }
    }
    if (count > itemCount) {
        if ((getStyle() & DWT.VIRTUAL) is 0) {
            for (int i=itemCount; i<count; i++) {
                new TreeItem (this, parentItem, DWT.NONE, i, true);
            }
            return;
        } 
    }
    int length = Math.max (4, (count + 3) / 4 * 4);
    TreeItem [] newItems = new TreeItem [length];
    if (children !is null) {
        System.arraycopy (children, 0, newItems, 0, Math.min (count, itemCount));
    }
    children = newItems;
    if (parentItem is null) {
        this.items = newItems;
        this.itemCount = count;
    } else {
        parentItem.items = newItems;
        parentItem.itemCount = count;
    }
    NSOutlineView widget = cast(NSOutlineView) view;
    widget.reloadItem (parentItem !is null ? parentItem.handle : null, true);
    widget.noteNumberOfRowsChanged();
}

/*public*/ void setItemHeight (int itemHeight) {
    checkWidget ();
    if (itemHeight < -1) error (DWT.ERROR_INVALID_ARGUMENT);
    if (itemHeight is -1) {
        //TODO - reset item height, ensure other API's such as setFont don't do this
    } else {
        //      OS.SetDataBrowserTableViewRowHeight (handle, cast(short) itemHeight);
    }
}

void setItemHeight (Image image) {
    //  Rectangle bounds = image !is null ? image.getBounds () : imageBounds;
    //  if (bounds is null) return;
    //  imageBounds = bounds;
    //  short [] height = new short [1];
    //  if (OS.GetDataBrowserTableViewRowHeight (handle, height) is OS.noErr) {
    //      if (height [0] < bounds.height) {
    //          OS.SetDataBrowserTableViewRowHeight (handle, cast(short) bounds.height);
    //      }
    //  }
}

/**
 * Marks the receiver's lines as visible if the argument is <code>true</code>,
 * and marks it invisible otherwise. 
 * <p>
 * If one of the receiver's ancestors is not visible or some
 * other condition makes the receiver not visible, marking
 * it visible may not actually cause it to be displayed.
 * </p>
 *
 * @param show the new visibility state
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.1
 */
public void setLinesVisible (bool show) {
    checkWidget ();
    (cast(NSOutlineView) view).setUsesAlternatingRowBackgroundColors (show);
}

public void setRedraw (bool redraw) {
    checkWidget ();
    super.setRedraw (redraw);
    if (redraw && drawCount is 0) {
        setScrollWidth ();
    }
}

bool setScrollWidth () {
    return setScrollWidth (items, true, true);
}

bool setScrollWidth (TreeItem item, bool recurse, bool callMeasureItem) {
    return setScrollWidth ([item], recurse, callMeasureItem);
}

bool setScrollWidth (TreeItem[] items, bool recurse, bool callMeasureItem) {
    if (columnCount !is 0) return false;
    //  if (currentItem !is null) {
    //      if (currentItem !is item) fixScrollWidth = true;
    //      return false;
    //  }
    if (/*ignoreRedraw ||*/ drawCount !is 0) return false;
    int newWidth = 0;
    GC gc = new GC (this);
    for (int i = 0; i < items.length; i++) {
        TreeItem item = items[i];
        if (item !is null && !item.isDisposed ()) {
            newWidth = Math.max (newWidth, item.calculateWidth (0, gc, recurse, callMeasureItem));
            if (isDisposed ()) {
                gc.dispose ();
                return false;
            }
        }
    }
    gc.dispose ();
    if (firstColumn.width () < newWidth) {
        NSOutlineView outlineView = cast(NSOutlineView)view;
        NSTableViewColumnAutoresizingStyle  oldResize = outlineView.columnAutoresizingStyle ();
        outlineView.setColumnAutoresizingStyle (OS.NSTableViewNoColumnAutoresizing);
        firstColumn.setWidth (newWidth);
        outlineView.setColumnAutoresizingStyle (oldResize);
        return true;
    }
    return false;
}

/**
 * Sets the receiver's selection to the given item.
 * The current selection is cleared before the new item is selected.
 * <p>
 * If the item is not in the receiver, then it is ignored.
 * </p>
 *
 * @param item the item to select
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.2
 */
public void setSelection (TreeItem item) {
    checkWidget ();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    setSelection ([item]);
}

/**
 * Sets the receiver's selection to be the given array of items.
 * The current selection is cleared before the new items are selected.
 * <p>
 * Items that are not in the receiver are ignored.
 * If the receiver is single-select and multiple items are specified,
 * then all items are ignored.
 * </p>
 *
 * @param items the array of items
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the array of items is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if one of the items has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see Tree#deselectAll()
 */
public void setSelection (TreeItem [] items) {
    checkWidget ();
    if (items is null) error (DWT.ERROR_NULL_ARGUMENT);
    deselectAll ();
    int length = items.length;
    if (length is 0 || ((style & DWT.SINGLE) !is 0 && length > 1)) return;
    NSOutlineView outlineView = cast(NSOutlineView) view;
    NSMutableIndexSet rows = cast(NSMutableIndexSet) (new NSMutableIndexSet ()).alloc ().init ();
    rows.autorelease ();
    for (int i=0; i<length; i++) {
        if (items [i] !is null) {
            if (items [i].isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
            TreeItem item = items [i];
            showItem (items [i], false);
            rows.addIndex (outlineView.rowForItem (item.handle));
        }
    }
    ignoreSelect = true;
    outlineView.selectRowIndexes (rows, false);
    ignoreSelect = false;
    if (items.length > 0) showItem(items[0], true);
}

/**
 * Sets the column used by the sort indicator for the receiver. A null
 * value will clear the sort indicator.  The current sort column is cleared 
 * before the new column is set.
 *
 * @param column the column used by the sort indicator or <code>null</code>
 * 
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_ARGUMENT - if the column is disposed</li> 
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.2
 */
public void setSortColumn (TreeColumn column) {
    checkWidget ();
    if (column !is null && column.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    if (column is sortColumn) return;
    TreeColumn oldSortColumn = sortColumn;
    sortColumn = column;
    if (sortDirection is DWT.NONE) return;
    NSTableHeaderView headerView = (cast(NSOutlineView)view).headerView ();
    if (headerView is null) return;
    if (oldSortColumn !is null) {
        NSInteger index = (cast(NSOutlineView)view).columnWithIdentifier (oldSortColumn.nsColumn);
        NSRect rect = headerView.headerRectOfColumn (index);
        headerView.setNeedsDisplayInRect (rect);
    }
    if (sortColumn !is null) {
        NSInteger index = (cast(NSOutlineView)view).columnWithIdentifier (sortColumn.nsColumn);
        NSRect rect = headerView.headerRectOfColumn (index);
        headerView.setNeedsDisplayInRect (rect);
    }
}

/**
 * Sets the direction of the sort indicator for the receiver. The value 
 * can be one of <code>UP</code>, <code>DOWN</code> or <code>NONE</code>.
 *
 * @param direction the direction of the sort indicator 
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 * 
 * @since 3.2
 */
public void setSortDirection  (int direction) {
    checkWidget ();
    if (direction !is DWT.UP && direction !is DWT.DOWN && direction !is DWT.NONE) return;
    if (direction is sortDirection) return;
    sortDirection = direction;
    if (sortColumn is null) return;
    NSTableHeaderView headerView = (cast(NSOutlineView)view).headerView ();
    if (headerView is null) return;
    NSInteger  index = (cast(NSOutlineView)view).columnWithIdentifier (sortColumn.nsColumn);
    NSRect rect = headerView.headerRectOfColumn (index);
    headerView.setNeedsDisplayInRect (rect);
}

/**
 * Sets the item which is currently at the top of the receiver.
 * This item can change when items are expanded, collapsed, scrolled
 * or new items are added or removed.
 *
 * @param item the item to be shown
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see Tree#getTopItem()
 * 
 * @since 2.1
 */
public void setTopItem (TreeItem item) {
    checkWidget();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    showItem (item, false);
    NSOutlineView outlineView = cast(NSOutlineView) view;
    //FIXME
    (cast(NSOutlineView) view).scrollRowToVisible (outlineView.rowForItem (item.handle));
}

/**
 * Shows the column.  If the column is already showing in the receiver,
 * this method simply returns.  Otherwise, the columns are scrolled until
 * the column is visible.
 *
 * @param column the column to be shown
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @since 3.1
 */
public void showColumn (TreeColumn column) {
    checkWidget ();
    if (column is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (column.isDisposed()) error (DWT.ERROR_INVALID_ARGUMENT);
    if (column.parent !is this) return;
    if (columnCount <= 1) return;
    int index = cast(int)/*64*/(cast(NSOutlineView)view).columnWithIdentifier (column.nsColumn);
    if (!(0 <= index && index < columnCount + ((style & DWT.CHECK) !is 0 ? 1 : 0))) return;
    (cast(NSOutlineView)view).scrollColumnToVisible (index);
}

/**
 * Shows the item.  If the item is already showing in the receiver,
 * this method simply returns.  Otherwise, the items are scrolled
 * and expanded until the item is visible.
 *
 * @param item the item to be shown
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the item is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the item has been disposed</li>
 * </ul>
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see Tree#showSelection()
 */
public void showItem (TreeItem item) {
    checkWidget ();
    if (item is null) error (DWT.ERROR_NULL_ARGUMENT);
    if (item.isDisposed ()) error (DWT.ERROR_INVALID_ARGUMENT);
    showItem (item, true);
}

void showItem (TreeItem item, bool scroll) {
    TreeItem parentItem = item.parentItem;
    if (parentItem !is null && !parentItem.expanded) {
        showItem (parentItem, false);
        parentItem.setExpanded (true);
    }
    if (scroll) {
        NSOutlineView outlineView = cast(NSOutlineView) view;
        outlineView.scrollRowToVisible (outlineView.rowForItem (item.handle));
    }
}

/**
 * Shows the selection.  If the selection is already showing in the receiver,
 * this method simply returns.  Otherwise, the items are scrolled until
 * the selection is visible.
 *
 * @exception DWTException <ul>
 *    <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed</li>
 *    <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver</li>
 * </ul>
 *
 * @see Tree#showItem(TreeItem)
 */
public void showSelection () {
    checkWidget ();
    //checkItems (false);
    //TODO - optimize
    TreeItem [] selection = getSelection ();
    if (selection.length > 0) showItem (selection [0], true);
}

}