// This may look like C code, but it's really -*- C++ -*-
/*
 * Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
 *
 * See the LICENSE file for terms of use.
 */
#ifndef WTREE_VIEW_H_
#define WTREE_VIEW_H_

#include <set>
#include <vector>

#include <Wt/WCompositeWidget>
#include <Wt/WJavaScript>
#include <Wt/WModelIndex>
#include <Wt/WSignalMapper>

namespace Wt {

class WAbstractItemDelegate;
class WAbstractItemModel;
class WApplication;
class WCheckBox;
class WCssRule;
class WCssTemplateRule;
class WImage;
class WItemSelectionModel;
class WText;
class WTreeViewNode;

/*! \class WTreeView Wt/WTreeView Wt/WTreeView
 *  \brief A view class that displays a model as a tree or tree table.
 *
 * The view displays data from a WAbstractItemModel in a tree or tree
 * table. It provides incremental rendering, allowing the display of
 * data models of any size efficiently, without excessive use of
 * client- or serverside resources. Data of all predefined roles is
 * displayed (see also ItemDataRole), including text, icons,
 * checkboxes, and tooltips .
 *
 * By default, all but the first columns are given a width of 150px,
 * and the first column takes the remaining size. <b>Note that this
 * may have as consequence that the first column's size is reduced to
 * 0.</b> Column widths of all columns, including the first column,
 * can be set through the API method setColumnWidth(), and also by the
 * user using handles provided in the header.
 *
 * Optionally, the treeview may be configured so that the first column
 * is always visible while scrolling through the other columns, which
 * may be convenient if you wish to display a model with many
 * columns. Use setColumn1Fixed() to enable this behaviour.
 *
 * If the model supports sorting (WAbstractItemModel::sort()), such as
 * the WStandardItemModel, then you can enable sorting buttons in the
 * header, using setSortingEnabled().
 *
 * You can allow selection on row or item level (using
 * setSelectionBehavior()), and selection of single or multiple items
 * (using setSelectionMode()), and listen for changes in the selection
 * using the selectionChanged() signal.
 *
 * You may enable drag & drop support for this view, whith awareness
 * of the items in the model. When enabling dragging (see
 * setDragEnabled()), the current selection may be dragged, but only
 * when all items in the selection indicate support for dragging
 * (controlled by the \link Wt::ItemIsDragEnabled
 * ItemIsDragEnabled\endlink flag), and if the model indicates a
 * mime-type (controlled by WAbstractItemModel::mimeType()). Likewise,
 * by enabling support for dropping (see setDropsEnabled()), the
 * treeview may receive a drop event on a particular item, at least if
 * the item indicates support for drops (controlled by the \link
 * Wt::ItemIsDropEnabled ItemIsDropEnabled\endlink flag).
 *
 * You may also react to mouse click events on any item, by connecting
 * to one of the clicked() or doubleClicked() signals.
 *
 * \if cpp
 * Usage example:
 * \code
 * // WTreeView will display the data of a model
 * Wt::WAbstractItemModel *model = ...
 *
 * // Create the WTreeView
 * Wt::WTreeView *gitView = new Wt::WTreeView();
 * gitView->resize(300, Wt::WLength::Auto);
 * gitView->setSortingEnabled(false);
 * gitView->setModel(model);
 * gitView->setSelectionMode(SingleSelection);
 * \endcode
 * \endif
 *
 * \ingroup modelview
 */
class WT_API WTreeView : public WCompositeWidget
{
public:
  /*! \brief Create a new tree view.
   */
  WTreeView(WContainerWidget *parent = 0);

  /*! \brief Destructor.
   */
  ~WTreeView();

  /*! \brief Sets the model.
   *
   * The view will render the data in the given <i>model</i>. Changes
   * to the model are reflected in the view.
   *
   * When resetting a model, all nodes are initially collapsed, the
   * selection is cleared, and the root index corresponds to the
   * model's top level node (see setRootIndex()).
   *
   * The initial model is 0.
   *
   * Ownership of the model is not transferred (and thus the
   * previously set model is not deleted).
   *
   * \sa setRootIndex()
   */
  void setModel(WAbstractItemModel *model);

  /*! \brief Returns the model.
   *
   * \sa setModel()
   */
  WAbstractItemModel *model() const { return model_; }

  /*! \brief Sets the root index.
   *
   * The root index is the model index that is considered the root
   * node. This node itself is not rendered, but all its children are
   * the top level nodes.
   *
   * The default value is WModelIndex(), corresponding to the
   * invisible root.
   *
   * \sa setModel()
   */
  void setRootIndex(const WModelIndex& rootIndex);

  /*! \brief Returns the root index.
   *
   * \sa setRootIndex()
   */
  const WModelIndex& rootIndex() const { return rootIndex_; }

  /*! \brief Sets the header height.
   *
   * Use this method to change the header height. You may also enable
   * the use of multi-line headers. By default, the header text is a 
   * single line, that is centered vertically.
   *
   * The default value is 20 pixels.
   */
  void setHeaderHeight(const WLength& height, bool multiLine = false);

  /*! \brief Returns the header height.
   *
   * \sa setHeaderHeight()
   */
  const WLength& headerHeight() const { return headerHeight_; }

  /*! \brief Sets the row height.
   *
   * The view assumes that all rows are of the same height. Use this
   * method to set the height.
   *
   * The default value is 20 pixels.
   *
   * \note The height must be specified in WLength::Pixel units.
   *
   * \sa setColumnWidth()
   */
  void setRowHeight(const WLength& rowHeight);

  /*! \brief Returns the row height.
   */
  const WLength& rowHeight() const { return rowHeight_; }

#ifndef WT_DEPRECATED_3_0_0
  /*! \brief Sets the column format string (<b>deprecated</b>).
   *
   * \if cpp
   * The DisplayRole data for that column is converted to a string using
   * asString(), with the given format.
   * \elseif java
   * The DisplayRole data for that column is converted to a string using
   * {javadoclink StringUtils#asString(Object)}, with the given format.
   * \endif
   *
   * The default value is "".
   *
   * \deprecated use itemDelegateForColumn() to customize the formatting. This
   *             method will create a new WItemDelegate for the
   *             column, and configure its format.
   */
  void setColumnFormat(int column, const WT_USTRING& format);

  /*! \brief Returns the column format string (<b>deprecated</b>).
   *
   * \sa setColumnFormat()
   *
   * \deprecated use itemDelegateForColumn() to customize the formatting. This
   *             method will try to cast the itemDelegateForColumn() to
   *             a WItemDelegate and return the format.
   */
  WT_USTRING columnFormat(int column) const;
#endif // WT_DEPRECATED_3_0_0

  /*! \brief Sets the column width.
   *
   * For a model with \link WAbstractItemModel::columnCount()
   * columnCount()\endlink == <i>N</i>, the initial width of columns
   * 1..<i>N</i> is set to 150 pixels, and column 0 will take all
   * remaining space.
   *
   * \note The actual space occupied by each column is the column width
   *       augmented by 7 pixels for internal padding and a border.
   *
   * \sa setRowHeight()
   */
  void setColumnWidth(int column, const WLength& width);
 
  /*! \brief Returns the column width.
   *
   * \sa setColumnWidth()
   */
  WLength columnWidth(int column) const;

  /*! \brief Sets the content alignment for a column.
   *
   * The default value is \link Wt::AlignLeft AlignLeft\endlink.
   *
   * \note For column 0, \link Wt::AlignCenter AlignCenter\endlink is
   * currently not supported.
   *
   * \sa setHeaderAlignment()
   */
  void setColumnAlignment(int column, AlignmentFlag alignment);

  /*! \brief Sets the header alignment for a column.
   *
   * The default value is \link Wt::AlignLeft AlignLeft\endlink.
   *
   * \sa setColumnAlignment()
   */
  void setHeaderAlignment(int column, AlignmentFlag alignment);

  /*! \brief Returns the content alignment for a column.
   *
   * \sa setColumnAlignment()
   */
  AlignmentFlag columnAlignment(int column) const;

  /*! \brief Returns the header alignment for a column.
   *
   * \sa setHeaderAlignment()
   */
  AlignmentFlag headerAlignment(int column) const;

  /*! \brief Setss the column border color
   *
   * \if cpp
   * The default border color is \link Wt::white white\endlink.
   * \elseif java
   * The default border color is WColor.white. 
   * \endif 
   */
  void setColumnBorder(const WColor& color);

  /*! \brief Setss the base urls for icons.
   *
   * This widget relies on several icons that are distributed together
   * with %Wt for drawing icons, lines, and backgrounds.
   *
   * The default location for the image pack is <i>resourcesURL</i>.
   *
   * The default value for <i>resourcesURL</i> is "resources/". This
   * value may be overridden with a URL that points to a folder where
   * these files are located, by configuring the <i>resourcesURL</i>
   * property in your %Wt configuration file.
   */
  void setImagePack(const std::string& uri) { }

  /*! \brief Returns the base url for icons.
   *
   * \sa setImagePack()
   */
  std::string imagePack() const { return imagePack_; }

  /*! \brief Expand or collapse a node.
   *
   * \sa expand(), collapse()
   */
  void setExpanded(const WModelIndex&, bool expanded);

  /*! \brief Returns whether a node is expanded.
   *
   * \sa setExpanded()
   */
  bool isExpanded(const WModelIndex& index) const;

  /*! \brief Collapse a node.
   *
   * \sa setExpanded(), expand()
   */
  void collapse(const WModelIndex& index);

  /*! \brief Expand a node.
   *
   * \sa setExpanded(), collapse()
   */
  void expand(const WModelIndex& index);

  /*! \brief Expand all nodes to a depth.
   *
   * Expands all nodes to the given <i>depth</i>. A depth of 1 corresponds
   * to the top level nodes.
   *
   * \sa expand()
   */
  void expandToDepth(int depth);

  /*! \brief Sets if alternating row colors are to be used.
   *
   * Configure whether rows get an alternating background color. These
   * are implemented by using a background image on the root node, like:
   * \image html stripe-30px.gif "Sample image use for alternating row colors"
   *
   * The image that is used is
   * imagePack() + "/stripes/stripe-<i>n</i>px.gif", where <i>n</i> is the
   * row height. In the resource folder are images pregenerated for
   * one color and row sizes from 10 to 30px.
   *
   * The default value is false.
   *
   * \sa setImagePack()
   */
  void setAlternatingRowColors(bool enable);

  /*! \brief Returns whether alternating row colors are used.
   *
   * \sa setAlternatingRowColors()
   */
  bool alternatingRowColors() const { return alternatingRowColors_; }

  /*! \brief Sets whether toplevel items are decorated.
   *
   * By default, top level nodes have expand/collapse and other lines
   * to display their linkage and offspring, like any node.
   *
   * By setting <i>show</i> to false, you can hide these decorations
   * for root nodes, and in this way mimic a plain list.
   *
   * \if cpp
   * \sa Ext::TableView
   * \endif 
   */
  void setRootIsDecorated(bool show);

  /*! \brief Returns whether toplevel items are decorated.
   *
   * \sa setRootIsDecorated()
   */
  bool rootIsDecorated() const { return rootIsDecorated_; }

  /*! \brief Sort the data according to a column.
   *
   * Sorts the data according to data in column <i>column</i> and sort
   * order <i>order</i>.
   *
   * \sa WAbstractItemModel::sort()
   */
  void sortByColumn(int column, SortOrder order);

  /*! \brief Enable sorting.
   *
   * Enable or disable sorting by the user on all columns.
   *
   * Sorting is enabled by default.
   *
   * \sa WAbstractItemModel::sort()
   */
  void setSortingEnabled(bool enabled);

  /*! \brief Enable sorting.
   *
   * Enable or disable sorting by the user for a specific column.
   *
   * Sorting is enabled by default.
   *
   * \sa WAbstractItemModel::sort()
   */
  void setSortingEnabled(int column, bool enabled);

  /*! \brief Returns whether sorting is enabled.
   *
   * \sa setSortingEnabled()
   */
  bool isSortingEnabled() const { return sorting_; }

  /*! \brief Enable interactive column resizing
   *
   * Enable or disable column resize handles for interactive resizing of
   * the columns.
   *
   * \sa setColumnResizeEnabled()
   */
  void setColumnResizeEnabled(bool enabled);

  /*! \brief Returns whether column resizing is enabled.
   *
   * \sa setColumnResizeEnabled()
   */
  bool isColumnResizeEnabled() const { return columnResize_; }

  /*! \brief Change the selection behaviour.
   *
   * The selection behavior indicates whether whole rows or individual
   * items can be selected. It is a property of the selectionModel().
   *
   * By default, selection operates on rows (\link Wt::SelectRows
   * SelectRows\endlink), in which case model indexes will always be
   * in the first column (column 0).
   *
   * Alternatively, you can allow selection for individual items
   * (\link Wt::SelectItems SelectItems\endlink).
   *
   * \sa WItemSelectionModel::setSelectionBehavior(), setSelectionMode()
   */
  void setSelectionBehavior(SelectionBehavior behavior);

  /*! \brief Returns the selection behaviour.
   *
   * \sa setSelectionBehavior()
   */
  SelectionBehavior selectionBehavior() const;

  /*! \brief Sets the selection mode.
   *
   * By default selection is disabled (\link Wt::NoSelection
   * NoSelection \endlink).
   *
   * \sa setSelectionBehavior()
   */
  void setSelectionMode(SelectionMode mode);

  /*! \brief Returns the selection mode.
   *
   * \sa setSelectionMode()
   */
  SelectionMode selectionMode() const { return selectionMode_; }

  /*! \brief Returns the selection model.
   *
   * The selection model keeps track of the currently selected items.
   */
  WItemSelectionModel *selectionModel() const { return selectionModel_; }

  /*! \brief Sets the selected items
   *
   * Replaces the current selection with <i>indexes</i>.
   *
   * \sa select(), selectionModel()
   */
  void setSelectedIndexes(const WModelIndexSet& indexes);

  /*! \brief Select a single item.
   *
   * \sa setSelectedIndexes(), selectionModel()
   */
  void select(const WModelIndex& index, SelectionFlag option = Select);

  /*! \brief Returns wheter an item is selected.
   *
   * This is a convenience method for:
   * \code
   * selectionModel()->isSelected(index)
   * \endcode
   *
   * \sa selectedIndexes(), select(), selectionModel()
   */
  bool isSelected(const WModelIndex& index) const;

  /*! \brief Returns the set of selected items.
   *
   * The model indexes are returned as a set, topologically ordered (in
   * the order they appear in the view).
   *
   * This is a convenience method for:
   * \code
   * selectionModel()->selectedIndexes()
   * \endcode
   *
   * \sa setSelectedIndexes()
   */
  WModelIndexSet selectedIndexes() const;

  /*! \brief Enable the selection to be dragged (drag & drop).
   *
   * To enable dragging of the selection, you first need to enable
   * selection using setSelectionMode().
   *
   * Whether an individual item may be dragged is controlled by the
   * item's \link Wt::ItemIsDragEnabled ItemIsDragEnabled \endlink
   * flag. The selection can be dragged only if all items currently
   * selected can be dragged.
   *
   * \sa setDropsEnabled() 
   */
  void setDragEnabled(bool enable);

  /*! \brief Enable drop operations (drag & drop).
   *
   * When drop is enabled, the tree view will indicate that something
   * may be dropped when the mime-type of the dragged object is
   * compatible with one of the model's accepted drop mime-types (see
   * WAbstractItemModel::acceptDropMimeTypes()) or this widget's
   * accepted drop mime-types (see WWidget::acceptDrops()), and the
   * target item has drop enabled (which is controlled by the item's
   * \link Wt::ItemIsDropEnabled ItemIsDropEnabled \endlink flag).
   *
   * Drop events must be handled in dropEvent().
   *
   * \sa setDragEnabled(), dropEvent()
   */
  void setDropsEnabled(bool enable);

  /*! \brief Configure whether horizontal scrolling includes the first column.
   *
   * To display a model with many columns, this option allows you to
   * keep the first column fixed while scrolling through the other
   * columns of the model.
   *
   * The default value is false.
   *
   * \note Currently, you must set this option before any other manipulation
   *       of a newly created treeview, and only <i>enable</i> = <i>true</i>
   *       is supported.
   */
  void setColumn1Fixed(bool enable);

  virtual void resize(const WLength& width, const WLength& height);
  virtual void load();

  /*! \brief %Signal emitted when a node is collapsed.
   *
   * \sa setExpanded(), expanded()
   */
  Signal<WModelIndex>& collapsed() { return collapsed_; }

  /*! \brief %Signal emitted when a node is expanded.
   *
   * \sa setExpanded(), collapsed()
   */
  Signal<WModelIndex>& expanded() { return expanded_; }

  /*! \brief %Signal emitted when an item is clicked.
   *
   * \sa doubleClicked()
   */
  Signal<WModelIndex, WMouseEvent>& clicked() { return clicked_; }

  /*! \brief %Signal emitted when an item is double clicked.
   *
   * \sa doubleClicked()
   */
  Signal<WModelIndex, WMouseEvent>& doubleClicked() { return doubleClicked_; }

  /*! \brief %Signal emitted when an item is double clicked.
   *
   * \sa doubleClicked()
   */
  Signal<WModelIndex, WMouseEvent>& mouseWentDown() { return mouseWentDown_; }

  /*! \brief %Signal emitted when the selection is changed.
   *
   * \sa select(), setSelectionMode(), setSelectionBehavior()
   */
  Signal<void>& selectionChanged() { return selectionChanged_; }

  void openPersistentEditor(const WModelIndex& index);
  void closePersistentEditor(const WModelIndex& index);

  /*! \brief Sets the default item delegate.
   *
   * The previous delegate is removed but not deleted.
   *
   * The default item delegate is a WItemDelegate.
   */
  void setItemDelegate(WAbstractItemDelegate *delegate);

  /*! \brief Returns the default item delegate.
   *
   * \sa setItemDelegate()
   */
  WAbstractItemDelegate *itemDelegate() const { return itemDelegate_; }

  /*! \brief Sets the delegate for a column.
   *
   * The previous delegate is removed but not deleted.
   *
   * \sa setItemDelegate()
   */
  void setItemDelegateForColumn(int column, WAbstractItemDelegate *delegate);

  /*! \brief Returns the delegate for a column.
   *
   * \sa setItemDelegateForColumn()
   */
  WAbstractItemDelegate *itemDelegateForColumn(int column) const;

  /*! \brief Returns the delegate for rendering an item.
   *
   * \sa setItemDelegateForColumn(), setItemDelegate()
   */
  WAbstractItemDelegate *itemDelegate(const WModelIndex& index) const;

  virtual void refresh();

protected:
  /*! \brief Handle a drop event (drag & drop).
   *
   * The <i>event</i> object contains details about the drop
   * operation, identifying the source (which provides the data) and
   * the mime-type of the data. The drop was received on the
   * <i>target</i> item.
   *
   * The drop event can be handled either by the view itself, or by
   * the model. The default implementation checks if the mime-type is
   * accepted by the model, and if so passes the drop event to the
   * model. If the source is the view's own selection model, then the
   * drop event will be handled as a \link Wt::MoveAction
   * MoveAction\endlink, otherwise the drop event will be handled as a
   * \link Wt::CopyAction CopyAction\endlink.
   *
   * \sa WAbstractItemModel::dropEvent()
   */
  virtual void dropEvent(const WDropEvent& event, const WModelIndex& target);

  /*! \brief Create an extra widget in the header.
   *
   * You may reimplement this method to provide an extra widget to be placed
   * below the header label. The extra widget will be visible only if
   * a multi-line header is configured using setHeaderHeight().
   *
   * The widget is created only once, but this method may be called repeatedly
   * for a column for which prior calls returned 0 (i.e. each time the header
   * is rerendered).
   *
   * The default implementation returns 0.
   *
   * \sa setHeaderHeight(), extraHeaderWidget()
   */
  virtual WWidget *createExtraHeaderWidget(int column);

  virtual void render();

  /*! \brief Returns the extra header widget.
   *
   * Returns the widget previously created using createExtraHeaderWidget()
   *
   * \sa createExtraHeaderWidget()
   */
  WWidget *extraHeaderWidget(int column);

  virtual void enableAjax();

private:
  struct ColumnInfo {
    WCssTemplateRule *styleRule;
    int id;
    SortOrder sortOrder;
    AlignmentFlag alignment;
    AlignmentFlag headerAlignment;
    WLength width;
    WWidget *extraHeaderWidget;
    bool sorting;
    WAbstractItemDelegate *itemDelegate_;

    std::string styleClass() const;

    ColumnInfo(const WTreeView *view, WApplication *app, int id, int column);
  };

  typedef std::map<WModelIndex, WTreeViewNode *> NodeMap;

  WAbstractItemModel  *model_;
  WAbstractItemDelegate *itemDelegate_;
  WItemSelectionModel *selectionModel_;
  WModelIndex          rootIndex_;
  WLength              rowHeight_, headerHeight_;
  WModelIndexSet       expandedSet_;
  NodeMap              renderedNodes_;
  WTreeViewNode       *rootNode_;
  std::string          imagePack_;
  WCssTemplateRule    *rowHeightRule_, *headerHeightRule_,
    *rowWidthRule_, *rowContentsWidthRule_, *c0WidthRule_;
  WCssRule            *borderColorRule_;
  bool                 alternatingRowColors_;
  bool                 rootIsDecorated_;
  SelectionMode        selectionMode_;
  bool                 sorting_, columnResize_;
  bool                 multiLineHeader_;
  bool                 column1Fixed_;

  std::vector<void *> expandedRaw_, selectionRaw_;
  void *rawRootIndex_;

  mutable std::vector<ColumnInfo> columns_;
  mutable int nextColumnId_;

  Signal<WModelIndex> collapsed_;
  Signal<WModelIndex> expanded_;
  Signal<WModelIndex, WMouseEvent> clicked_;
  Signal<WModelIndex, WMouseEvent> doubleClicked_;
  Signal<WModelIndex, WMouseEvent> mouseWentDown_;
  Signal<void> selectionChanged_;

  WSignalMapper<int>         *clickedForSortMapper_;
  WSignalMapper<WModelIndex> *clickedMapper_;

  enum RenderState {
    RenderOk = 0,
    NeedAdjustViewPort = 1,
    NeedRerenderTree = 2,
    NeedRerenderHeader = 3,
    NeedRerender = 4
  };

  RenderState renderState_;

  // in rows, as indicated by the current position of the viewport:
  int viewportTop_;
  int viewportHeight_;

  // the firstRenderedRow may differ from viewportTop_, because the user
  // adjusted the view port slightly, but not enough to trigger a correction
  //
  // the validRowCount may differ from viewportHeight_ as a result of
  // expanding or collapsing nodes, or inserting and deleting rows.
  // it takes into account that an expanded node may be incomplete, and
  // thus everything beyond is irrelevant
  int firstRenderedRow_;
  int validRowCount_;

  // rendered nodes in memory (including those collapsed and not included in
  // actualRenderedRowCount_), but excluding nodes that are simply there since
  // some of its children are rendered
  int nodeLoad_;

  int currentSortColumn_;

  WContainerWidget *impl_;
  WContainerWidget *headers_, *headerContainer_;
  WContainerWidget *contents_, *contentsContainer_;

  int firstRemovedRow_, removedHeight_;

  std::vector<boost::signals::connection> modelConnections_;
  JSlot resizeHandleMDownJS_, resizeHandleMMovedJS_, resizeHandleMUpJS_,
    tieContentsHeaderScrollJS_, tieRowsScrollJS_, itemClickedJS_,
    itemDoubleClickedJS_, itemMouseDownJS_;

  JSignal<std::string, int, std::string, std::string,
          std::string, WMouseEvent> itemEvent_;

  bool     dragEnabled_, dropsEnabled_;
  WWidget *dragWidget_;

  void initLayoutJavaScript();
  void rerenderHeader();
  void rerenderTree();
  void scheduleRerender(RenderState what);

  void modelColumnsInserted(const WModelIndex& parent, int start, int end);
  void modelColumnsAboutToBeRemoved(const WModelIndex& parent,
				    int start, int end);
  void modelColumnsRemoved(const WModelIndex& parent, int start, int end);
  void modelRowsInserted(const WModelIndex& parent, int start, int end);
  void modelRowsAboutToBeRemoved(const WModelIndex& parent, int start, int end);
  void modelRowsRemoved(const WModelIndex& parent, int start, int end);
  void modelDataChanged(const WModelIndex& topLeft,
			const WModelIndex& bottomRight);
  void modelHeaderDataChanged(Orientation orientation, int start, int end);
  void modelLayoutAboutToBeChanged();
  void modelLayoutChanged();
  void modelReset();

  void onViewportChange(WScrollEvent event);
  void toggleSortColumn(int columnid);
  void onItemEvent(std::string nodeId, int columnId, std::string type,
		   std::string extra1, std::string extra2, WMouseEvent event);
  void setRootNodeStyle();
  void setCollapsed(const WModelIndex& index);

  int calcOptimalFirstRenderedRow() const;
  int calcOptimalRenderedRowCount() const;

  void shiftModelIndexes(const WModelIndex& parent, int start, int count);
  static int shiftModelIndexes(const WModelIndex& parent, int start, int count,
			       WAbstractItemModel *model, WModelIndexSet& set);

  void addRenderedNode(WTreeViewNode *node);
  void removeRenderedNode(WTreeViewNode *node);

  void adjustToViewport(WTreeViewNode *changed = 0);

  int pruneNodes(WTreeViewNode *node, int theNodeRow);
  int adjustRenderedNode(WTreeViewNode *node, int theNodeRow);

  WWidget *widgetForIndex(const WModelIndex& index) const;
  int subTreeHeight(const WModelIndex& index,
		    int lowerBound = 0,
		    int upperBound = std::numeric_limits<int>::max());
  int renderedRow(const WModelIndex& index,
		  WWidget *w,
		  int lowerBound = 0,
		  int upperBound = std::numeric_limits<int>::max());
  int getIndexRow(const WModelIndex& index,
		  const WModelIndex& ancestor,
		  int lowerBound = 0,
		  int upperBound = std::numeric_limits<int>::max());

  int columnCount() const;
  int columnById(int columnid) const;
  std::string columnStyleClass(int column) const;

  int renderLowerBound() const;
  int renderUpperBound() const;

  void renderedRowsChanged(int row, int count);
  void convertToRaw(WModelIndexSet& set, std::vector<void *>& result);

  WContainerWidget *headerRow();
  WWidget *createHeaderWidget(WApplication *app, int column);
  WWidget *headerWidget(int column);
  WText   *headerTextWidget(int column);
  WImage  *headerSortIconWidget(int column);

  void selectionHandleClick(const WModelIndex& index,
			    WFlags<KeyboardModifier> modifiers);
  void handleClick(const WModelIndex& index);
  bool internalSelect(const WModelIndex& index, SelectionFlag option);
  void selectRange(const WModelIndex& first, const WModelIndex& last);
  void extendSelection(const WModelIndex& index);
  void clearSelection();

  void checkDragSelection();
  void configureModelDragDrop();
  void expandChildrenToDepth(const WModelIndex& index, int depth);

  ColumnInfo& columnInfo(int column) const;

  friend class WTreeViewNode;
};

}

#endif // WTREE_VIEW_H_
