/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

/****************************************************************************
**
** Copyright (C) 2009-2023 Arm Limited (or its affiliates).
** Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
**
****************************************************************************/

#include "mdatable.h"

#include <QApplication>
#include <QClipboard>
#include <QPainter>
#include <QPaintEvent>
#include <QScrollBar>
#include <QStyle>
#include <QStyleOption>
#include <QTimer>

#include "sectionmap.h"

using namespace Qt;

struct MDATableHeaderBounds
{
    MDATableHeaderBounds() { min = 0; max = 0; span = 0; }
    QString name;
    long long min, max, span;
};

class MDATableHeader : public QWidget
{
    friend class MDATable;
    Q_OBJECT
    Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation)
    Q_PROPERTY(long long count READ count WRITE setCount)
    Q_PROPERTY(int offset READ offset WRITE setOffset)

public:
    MDATableHeader(MDATable *t, QWidget* parent=0, const char* name=0);
    MDATableHeader(long long, MDATable *t, QWidget* parent=0, const char* name=0);

    void setNumLines(int n);
    int numLines() const;
    void setLineNameAndBounds(int i, const QString& name, long long min, long long max);

    void setOrientation(Qt::Orientation);
    Orientation orientation() const;

    bool isSectionHidden(long long s) const;
    bool isSectionHidden(long long s, long long e) const;
    void hideSection(long long s);
    void showSection(long long s);
    void hideSections(long long s, long long e);
    void showSections(long long s, long long e);

    bool isSectionValid(long long s);
    bool isSectionValid(long long s, long long e);

    void resizeSections(int s);
    int sectionSize() const;
    int sectionPos(long long section) const;
    long long sectionAt(int section) const;
    int headerWidth() const;
    long long count() const;
    void setCount(long long c);

    int offset() const;

    void clear();

    QSize sizeHint() const override;

public slots:
    void setOffset(int pos);

signals:
    void sectionSizeChanged();
    void clicked(int section);
    void pressed(int section);
    void released(int section);
    void fixedExtentChanged(int newSize);

protected:
    void paintEvent(QPaintEvent *e) override;
    void paintSection(QPainter *p, long long index1, long long index2, const QRect& fr, QString label);
    void paintSectionLabel(QPainter *p, const QRect& fr, QString label);
    void paintName(QPainter *p, const QRect& fr, QString name);
    void resizeEvent(QResizeEvent *e) override;

    QRect sRect(int line, long long index1, long long index2);
    QRect sRect(long long index);
    QRect nameRect(int line);

private:
    void sectionLabelChanged(int section);
    void init(long long i);
    void updateSpans();

private:
    MDATable *table;
    int sectionSz;

    QVector<MDATableHeaderBounds> bounds;
    bool initialised;

    int fixedExtent; // we abuse the heights as widths for vertical layout
    int nameWidth;
    int nameHeight;

    long long sectionCount;

    int offs;
    Orientation orient;

    SectionMap map;
};

#ifdef _WS_QWS_
# define NO_LINE_WIDGET
#endif

struct MDATablePrivate
{
    MDATablePrivate() : inMenuMode(false), redirectMouseEvent(false)
    {
    }
    uint inMenuMode : 1;
    uint redirectMouseEvent : 1;
    QTimer *geomTimer;
    long long lastVisRow;
    long long  lastVisCol;
};

/*!
    \class MDATableSelection
    \brief The MDATableSelection class provides access to a selected area in a
    MDATable.

    \compat

    The selection is a rectangular set of cells in a MDATable. One of
    the rectangle's cells is called the anchor cell; this is the cell
    that was selected first. The init() function sets the anchor and
    the selection rectangle to exactly this cell; the expandTo()
    function expands the selection rectangle to include additional
    cells.

    There are various access functions to find out about the area:
    anchorRow() and anchorCol() return the anchor's position;
    leftCol(), rightCol(), topRow() and bottomRow() return the
    rectangle's four edges. All four are part of the selection.

    A newly created MDATableSelection is inactive -- isActive() returns
    false. You must use init() and expandTo() to activate it.

    \sa MDATable MDATable::addSelection() MDATable::selection()
    MDATable::selectCells() MDATable::selectRow() MDATable::selectColumn()
*/

/*!
    Creates an inactive selection. Use init() and expandTo() to
    activate it.
*/

MDATableSelection::MDATableSelection()
    : active(false), inited(false), tRow(-1), lCol(-1),
      bRow(-1), rCol(-1), aRow(-1), aCol(-1)
{
}

/*!
    Creates an active selection, starting at \a start_row and \a
    start_col, ending at \a end_row and \a end_col.
*/

MDATableSelection::MDATableSelection(long long start_row, long long start_col, long long end_row, long long end_col)
    : active(false), inited(false), tRow(-1), lCol(-1),
      bRow(-1), rCol(-1), aRow(-1), aCol(-1)
{
    init(start_row, start_col);
    expandTo(end_row, end_col);
}

/*!
    Sets the selection anchor to cell \a row, \a col and the selection
    to only contain this cell. The selection is not active until
    expandTo() is called.

    To extend the selection to include additional cells, call
    expandTo().

    \sa isActive()
*/

void MDATableSelection::init(long long row, long long col)
{
    aCol = lCol = rCol = col;
    aRow = tRow = bRow = row;
    active = false;
    inited = true;
}

/*!
    Expands the selection to include cell \a row, \a col. The new
    selection rectangle is the bounding rectangle of \a row, \a col
    and the previous selection rectangle. After calling this function
    the selection is active.

    If you haven't called init(), this function does nothing.

    \sa init() isActive()
*/

void MDATableSelection::expandTo(long long row, long long col)
{
    if (!inited)
        return;
    active = true;

    if (row < aRow) {
        tRow = row;
        bRow = aRow;
    } else {
        tRow = aRow;
        bRow = row;
    }

    if (col < aCol) {
        lCol = col;
        rCol = aCol;
    } else {
        lCol = aCol;
        rCol = col;
    }
}

/*!
    Returns true if \a s includes the same cells as the selection;
    otherwise returns false.
*/

bool MDATableSelection::operator==(const MDATableSelection &s) const
{
    return (s.active == active &&
             s.tRow == tRow && s.bRow == bRow &&
             s.lCol == lCol && s.rCol == rCol);
}

/*!
    \fn bool MDATableSelection::operator!=(const MDATableSelection &s) const

    Returns true if \a s does not include the same cells as the
    selection; otherwise returns false.
*/


/*!
    \fn int MDATableSelection::topRow() const

    Returns the top row of the selection.

    \sa bottomRow() leftCol() rightCol()
*/

/*!
    \fn int MDATableSelection::bottomRow() const

    Returns the bottom row of the selection.

    \sa topRow() leftCol() rightCol()
*/

/*!
    \fn int MDATableSelection::leftCol() const

    Returns the left column of the selection.

    \sa topRow() bottomRow() rightCol()
*/

/*!
    \fn int MDATableSelection::rightCol() const

    Returns the right column of the selection.

    \sa topRow() bottomRow() leftCol()
*/

/*!
    \fn int MDATableSelection::anchorRow() const

    Returns the anchor row of the selection.

    \sa anchorCol() expandTo()
*/

/*!
    \fn int MDATableSelection::anchorCol() const

    Returns the anchor column of the selection.

    \sa anchorRow() expandTo()
*/

/*!
    \fn int MDATableSelection::numRows() const

    Returns the number of rows in the selection.

    \sa numCols()
*/
long long MDATableSelection::numRows() const
{
    return (tRow < 0) ? 0 : bRow - tRow + 1;
}

/*!
    Returns the number of columns in the selection.

    \sa numRows()
*/
long long MDATableSelection::numCols() const
{
    return (lCol < 0) ? 0 : rCol - lCol + 1;
}

/*!
    \fn bool MDATableSelection::isActive() const

    Returns whether the selection is active or not. A selection is
    active after init() \e and expandTo() have been called.
*/

/*!
    \fn bool MDATableSelection::isEmpty() const

    Returns whether the selection is empty or not.

    \sa numRows(), numCols()
*/

/*!
    \class MDATableItem
    \brief The MDATableItem class provides the cell content for MDATable cells.

    \compat

    For many applications MDATableItems are ideal for presenting and
    editing the contents of MDATable cells. In situations where you need
    to create very large tables you may prefer an alternative approach
    to using MDATableItems: see the notes on large tables.

    A MDATableItem contains a cell's data, by default, a string and a
    pixmap. The table item also holds the cell's display size and how
    the data should be aligned. The table item specifies the cell's
    \l EditType and the editor used for in-place editing (by default a
    QLineEdit). If you want checkboxes use \l{MDACheckTableItem}, and if
    you want comboboxes use \l{MDAComboTableItem}. The \l EditType (set
    in the constructor) determines whether the cell's contents may be
    edited.

    If a pixmap is specified it is displayed to the left of any text.
    You can change the text or pixmap with setText() and setPixmap()
    respectively. For text you can use setWordWrap().

    When sorting table items the key() function is used; by default
    this returns the table item's text(). Reimplement key() to
    customize how your table items will sort.

    Table items are inserted into a table using MDATable::setItem(). If
    you insert an item into a cell that already contains a table item
    the original item will be deleted.

    Example:
    \snippet doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp 0

    You can move a table item from one cell to another, in the same or
    a different table, using MDATable::takeItem() and MDATable::setItem()
    but see also MDATable::swapCells().

    Table items can be deleted with delete in the standard way; the
    table and cell will be updated accordingly.

    Note, that if you have a table item that is not currently in a table
    then anything you do to that item other than insert it into a table
    will result in undefined behaviour.

    Reimplement createEditor() and setContentFromEditor() if you want
    to use your own widget instead of a QLineEdit for editing cell
    contents. Reimplement paint() if you want to display custom
    content.

    It is important to ensure that your custom widget can accept the
    keyboard focus, so that the user can use the tab key to navigate the
    table as normal. Therefore, if the widget returned by createEditor()
    does not itself accept the keyboard focus, it is necessary to
    nominate a child widget to do so on its behalf. For example, a
    QHBox with two child QLineEdit widgets may use one of them to
    accept the keyboard focus:

    \snippet doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp 1

    By default, table items may be replaced by new MDATableItems
    during the lifetime of a MDATable. Therefore, if you create your
    own subclass of MDATableItem, and you want to ensure that
    this does not happen, you must call setReplaceable(false)
    in the constructor of your subclass.

    \img qtableitems.png Table Items

    \sa MDACheckTableItem MDAComboTableItem

*/

/*!
    \fn MDATable *MDATableItem::table() const

    Returns the MDATable the table item belongs to.

    \sa MDATable::setItem() MDATableItem()
*/

/*!
    \enum MDATableItem::EditType

    \target wheneditable
    This enum is used to define whether a cell is editable or
    read-only (in conjunction with other settings), and how the cell
    should be displayed.

    \value Always
    The cell always \e looks editable.

    Using this EditType ensures that the editor created with
    createEditor() (by default a QLineEdit) is always visible. This
    has implications for the alignment of the content: the default
    editor aligns everything (even numbers) to the left whilst
    numerical values in the cell are by default aligned to the right.

    If a cell with the edit type \c Always looks misaligned you could
    reimplement createEditor() for these items.

    \value WhenCurrent
    The cell \e looks editable only when it has keyboard focus (see
    MDATable::setCurrentCell()).

    \value OnTyping
    The cell \e looks editable only when the user types in it or
    double-clicks it. It resembles the \c WhenCurrent functionality
    but is, perhaps, nicer.

    The \c OnTyping edit type is the default when MDATableItem objects
    are created by the convenience functions MDATable::setText() and
    MDATable::setPixmap().

    \value Never  The cell is not editable.

    The cell is actually editable only if MDATable::isRowReadOnly() is
    false for its row, MDATable::isColumnReadOnly() is false for its
    column, and MDATable::isReadOnly() is false.

    MDAComboTableItems have an isEditable() property. This property is
    used to indicate whether the user may enter their own text or are
    restricted to choosing one of the choices in the list.
    MDAComboTableItems may be interacted with only if they are editable
    in accordance with their EditType as described above.

*/

/*!
    Creates a table item that is a child of table \a table with no
    text. The item has the \l EditType \a et.

    The table item will use a QLineEdit for its editor, will not
    word-wrap and will occupy a single cell. Insert the table item
    into a table with MDATable::setItem().

    The table takes ownership of the table item, so a table item
    should not be inserted into more than one table at a time.
*/

MDATableItem::MDATableItem(MDATable *table)
    : txt(), t(table),
      rw(-1), cl(-1)
{
    enabled = true;
}

/*!
    Creates a table item that is a child of table \a table with text
    \a text. The item has the \l EditType \a et.

    The table item will use a QLineEdit for its editor, will not
    word-wrap and will occupy a single cell. Insert the table item
    into a table with MDATable::setItem().

    The table takes ownership of the table item, so a table item
    should not be inserted into more than one table at a time.
*/

MDATableItem::MDATableItem(MDATable *table, const QString &text)
    : txt(text), t(table),
      rw(-1), cl(-1)
{
    enabled = true;
}

int MDATableItem::RTTI = 0;

/*!
    Returns the Run Time Type Identification value for this table item
    which for MDATableItems is 0.

    When you create subclasses based on MDATableItem make sure that each
    subclass returns a unique rtti() value. It is advisable to use
    values greater than 1000, preferably large random numbers, to
    allow for extensions to this class.

    \sa MDACheckTableItem::rtti() MDAComboTableItem::rtti()
*/

int MDATableItem::rtti() const
{
    return RTTI;
}

/*!
    Returns the text of the table item or an empty string if there is
    no text.

    To ensure that the current value of the editor is returned,
    setContentFromEditor() is called:
    \list 1
    \i if the editMode() is \c Always, or
    \i if editMode() is \e not \c Always but the editor of the cell is
    active and the editor is not a QLineEdit.
    \endlist

    This means that text() returns the original text value of the item
    if the editor is a line edit, until the user commits an edit (e.g.
    by pressing Enter or Tab) in which case the new text is returned.
    For other editors (e.g. a combobox) setContentFromEditor() is
    always called so the currently display value is the one returned.

    \sa setText() pixmap()
*/

QString MDATableItem::text() const
{
    return txt;
}

/*!
    Changes the table item's text to \a str.

    Note that setText() does not update the cell the table item
    belongs to. Use MDATable::updateCell() to repaint the cell's
    contents.

    \sa MDATable::setText() text() setPixmap() MDATable::updateCell()
*/

void MDATableItem::setText(const QString &str)
{
    txt = str;
}

/*!
    This virtual function is used to paint the contents of an item
    using the painter \a p in the rectangular area \a cr using the
    color group \a cg.

    If \a selected is true the cell is displayed in a way that
    indicates that it is highlighted.

    You don't usually need to use this function but if you want to
    draw custom content in a cell you will need to reimplement it.

    The painter passed to this function is translated so that 0, 0
    is the top-left corner of the item that is being painted.

    Note that the painter is not clipped by default in order to get
    maximum efficiency. If you want clipping, use

    \snippet doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp 2

*/

void MDATableItem::paint(QPainter *p, const QPalette &pal,
                        const QRect &cr, bool selected)
{
    p->fillRect(0, 0, cr.width(), cr.height(),
                 selected ? pal.brush(QPalette::Highlight)
			              : pal.brush(QPalette::Base));

    int w = cr.width();
    int h = cr.height();

    if (selected)
        p->setPen(pal.color(QPalette::HighlightedText));
    else
        p->setPen(pal.color(QPalette::Text));
    p->drawText(2, 0, w - 4, h,
                 alignment(), text());
}

/*!
    The alignment function returns how the text contents of the cell
    are aligned when drawn. The default implementation aligns numbers
    to the right and any other text to the left.

    \sa Qt::Alignment
*/

// ed: For consistency reasons a setAlignment() should be provided
// as well.

int MDATableItem::alignment() const
{
    bool num;
    bool ok1 = false, ok2 = false;
    (void)text().toInt(&ok1);
    if (!ok1)
        (void)text().toDouble(&ok2); // ### should be .-aligned
    num = ok1 || ok2;

    return (num ? AlignRight : AlignLeft) | AlignVCenter;
}

/*!
    This virtual function returns the key that should be used for
    sorting. The default implementation returns the text() of the
    relevant item.

    \sa MDATable::setSorting()
*/

QString MDATableItem::key() const
{
    return text();
}

/*!
    This virtual function returns the size a cell needs to show its
    entire content.

    If you subclass MDATableItem you will often need to reimplement this
    function.
*/

QSize MDATableItem::sizeHint() const
{
    if (text().indexOf('\n') == -1)
        return QSize(table()->fontMetrics().horizontalAdvance(text()) + 10,
                      table()->fontMetrics().height());

    QRect r = table()->fontMetrics().boundingRect(2, 0, table()->columnWidth() - 4, 0,
                                                   alignment(),
                                                   text());
    r.setWidth(qMax(r.width() + 10, table()->columnWidth()));
    return QSize(r.width(), r.height());
}

/*!
    Sets row \a r as the table item's row. Usually you do not need to
    call this function.

    If the cell spans multiple rows, this function sets the top row
    and retains the height of the multi-cell table item.

    \sa row() setCol() rowSpan()
*/

void MDATableItem::setRow(long long r)
{
    rw = r;
}

/*!
    Sets column \a c as the table item's column. Usually you will not
    need to call this function.

    If the cell spans multiple columns, this function sets the
    left-most column and retains the width of the multi-cell table
    item.

    \sa col() setRow() colSpan()
*/

void MDATableItem::setCol(long long c)
{
    cl = c;
}

/*!
    Returns the row where the table item is located. If the cell spans
    multiple rows, this function returns the top-most row.

    \sa col() setRow()
*/

long long MDATableItem::row() const
{
    return rw;
}

/*!
    Returns the column where the table item is located. If the cell
    spans multiple columns, this function returns the left-most
    column.

    \sa row() setCol()
*/

long long MDATableItem::col() const
{
    return cl;
}

/*!
    If \a b is true, the table item is enabled; if \a b is false the
    table item is disabled.

    A disabled item doesn't respond to user interaction.

    \sa isEnabled()
*/

void MDATableItem::setEnabled(bool b)
{
    if (b == (bool)enabled)
        return;
    enabled = b;
    table()->updateCell(row(), col());
}

/*!
    Returns true if the table item is enabled; otherwise returns false.

    \sa setEnabled()
*/

bool MDATableItem::isEnabled() const
{
    return (bool)enabled;
}

/*!
    \class MDATable
    \brief The MDATable class provides a flexible editable table widget.

    \compat

    MDATable is easy to use, although it does have a large API because
    of the comprehensive functionality that it provides. MDATable
    includes functions for manipulating \link #headers
    headers\endlink, \link #columnsrows rows and columns\endlink,
    \link #cells cells\endlink and \link #selections
    selections\endlink. MDATable also provides in-place editing and
    drag and drop, as well as a useful set of
    \link #signals signals\endlink. MDATable efficiently supports very
    large tables, for example, tables one million by one million cells
    are perfectly possible. MDATable is economical with memory, using
    none for unused cells.

    \snippet doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp 3

    The first line constructs the table specifying its size in rows
    and columns. We then insert a pixmap and some text into the \e
    same \link #cells cell\endlink, with the pixmap appearing to the
    left of the text. MDATable cells can be populated with
    \l{MDATableItem}s, \l{MDAComboTableItem}s or by \l{MDACheckTableItem}s.
    By default a vertical header appears at the left of the table
    showing row numbers and a horizontal header appears at the top of
    the table showing column numbers. (The numbers displayed start at
    1, although row and column numbers within MDATable begin at 0.)

    If you want to use mouse tracking call setMouseTracking(true) on
    the \e viewport.

    \img qtableitems.png Table Items

    \target headers
    \section1 Headers

    MDATable supports a header column, e.g. to display row numbers, and
    a header row, e.g to display column titles. To set row or column
    labels use MDAHeader::setLabel() on the pointers returned by
    verticalHeader() and horizontalHeader() respectively. The vertical
    header is displayed within the table's left margin whose width is
    set with setLeftMargin(). The horizontal header is displayed
    within the table's top margin whose height is set with
    setTopMargin(). The table's grid can be switched off with
    setShowGrid(). If you want to hide a horizontal header call
    hide(), and call setTopMargin(0) so that the area the header
    would have occupied is reduced to zero size.

    Header labels are indexed via their section numbers. Note that the
    default behavior of MDAHeader regarding section numbers is overriden
    for MDATable. See the explanation below in the Rows and Columns
    section in the discussion of moving columns and rows.

    \target columnsrows
    \section1 Rows and Columns

    Row and column sizes are set with setRowHeight() and
    setColumnWidth(). If you want a row high enough to show the
    tallest item in its entirety, use adjustRow(). Similarly, to make
    a column wide enough to show the widest item use adjustColumn().
    If you want the row height and column width to adjust
    automatically as the height and width of the table changes use
    setRowStretchable() and setColumnStretchable().

    Rows and columns can be hidden and shown with hideRow(),
    hideColumn(), showRow() and showColumn(). New rows and columns are
    inserted using insertRows() and insertColumns(). Additional rows
    and columns are added at the  bottom (rows) or right (columns) if
    you set setNumRows() or setNumCols() to be larger than numRows()
    or numCols(). Existing rows and columns are removed with
    removeRow() and removeColumn(). Multiple rows and columns can be
    removed with removeRows() and removeColumns().

    Rows and columns can be set to be movable using
    rowMovingEnabled() and columnMovingEnabled(). The user can drag
    them to reorder them holding down the Ctrl key and dragging the
    mouse. For performance reasons, the default behavior of Q3Header
    section numbers is overridden by Q3Table. Currently in Q3Table, when
    a row or column is dragged and reordered, the section number is
    also changed to its new position. Therefore, there is no
    difference between the section and the index fields in Q3Header.
    The Q3Table Q3Header classes do not provide a mechanism for indexing
    independently of the user interface ordering.

    The table can be sorted using sortColumn(). Users can sort a
    column by clicking its header if setSorting() is set to true. Rows
    can be swapped with swapRows(), columns with swapColumns() and
    cells with swapCells().

    For editable tables (see setReadOnly()) you can set the read-only
    property of individual rows and columns with setRowReadOnly() and
    setColumnReadOnly(). (Whether a cell is editable or read-only
    depends on these settings and the cell's MDATableItem.

    The row and column which have the focus are returned by
    currentRow() and currentColumn() respectively.

    Although many MDATable functions operate in terms of rows and
    columns the indexOf() function returns a single integer
    identifying a particular cell.

    \target cells
    \section1 Cells

    All of a MDATable's cells are empty when the table is constructed.

    There are two approaches to populating the table's cells. The
    first and simplest approach is to use MDATableItems or MDATableItem
    subclasses. The second approach doesn't use MDATableItems at all
    which is useful for very large sparse tables but requires you to
    reimplement a number of functions. We'll look at each approach in
    turn.

    To put a string in a cell use setText(). This function will create
    a new MDATableItem for the cell if one doesn't already exist, and
    displays the text in it. By default the table item's widget will
    be a QLineEdit. A pixmap may be put in a cell with setPixmap(),
    which also creates a table item if required. A cell may contain \e
    both a pixmap and text; the pixmap is displayed to the left of the
    text. Another approach is to construct a MDATableItem or MDATableItem
    subclass, set its properties, then insert it into a cell with
    setItem().

    If you want cells which contain comboboxes use the MDAComboTableItem
    class. Similarly if you require cells containing checkboxes use
    the MDACheckTableItem class. These table items look and behave just
    like the combobox or checkbox widgets but consume far less memory.

    MDATable takes ownership of its MDATableItems and will delete them
    when the table itself is destroyed. You can take ownership of a
    table item using takeItem() which you use to move a cell's
    contents from one cell to another, either within the same table,
    or from one table to another. (See also, swapCells()).

    In-place editing of the text in MDATableItems, and the values in
    MDAComboTableItems and MDACheckTableItems works automatically. Cells
    may be editable or read-only, see MDATableItem::EditType. If you
    want fine control over editing see beginEdit() and endEdit().

    The contents of a cell can be retrieved as a MDATableItem using
    item(), or as a string with text() or as a pixmap (if there is
    one) with pixmap(). A cell's bounding rectangle is given by
    cellGeometry(). Use updateCell() to repaint a cell, for example to
    clear away a cell's visual representation after it has been
    deleted with clearCell(). The table can be forced to scroll to
    show a particular cell with ensureCellVisible(). The isSelected()
    function indicates if a cell is selected.

    It is possible to use your own widget as a cell's widget using
    setCellWidget(), but subclassing MDATableItem might be a simpler
    approach. The cell's widget (if there is one) can be removed with
    clearCellWidget().

    \keyword notes on large tables
    \target bigtables
    \section2 Large tables

    For large, sparse, tables using MDATableItems or other widgets is
    inefficient. The solution is to \e draw the cell as it should
    appear and to create and destroy cell editors on demand.

    This approach requires that you reimplement various functions.
    Reimplement paintCell() to display your data, and createEditor()
    and setCellContentFromEditor() to support in-place editing. It
    is very important to reimplement resizeData() to have no
    functionality, to prevent MDATable from attempting to create a huge
    array. You will also need to reimplement item(), setItem(),
    takeItem(), clearCell(), and insertWidget(), cellWidget() and
    clearCellWidget(). In almost every circumstance (for sorting,
    removing and inserting columns and rows, etc.), you also need
    to reimplement swapRows(), swapCells() and swapColumns(), including
    header handling.

    If you represent active cells with a dictionary of MDATableItems and
    QWidgets, i.e. only store references to cells that are actually
    used, many of the functions can be implemented with a single line
    of code.

    For more information on cells see the MDATableItem documenation.

    \target selections
    \section1 Selections

    MDATable's support single selection, multi-selection (multiple
    cells) or no selection. The selection mode is set with
    setSelectionMode(). Use isSelected() to determine if a particular
    cell is selected, and isRowSelected() and isColumnSelected() to
    see if a row or column is selected.

    MDATable's support many simultaneous selections. You can
    programmatically select cells with addSelection(). The number of
    selections is given by numSelections(). The current selection is
    returned by currentSelection(). You can remove a selection with
    removeSelection() and remove all selections with
    clearSelection(). Selections are MDATableSelection objects.

    To easily add a new selection use selectCells(), selectRow() or
    selectColumn().

    Alternatively, use addSelection() to add new selections using
    MDATableSelection objects. The advantage of using MDATableSelection
    objects is that you can call MDATableSelection::expandTo() to resize
    the selection and can query and compare them.

    The number of selections is given by numSelections(). The current
    selection is returned by currentSelection(). You can remove a
    selection with removeSelection() and remove all selections with
    clearSelection().

    \target signals
    \section1 Signals

    When the user clicks a cell the currentChanged() signal is
    emitted. You can also connect to the lower level clicked(),
    doubleClicked() and pressed() signals. If the user changes the
    selection the selectionChanged() signal is emitted; similarly if
    the user changes a cell's value the valueChanged() signal is
    emitted. If the user right-clicks (or presses the appropriate
    platform-specific key sequence) the contextMenuRequested() signal
    is emitted. If the user drops a drag and drop object the dropped()
    signal is emitted with the drop event.
*/

/*!
    \fn void MDATable::currentChanged(int row, int col)

    This signal is emitted when the current cell has changed to \a
    row, \a col.
*/

/*!
    \fn void MDATable::valueChanged(int row, int col)

    This signal is emitted when the user changed the value in the cell
    at \a row, \a col.
*/

/*!
    \fn int MDATable::currentRow() const

    Returns the current row.

    \sa currentColumn()
*/

/*!
    \fn int MDATable::currentColumn() const

    Returns the current column.

    \sa currentRow()
*/

/*!
    \enum MDATable::FocusStyle

    Specifies how the current cell (focus cell) is drawn.

    \value FollowStyle The current cell is drawn according to the
    current style and the cell's background is also drawn selected, if
    the current cell is within a selection

    \value SpreadSheet The current cell is drawn as in a spreadsheet.
    This means, it is signified by a black rectangle around the cell,
    and the background of the current cell is always drawn with the
    widget's base color - even when selected.

*/

/*!
    \fn void MDATable::clicked(int row, int col, int button, const QPoint &mousePos)

    This signal is emitted when mouse button \a button is clicked. The
    cell where the event took place is at \a row, \a col, and the
    mouse's position is in \a mousePos.

    \sa Qt::MouseButton
*/

/*!
    \fn void MDATable::doubleClicked(int row, int col, int button, const QPoint &mousePos)

    This signal is emitted when mouse button \a button is
    double-clicked. The cell where the event took place is at \a row,
    \a col, and the mouse's position is in \a mousePos.

    \sa Qt::MouseButton
*/

/*!
    \fn void MDATable::pressed(int row, int col, int button, const QPoint &mousePos)

    This signal is emitted when mouse button \a button is pressed. The
    cell where the event took place is at \a row, \a col, and the
    mouse's position is in \a mousePos.

    \sa Qt::MouseButton
*/

/*!
    \fn void MDATable::selectionChanged()

    This signal is emitted whenever a selection changes.

    \sa MDATableSelection
*/

/*!
    \fn void MDATable::contextMenuRequested(int row, int col, const QPoint & pos)

    This signal is emitted when the user invokes a context menu with
    the right mouse button (or with a system-specific keypress). The
    cell where the event took place is at \a row, \a col. \a pos is
    the position where the context menu will appear in the global
    coordinate system. This signal is always emitted, even if the
    contents of the cell are disabled.
*/

/*!
    Creates an empty table object called \a name as a child of \a
    parent.

    Call setNumRows() and setNumCols() to set the table size before
    populating the table if you're using MDATableItems.
*/

MDATable::MDATable(QWidget *parent, const char *name)
    : QScrollArea(parent),
      leftHeader(0), topHeader(0),
      currentSel(0), lastSortCol(-1), sGrid(true), mRows(false), mCols(false),
      asc(true), doSort(true)
{
    setObjectName(name);
    setAttribute(Qt::WA_StaticContents);
    init(0, 0);
}

/*!
    Constructs an empty table called \a name with \a numRows rows and
    \a numCols columns. The table is a child of \a parent.

    If you're using \l{MDATableItem}s to populate the table's cells, you
    can create MDATableItem, MDAComboTableItem and MDACheckTableItem items
    and insert them into the table using setItem(). (See the notes on
    large tables for an alternative to using MDATableItems.)
*/

MDATable::MDATable(long long numRows, long long numCols, QWidget *parent, const char *name)
    : QScrollArea(parent),
      leftHeader(0), topHeader(0),
      currentSel(0), lastSortCol(-1), sGrid(true), mRows(false), mCols(false),
      asc(true), doSort(true)
{
    setObjectName(name);
    setAttribute(Qt::WA_StaticContents);
    init(numRows, numCols);
}

/*! \internal
*/

void MDATable::init( long long rows, long long cols )
{
    d = new MDATablePrivate;
    d->geomTimer = new QTimer(this);
    d->geomTimer->setSingleShot(true);
    d->lastVisCol = 0;
    d->lastVisRow = 0;
    connect(d->geomTimer, &QTimer::timeout, this, &MDATable::updateGeometriesSlot);
    shouldClearSelection = false;
    dEnabled = false;
    sparse = false;
    maxColWidth = 0;
    oldCurrentCol = -1;
    oldCurrentRow = -1;
    pressedCol = -1;
    pressedRow = -1;

    // All margins are 0 by default (Qt4 lacks a direct accessor for this property)
    viewportMargins = QMargins(0, 0, 0, 0);
    viewport()->setFocusProxy(this);
    viewport()->setFocusPolicy(Qt::WheelFocus);
    setFocusPolicy(Qt::WheelFocus);

    leftHeader = new MDATableHeader(rows, this, this, "left table header");
    leftHeader->setOrientation(Vertical);
    topHeader = new MDATableHeader(cols, this, this, "right table header");
    topHeader->setOrientation(Horizontal);
    int topHeaderMargin = topHeader->sizeHint().height();
    int leftHeaderMargin = leftHeader->sizeHint().width();
    if (QApplication::isRightToLeft())
        setViewportMargins(0, topHeaderMargin, leftHeaderMargin, 0);
    else
        setViewportMargins(leftHeaderMargin, topHeaderMargin, 0, 0);

    // Connect header, table and scrollbars
    connect(horizontalScrollBar(), &QScrollBar::valueChanged,
             topHeader, &MDATableHeader::setOffset);
    connect(verticalScrollBar(), &QScrollBar::valueChanged,
             leftHeader, &MDATableHeader::setOffset);
    connect(horizontalScrollBar(), &QScrollBar::valueChanged,
             viewport(), qOverload<>(&QWidget::update));
    connect(verticalScrollBar(), &QScrollBar::valueChanged,
             viewport(), qOverload<>(&QWidget::update));
    connect(topHeader, &MDATableHeader::sectionSizeChanged,
             this, &MDATable::columnWidthChanged);
    connect(leftHeader, &MDATableHeader::sectionSizeChanged,
             this, &MDATable::rowHeightChanged);
    connect(topHeader, &MDATableHeader::fixedExtentChanged,
             this, &MDATable::topHeaderFixedExtentChanged);
    connect(leftHeader, &MDATableHeader::fixedExtentChanged,
             this, &MDATable::leftHeaderFixedExtentChanged);

    // Initialize variables
    autoScrollTimer = new QTimer(this);
    autoScrollTimer->setSingleShot(true);
    connect(autoScrollTimer, &QTimer::timeout,
             this, &MDATable::doAutoScroll);
    if (rows > 0 && cols > 0)
        setCurrentCell(0, 0);
    else
        curRow = curCol = -1;

    drawActiveSelection = true;

    installEventFilter(this);

    focusStl = FollowStyle;

    was_visible = false;

    // initial size
    resize(640, 480);
}

/*!
    Releases all the resources used by the MDATable object,
    including all \l{MDATableItem}s and their widgets.
*/

MDATable::~MDATable()
{
    setUpdatesEnabled(false);
    qDeleteAll(contents);
    contents.clear();
    foreach (MDATableItem *item, sparseContents)
        delete item;
    sparseContents.clear();

    delete d;
}

/*!
    \property MDATable::focusStyle
    \brief how the current (focus) cell is drawn

    The default style is \c SpreadSheet.

    \sa MDATable::FocusStyle
*/

void MDATable::setFocusStyle(FocusStyle fs)
{
    focusStl = fs;
    updateCell(curRow, curCol);
}

MDATable::FocusStyle MDATable::focusStyle() const
{
    return focusStl;
}

void MDATable::setShowGrid(bool b)
{
    if (sGrid == b)
        return;
    sGrid = b;
    viewport()->update();
}

/*!
    \property MDATable::showGrid
    \brief whether the table's grid is displayed

    The grid is shown by default.
*/

bool MDATable::showGrid() const
{
    return sGrid;
}

/*!
    This is called when MDATable's internal array needs to be resized to
    \a len elements.

    If you don't use MDATableItems you should reimplement this as an
    empty method to avoid wasting memory. See the notes on large
    tables for further details.
*/

void MDATable::resizeData(long long len)
{
    if (isSparse())
        return;
    if (len > INT_MAX)
        qFatal("resizeData called with len > INT_MAX: %lld", len);

    while (len > contents.size())
        contents.resize(static_cast<int>(len));
    while (len < contents.size()) {
        MDATableItem *itm = contents.last();
        contents.remove(contents.size() - 1);
        delete itm;
    }
}

/*!
    Sets the left margin to be \a m pixels wide.

    The verticalHeader(), which displays row labels, occupies this
    margin.

    In an Arabic or Hebrew localization, the verticalHeader() will
    appear on the right side of the table, and this call will set the
    right margin.

    \sa viewportMargins.left() setTopMargin() verticalHeader()
*/

void MDATable::setLeftMargin(int m)
{
    if (QApplication::isRightToLeft())
        viewportMargins.setRight(m);
    else
        viewportMargins.setLeft(m);
    setViewportMargins(viewportMargins);
    updateGeometries();
}

/*!
    Sets the top margin to be \a m pixels high.

    The horizontalHeader(), which displays column labels, occupies
    this margin.

    \sa viewportMargins.top() setLeftMargin()
*/

void MDATable::setTopMargin(int m)
{
    viewportMargins.setTop(m);
    setViewportMargins(viewportMargins);
    updateGeometries();
}

void MDATable::leftHeaderFixedExtentChanged(int s)
{
    setLeftMargin(s);
}

void MDATable::topHeaderFixedExtentChanged(int s)
{
    setTopMargin(s);
}

static bool is_child_of(QWidget *child, QWidget *parent)
{
    while (child) {
        if (child == parent)
            return true;
        child = child->parentWidget();
    }
    return false;
}

/*!
    Draws the table contents on the painter \a p. This function is
    optimized so that it only draws the cells inside the \a cw pixels
    wide and \a ch pixels high clipping rectangle at position \a cx,
    \a cy.

    Additionally, drawContents() highlights the current cell.
*/

void MDATable::drawContents(QPainter *p, const QRect &rect)
{
    const int vpx = 0;
    const int vpy = 0;
    const int vpw = viewport()->width();
    const int vph = viewport()->height();

    if (numRows() == 0 || numCols() == 0) {
        paintEmptyArea(p, vpx, vpy, vpw, vph);
        return;
    }

    long long colfirst = columnAt(rect.left());
    long long collast = columnAt(rect.right());
    long long rowfirst = rowAt(rect.top());
    long long rowlast = rowAt(rect.bottom());

    if (rowfirst == -1 || colfirst == -1) {
        paintEmptyArea(p, vpx, vpy, vpw, vph);
        return;
    }

    drawActiveSelection = hasFocus() || viewport()->hasFocus() || d->inMenuMode
                        || is_child_of(qApp->focusWidget(), viewport())
                        || !style()->styleHint(QStyle::SH_ItemView_ChangeHighlightOnFocus);
    if (rowlast == -1)
        rowlast = numRows() - 1;
    if (collast == -1)
        collast = numCols() - 1;

    bool currentInSelection = false;

    QListIterator<MDATableSelection*> it( selections );
    while ( it.hasNext() ) {
        MDATableSelection *s = it.next();
        if (s->isActive() &&
             curRow >= s->topRow() &&
             curRow <= s->bottomRow() &&
             curCol >= s->leftCol() &&
             curCol <= s->rightCol()) {
            currentInSelection = s->topRow() != curRow || s->bottomRow() != curRow || s->leftCol() != curCol || s->rightCol() != curCol;
            break;
        }
    }

    int colw = columnWidth();
    int rowh = rowHeight();
    int rowp = rowPos(rowfirst);

    // Go through the rows
    for (long long r = rowfirst; r <= rowlast; ++r) {
        if (isRowHidden(r))
            continue;

        // get position and width of first column
        int colp = columnPos(colfirst);

        // Go through the columns in row r
        // if we know from where to where, go through [colfirst, collast],
        // else go through all of them
        for (long long c = colfirst; c <= collast; ++c) {
            if (isColumnHidden(c))
                continue;

            // Translate painter and draw the cell
    	    p->translate(colp, rowp);
    	    bool selected = isSelected(r, c);
            if (focusStl != FollowStyle && selected && !currentInSelection &&
                 r == curRow && c == curCol )
                selected = false;
    	    paintCell(p, r, c, QRect(colp, rowp, colw, rowh), selected);
    	    p->translate(-colp, -rowp);

            colp += colw;
        }

        rowp += rowh;
    }
    d->lastVisCol = collast;
    d->lastVisRow = rowlast;

    // draw indication of current cell
    if (curRow != -1 && curCol != -1) {
        QRect focusRect = cellGeometry(curRow, curCol);
        p->translate(focusRect.x(), focusRect.y());
        paintFocus(p, focusRect);
        p->translate(-focusRect.x(), -focusRect.y());
    }

    // Paint empty rects
    paintEmptyArea(p, vpx, vpy, vpw, vph);

    drawActiveSelection = true;
}

/*!
    Returns the geometry of cell \a row, \a col in the cell's
    coordinate system. This is a convenience function useful in
    paintCell(). It is equivalent to QRect(QPoint(0,0), cellGeometry(
    row, col).size());

    \sa cellGeometry()
*/

QRect MDATable::cellRect(long long row, long long col) const
{
    return QRect(QPoint(0,0), cellGeometry(row, col).size());
}

/*!
    \overload

    Use the other paintCell() function. This function is only included
    for backwards compatibility.
*/

void MDATable::paintCell(QPainter* p, long long row, long long col,
                        const QRect &cr, bool selected)
{
    if (cr.width() == 0 || cr.height() == 0)
        return;
#if defined(Q_OS_WIN)
    const QPalette::ColorGroup cg = (!drawActiveSelection && style()->styleHint(QStyle::SH_ItemView_ChangeHighlightOnFocus) ? QPalette::Inactive : QPalette::Normal);
#else
    const QPalette::ColorGroup cg = QPalette::Normal;
#endif

    MDATableItem *itm = item(row, col);
    QPalette::ColorGroup cg2 = cg;
    if ((itm && !itm->isEnabled()) ||
        (!itm && validRegion.contains(QPoint(col, row))))
        cg2 = QPalette::Disabled;

    paintCell(p, row, col, cr, selected, cg2);
}

/*!
    Paints the cell at \a row, \a col on the painter \a p. The painter
    has already been translated to the cell's origin. \a cr describes
    the cell coordinates in the content coordinate system.

    If \a selected is true the cell is highlighted.

    \a cg is the colorgroup which should be used to draw the cell
    content.

    If you want to draw custom cell content, for example right-aligned
    text, you must either reimplement paintCell(), or subclass
    MDATableItem and reimplement MDATableItem::paint() to do the custom
    drawing.

    If you're using a MDATableItem subclass, for example, to store a
    data structure, then reimplementing MDATableItem::paint() may be the
    best approach. For data you want to draw immediately, e.g. data
    retrieved from a database, it is probably best to reimplement
    paintCell(). Note that if you reimplement paintCell(), i.e. don't
    use \l{MDATableItem}s, you must reimplement other functions: see the
    notes on large tables.

    Note that the painter is not clipped by default in order to get
    maximum efficiency. If you want clipping, use code like this:

    \snippet doc/src/snippets/code/src_qt3support_itemviews_q3table.cpp 4
*/

void MDATable::paintCell(QPainter *p, long long row, long long col,
                         const QRect &cr, bool selected, const QPalette::ColorGroup cg)
{
    if (focusStl == SpreadSheet && selected &&
         row == curRow &&
         col == curCol && ( hasFocus() || viewport()->hasFocus() ) )
        selected = false;

    QPalette pal = palette();
    pal.setCurrentColorGroup(cg);
    int w = cr.width();
    int h = cr.height();
    int x2 = w - 1;
    int y2 = h - 1;


    MDATableItem *itm = item(row, col);
    if (itm) {
        p->save();
        itm->paint(p, pal, cr, selected);
        p->restore();
    } else {
        p->fillRect(0, 0, w, h, selected ? pal.brush(QPalette::Highlight) : pal.brush(QPalette::Base));
    }

    if (sGrid) {
        // Draw our lines
        QPen pen(p->pen());
        int gridColor =        style()->styleHint(QStyle::SH_Table_GridLineColor);
        if (gridColor != -1) {
            if (palette() != pal)
                p->setPen(pal.mid().color());
            else
                p->setPen((QRgb)gridColor);
        } else {
            p->setPen(pal.mid().color());
        }
        p->drawLine(x2, 0, x2, y2);
        p->drawLine(0, y2, x2, y2);
        p->setPen(pen);
    }
}

/*!
    Draws the focus rectangle of the current cell (see currentRow(),
    currentColumn()).

    The painter \a p is already translated to the cell's origin, while
    \a cr specifies the cell's geometry in content coordinates.
*/

void MDATable::paintFocus(QPainter *p, const QRect &cr)
{
    if (!hasFocus() && !viewport()->hasFocus())
        return;
    QRect focusRect(0, 0, cr.width(), cr.height());
    if (focusStyle() == SpreadSheet) {
        p->setPen(QPen(Qt::black, 1));
        p->setBrush(Qt::NoBrush);
        p->drawRect(focusRect.x(), focusRect.y(), focusRect.width() - 1, focusRect.height() - 1);
        p->drawRect(focusRect.x() - 1, focusRect.y() - 1, focusRect.width() + 1, focusRect.height() + 1);
    } else {
        QStyleOptionFocusRect opt;
        opt.initFrom(this);
        opt.rect = focusRect;
        opt.palette = palette();
        opt.state |= QStyle::State_KeyboardFocusChange;
        if (isSelected(curRow, curCol, false)) {
            opt.state |= QStyle::State_FocusAtBorder;
            opt.backgroundColor = palette().highlight().color();
        } else {
            opt.state |= QStyle::State_None;
            opt.backgroundColor = palette().base().color();
        }
        style()->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, p, this);
    }
}

/*!
    This function fills the \a cw pixels wide and \a ch pixels high
    rectangle starting at position \a cx, \a cy with the background
    color using the painter \a p.

    paintEmptyArea() is invoked by drawContents() to erase or fill
    unused areas.
*/

void MDATable::paintEmptyArea(QPainter *p, int cx, int cy, int cw, int ch)
{
    // Determine the region to paint over by subtracting the table from it
    const QRegion reg = QRegion(QRect(cx, cy, cw, ch)).subtracted(QRect(QPoint(0, 0), tableSize()));

    for (const QRect& rect : reg)
        p->fillRect(rect, viewport()->palette().brush(QPalette::Base));
}

/*!
    Returns the MDATableItem representing the contents of the cell at \a
    row, \a col.

    If \a row or \a col are out of range or no content has been set
    for this cell, item() returns 0.

    If you don't use \l{MDATableItem}s you may need to reimplement this
    function: see the notes on large tables.

    \sa setItem()
*/

MDATableItem *MDATable::item(long long row, long long col) const
{
    if (row < 0 || col < 0 || row > numRows() - 1 ||
         col > numCols() - 1)
        return 0;

    if (isSparse())
        return sparseContents[ indexOf(row, col) ];

    if (row * col >= (int)contents.size())
        return 0;

    return contents[ indexOf(row, col) ];        // contents array lookup
}

/*!
    Inserts the table item \a item into the table at row \a row,
    column \a col, and repaints the cell. If a table item already
    exists in this cell it is deleted and replaced with \a item. The
    table takes ownership of the table item.

    If you don't use \l{MDATableItem}s you may need to reimplement this
    function: see the notes on large tables.

    \sa item() takeItem()
*/

void MDATable::setItem(long long row, long long col, MDATableItem *item)
{
    if (!item)
        return;

    if (!isSparse())
        if ((int)contents.size() != numRows() * numCols())
            resizeData(numRows() * numCols());

    clearCell(row, col);

    if (isSparse())
        sparseContents.insert(indexOf(row, col), item);
    else
        contents[ indexOf(row, col) ] = item;

    item->setRow(row);
    item->setCol(col);
    item->t = this;
    updateCell(row, col);

    maxColWidth = qMax(maxColWidth, item->sizeHint().width());
}

/*!
    Removes the MDATableItem at \a row, \a col.

    If you don't use \l{MDATableItem}s you may need to reimplement this
    function: see the notes on large tables.
*/

void MDATable::clearCell(long long row, long long col)
{
    if (!isSparse())
        if ((int)contents.size() != numRows() * numCols())
            resizeData(numRows() * numCols());

    QRect rect = cellGeometry(row, col);
    if (isSparse()) {
        long long index = indexOf(row, col);
        QMap<long long, MDATableItem *>::iterator it(sparseContents.find(index));
        if (it != sparseContents.end()) {
            delete *it;
            sparseContents.erase(it);
        }
    } else {
        MDATableItem *itm = contents[ indexOf(row, col) ];
        contents[ indexOf(row, col) ] = 0;
        delete itm;
    }
    viewport()->repaint(rect);
}

/*!
    Sets the text in the cell at \a row, \a col to \a text.

    If the cell does not contain a table item a MDATableItem is created
    with an \link MDATableItem::EditType EditType\endlink of \c OnTyping,
    otherwise the existing table item's text (if any) is replaced with
    \a text.

    \sa text() setPixmap() setItem() MDATableItem::setText()
*/

void MDATable::setText(long long row, long long col, const QString &text)
{
    MDATableItem *itm = item(row, col);
    if (itm) {
        itm->setText(text);
        updateCell(row, col);
    } else {
        MDATableItem *i = new MDATableItem(this, text);
        setItem(row, col, i);
    }
}

/*!
    Returns the text in the cell at \a row, \a col, or an empty string
    if the relevant item does not exist or has no text.

    \sa setText() setPixmap()
*/

QString MDATable::text(long long row, long long col) const
{
    MDATableItem *itm = item(row, col);
    if (itm)
        return itm->text();
    return QString();
}

/*!
    Moves the focus to the cell at \a row, \a col.

    \sa currentRow() currentColumn()
*/

void MDATable::setCurrentCell(long long row, long long col)
{
    setCurrentCell(row, col, true, true);
}

/*!
    \reimp
*/
QVariant MDATable::inputMethodQuery(Qt::InputMethodQuery query) const
{
    if (query == Qt::ImCursorRectangle)
        return QRect(columnPos(curCol) + viewportMargins.left() - horizontalScrollBar()->value(), rowPos(curRow) + viewportMargins.top() - verticalScrollBar()->value(),
                     columnWidth(), rowHeight());
    return QWidget::inputMethodQuery(query);

}

/*! \internal */

void MDATable::setCurrentCell(long long row, long long col, bool updateSelections, bool ensureVisible)
{
    if (row > numRows() - 1)
        row = numRows() - 1;
    if (col > numCols() - 1)
        col = numCols() - 1;

    if (curRow == row && curCol == col)
        return;

    long long oldRow = curRow;
    long long oldCol = curCol;
    curRow = row;
    curCol = col;
    if (oldRow != -1 && oldCol != -1)
        repaintCell(oldRow, oldCol);
    if (curRow != -1 && curCol != -1) {
        repaintCell(curRow, curCol);
        if (ensureVisible)
            ensureCellVisible(curRow, curCol);
    }
    emit currentChanged(row, col);

    if (updateSelections && !isSelected(curRow, curCol, false)) {
        clearSelection();
        currentSel = new MDATableSelection();
        selections.append(currentSel);
        currentSel->init(curRow, curCol);
        repaintSelections(0, currentSel);
    }
}

/*!
    Scrolls the table until the cell at \a row, \a col becomes
    visible.
*/

void MDATable::ensureCellVisible(long long row, long long col)
{
    if (!viewport()->updatesEnabled())
        return;

    // N.B. this is in viewport coordinates
    const QRect cellRect(cellGeometry(row, col));

    // Adjust scrollbars by amount necessary to make cell visible
    if (cellRect.bottom() > viewport()->height())
        verticalScrollBar()->setValue(verticalScrollBar()->value() + cellRect.bottom() - viewport()->height() + 1);
    else if (cellRect.top() < 0)
        verticalScrollBar()->setValue(verticalScrollBar()->value() + cellRect.top());

    if (cellRect.right() > viewport()->width())
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() + cellRect.right() - viewport()->width() + 1);
    else if (cellRect.left() < 0)
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() + cellRect.left());
}

/*!
    Returns true if the cell at \a row, \a col is selected; otherwise
    returns false.

    \sa isRowSelected() isColumnSelected()
*/

bool MDATable::isSelected(long long row, long long col) const
{
    return isSelected(row, col, true);
}

/*! \internal */

bool MDATable::isSelected(long long row, long long col, bool includeCurrent) const
{
    QListIterator<MDATableSelection*> it(selections);
    while (it.hasNext()) {
        MDATableSelection *s = it.next();
        if (s->isActive() &&
             row >= s->topRow() &&
             row <= s->bottomRow() &&
             col >= s->leftCol() &&
             col <= s->rightCol())
            return true;
        if (includeCurrent && row == currentRow() && col == currentColumn())
            return true;
    }
    return false;
}

/*!
    Returns true if row \a row is selected; otherwise returns false.

    If \a full is false (the default), 'row is selected' means that at
    least one cell in the row is selected. If \a full is true, then 'row
    is selected' means every cell in the row is selected.

    \sa isColumnSelected() isSelected()
*/

bool MDATable::isRowSelected(long long row, bool full) const
{
    if (!full) {
        QListIterator<MDATableSelection*> it(selections);
        while (it.hasNext()) {
            MDATableSelection *s = it.next();
            if (s->isActive() &&
                 row >= s->topRow() &&
                 row <= s->bottomRow())
            return true;
        if (row == currentRow())
            return true;
	}
    } else {
        QListIterator<MDATableSelection*> it(selections);
        while (it.hasNext()) {
            MDATableSelection *s = it.next();
            if (s->isActive() &&
                 row >= s->topRow() &&
                 row <= s->bottomRow() &&
                 s->leftCol() == 0 &&
                 s->rightCol() == numCols() - 1)
                return true;
        }
    }
    return false;
}

/*!
    Returns true if column \a col is selected; otherwise returns false.

    If \a full is false (the default), 'column is selected' means that
    at least one cell in the column is selected. If \a full is true,
    then 'column is selected' means every cell in the column is
    selected.

    \sa isRowSelected() isSelected()
*/

bool MDATable::isColumnSelected(long long col, bool full) const
{
    if (!full) {
        QListIterator<MDATableSelection*> it(selections);
        while (it.hasNext()) {
            MDATableSelection *s = it.next();
            if (s->isActive() &&
                 col >= s->leftCol() &&
                 col <= s->rightCol())
            return true;
        if (col == currentColumn())
            return true;
        }
    } else {
        QListIterator<MDATableSelection*> it( selections );
        while (it.hasNext()) {
            MDATableSelection *s = it.next();
            if (s->isActive() &&
                 col >= s->leftCol() &&
                 col <= s->rightCol() &&
                 s->topRow() == 0 &&
                 s->bottomRow() == numRows() - 1)
                return true;
        }
    }
    return false;
}

bool MDATable::isSectionValid(long long row, long long col) const
{
    return leftHeader->isSectionValid(row) && topHeader->isSectionValid(col);
}

/*!
    \property MDATable::numSelections
    \brief The number of selections.

    \sa currentSelection()
*/

int MDATable::numSelections() const
{
    return selections.count();
}

/*!
    Returns selection number \a num, or an inactive MDATableSelection if \a
    num is out of range (see MDATableSelection::isActive()).
*/

MDATableSelection MDATable::selection(int num) const
{
    if (num < 0 || num >= (int)selections.count())
        return MDATableSelection();

    return *(selections.at(num));
}

/*!
    Adds a selection described by \a s to the table and returns its
    number or -1 if the selection is invalid.

    Remember to call MDATableSelection::init() and
    MDATableSelection::expandTo() to make the selection valid (see also
    MDATableSelection::isActive(), or use the
    MDATableSelection(int,int,int,int) constructor).

    \sa numSelections() removeSelection() clearSelection()
*/

int MDATable::addSelection(const MDATableSelection &s)
{
    if (!s.isActive())
        return -1;

    const long long maxr = numRows()-1;
    const long long maxc = numCols()-1;
    currentSel = new MDATableSelection(qMin(s.anchorRow(), maxr), qMin(s.anchorCol(), maxc),
                                    qMin(s.bottomRow(), maxr), qMin(s.rightCol(), maxc));

    selections.append(currentSel);

    repaintSelections(0, currentSel, true, true);

    emit selectionChanged();

    return selections.count() - 1;
}

/*!
    If the table has a selection, \a s, this selection is removed from
    the table.

    \sa addSelection() numSelections()
*/

void MDATable::removeSelection(const MDATableSelection &s)
{
    QMutableListIterator<MDATableSelection*> it(selections);
    while (it.hasNext()) {
        MDATableSelection *sel = it.next();
        if (s == *sel) {
            it.remove();
            repaintSelections(sel, 0, true, true);
            if (sel == currentSel)
                currentSel = 0;
            delete sel;
        }
    }
    emit selectionChanged();
}

/*!
    \overload

    Removes selection number \a num from the table.

    \sa numSelections() addSelection() clearSelection()
*/

void MDATable::removeSelection(int num)
{
    if (num < 0 || num >= (int)selections.count())
        return;

    MDATableSelection *s = selections.takeAt(num);
    if (s == currentSel)
        currentSel = 0;
    delete s;
    viewport()->repaint();
}

/*!
    Returns the number of the current selection or -1 if there is no
    current selection.

    \sa numSelections()
*/

int MDATable::currentSelection() const
{
    if (!currentSel)
        return -1;
    return selections.indexOf(currentSel);
}

/*!
 * Returns the current selection as a MDATableSelection
 */
MDATableSelection MDATable::getCurrentSelection() const
{
    return selection(currentSelection());
}

/*! Selects the range starting at \a start_row and \a start_col and
  ending at \a end_row and \a end_col.

  \sa MDATableSelection
*/

void MDATable::selectCells(long long start_row, long long start_col, long long end_row, long long end_col)
{
    const long long maxr = numRows()-1;
    const long long maxc = numCols()-1;

    start_row = qMin(maxr, qMax(0LL, start_row));
    start_col = qMin(maxc, qMax(0LL, start_col));
    end_row = qMin(maxr, end_row);
    end_col = qMin(maxc, end_col);
    MDATableSelection sel(start_row, start_col, end_row, end_col);
    addSelection(sel);
}

/*! Selects the row \a row.

  \sa MDATableSelection
*/

void MDATable::selectRow(long long row)
{
    row = qMin(numRows()-1, row);
    if (row < 0)
        return;
    MDATableSelection sel(row, 0, row, numCols() - 1);
    addSelection(sel);
}

/*! Selects the column \a col.

  \sa MDATableSelection
*/

void MDATable::selectColumn(long long col)
{
    col = qMin(numCols()-1, col);
    MDATableSelection sel(0, col, numRows() - 1, col);
    addSelection(sel);
}

/*! \reimp
*/
void MDATable::mousePressEvent(QMouseEvent* e)
{
    mousePressEventEx(e);
}

void MDATable::mousePressEventEx(QMouseEvent* e)
{
    shouldClearSelection = false;

    d->redirectMouseEvent = false;

    long long tmpRow = rowAt(e->pos().y());
    long long tmpCol = columnAt(e->pos().x());
    pressedRow = tmpRow;
    pressedCol = tmpCol;
    fixRow(tmpRow, e->pos().y());
    fixCol(tmpCol, e->pos().x());
    if (tmpRow == -1 && tmpCol == -1)
        return;

    MDATableItem *itm = item(pressedRow, pressedCol);
    if (itm && !itm->isEnabled()) {
        emit pressed(tmpRow, tmpCol, e->button(), e->pos());
        return;
    }

    if ((e->modifiers() & ShiftModifier) == ShiftModifier) {
          long long oldRow = curRow;
          long long oldCol = curCol;
        setCurrentCell(tmpRow, tmpCol, false, true);
        if (!currentSel) {
           currentSel = new MDATableSelection();
           selections.append(currentSel);
           currentSel->init(oldRow, oldCol);
        }
        MDATableSelection oldSelection = *currentSel;
        currentSel->expandTo(tmpRow, tmpCol);
        repaintSelections(&oldSelection, currentSel);
        emit selectionChanged();
    } else {
        setCurrentCell(tmpRow, tmpCol, false, true);
        if (isSelected(tmpRow, tmpCol, false)) {
            shouldClearSelection = true;
        } else {
            bool b = signalsBlocked();
            blockSignals(true);
            clearSelection();
            blockSignals(b);
            currentSel = new MDATableSelection();
            selections.append(currentSel);
            currentSel->init(tmpRow, tmpCol);
            currentSel->expandTo(tmpRow, tmpCol);
            emit selectionChanged();
        }
    }

    emit pressed(tmpRow, tmpCol, e->button(), e->pos());
}

/*! \reimp
*/

void MDATable::mouseDoubleClickEvent(QMouseEvent *e)
{
    if (e->button() != LeftButton)
        return;   
    long long tmpRow = rowAt(e->pos().y());
    long long tmpCol = columnAt(e->pos().x());
    if (tmpRow == -1 && tmpCol == -1)
        return;
    MDATableItem *itm = item(tmpRow, tmpCol);
    if (itm && !itm->isEnabled())
        return;

    emit doubleClicked(tmpRow, tmpCol, e->button(), e->pos());
}

/*! \reimp
*/

void MDATable::mouseMoveEvent(QMouseEvent *e)
{
    long long tmpRow = rowAt(e->pos().y());
    long long tmpCol = columnAt(e->pos().x());
    fixRow(tmpRow, e->pos().y());
    fixCol(tmpCol, e->pos().x());
    if (tmpRow == -1 && tmpCol == -1)
        return;

    if (shouldClearSelection) {
        clearSelection();
        currentSel = new MDATableSelection();
        selections.append(currentSel);
        currentSel->init(tmpRow, tmpCol);
        emit selectionChanged();
        shouldClearSelection = false;
    }

    QPoint pos = mapFromGlobal(e->globalPos());
    pos -= QPoint(viewportMargins.left(), viewportMargins.top());
    autoScrollTimer->stop();
    doAutoScroll();
    if (pos.x() < 0 || pos.x() > viewport()->width() || pos.y() < 0 || pos.y() > viewport()->height())
        autoScrollTimer->start(100);
}

/*! \internal
*/

void MDATable::doAutoScroll()
{
    const QPoint pos = viewport()->mapFromGlobal(QCursor::pos());

	long long tmpRow = rowAt(pos.y());
	long long tmpCol = columnAt(pos.x());

    if (tmpRow < 0 || tmpRow > numRows() - 1)
        tmpRow = currentRow();
    if (tmpCol < 0 || tmpCol > numCols() - 1)
        tmpCol = currentColumn();

    ensureCellVisible(tmpRow, tmpCol);

    if (currentSel) {
        MDATableSelection oldSelection = *currentSel;
        bool useOld = true;
        currentSel->expandTo(tmpRow, tmpCol);
        setCurrentCell(tmpRow, tmpCol, false, true);
        repaintSelections(useOld ? &oldSelection : 0, currentSel);
        if (currentSel && oldSelection != *currentSel)
            emit selectionChanged();
    } else {
        setCurrentCell(tmpRow, tmpCol, false, true);
    }

    if (pos.x() < 0 || pos.x() > viewport()->width() || pos.y() < 0 || pos.y() > viewport()->height())
        autoScrollTimer->start(100);
}

/*! \reimp
*/

void MDATable::mouseReleaseEvent(QMouseEvent *e)
{
    if (pressedRow == curRow && pressedCol == curCol)
        emit clicked(curRow, curCol, e->button(), e->pos());

    if (e->button() != LeftButton)
        return;
    if (shouldClearSelection) {
        long long tmpRow = rowAt(e->pos().y());
        long long tmpCol = columnAt(e->pos().x());
        fixRow(tmpRow, e->pos().y());
        fixCol(tmpCol, e->pos().x());
        if (tmpRow != -1 && tmpCol != -1) {
           clearSelection();
           currentSel = new MDATableSelection();
           selections.append(currentSel);
           currentSel->init(tmpRow, tmpCol);
           repaintSelections(0, currentSel);
           emit selectionChanged();
           shouldClearSelection = false;
        }
    }
    autoScrollTimer->stop();
}

/*!
  \reimp
*/

void MDATable::contextMenuEvent(QContextMenuEvent *e)
{
    if (e->reason() == QContextMenuEvent::Keyboard) {
        QRect r = cellGeometry(curRow, curCol);
        emit contextMenuRequested(curRow, curCol, viewport()->mapToGlobal(r.center()));
    } else {
        long long tmpRow = rowAt(e->pos().y());
        long long tmpCol = columnAt(e->pos().x());
        emit contextMenuRequested(tmpRow, tmpCol, e->globalPos());
    }
}

void MDATable::copy()
{
    int curSel = currentSelection();
    if (curSel == -1)
        return;
    MDATableSelection sel = selection(curSel);
    if (!sel.isActive())
        return;
    QString s;
    for (long long r = sel.topRow(); r <= sel.bottomRow(); ++r) {
        for (long long c = sel.leftCol(); c <= sel.rightCol(); ++c) {
            if (c != sel.leftCol())
                s += ",";
            s += text(r, c);
        }
        if (r != sel.bottomRow())
            s += "\n";
    }
    QClipboard *cb = QApplication::clipboard();
    cb->setText(s, QClipboard::Clipboard);
}

/*! \reimp
*/

bool MDATable::eventFilter(QObject *o, QEvent *e)
{
    switch (e->type()) {
    case QEvent::KeyPress: {
        if (o == this || o == viewport()) {
            QKeyEvent *ke = (QKeyEvent*)e;
            if ((ke->modifiers() & ControlModifier) == ControlModifier ||
                 (ke->key() != Key_Left && ke->key() != Key_Right &&
                   ke->key() != Key_Up && ke->key() != Key_Down &&
                   ke->key() != Key_PageUp && ke->key() != Key_PageDown &&
                   ke->key() != Key_Home && ke->key() != Key_End))
                return false;
            keyPressEvent((QKeyEvent*)e);
            return true;
        }

	} break;
#ifndef QT_NO_WHEELEVENT
    case QEvent::Wheel:
	    if (o == this || o == viewport()) {
	        QWheelEvent* we = (QWheelEvent*)e;
            verticalScrollBar()->setValue(verticalScrollBar()->value() - we->angleDelta().y());
	        we->accept();
	        return true;
	    }
#endif
    default:
        break;
    }

    return QScrollArea::eventFilter(o, e);
}

void MDATable::fixCell(long long &row, long long &col, int key)
{
    if (row == -1 || col == -1) {
        row = -1;
        col = -1;
        return;
    }

    if (!isRowHidden(row) && !isColumnHidden(col))
        return;
    if (isRowHidden(row)) {
        if (key == Key_Down ||
             key == Key_PageDown ||
             key == Key_End) {
            while (row < numRows() && isRowHidden(row))
                ++row;
            if (row == numRows())
                row = curRow;
        } else if (key == Key_Up ||
                    key == Key_PageUp ||
                    key == Key_Home)
                while (row >= 0 && isRowHidden(row))
                    --row;
        if (row < 0)
            row = curRow;
    } else if (isColumnHidden(col)) {
        if (key == Key_Left) {
            while (col >= 0 && isColumnHidden(col))
                --col;
            if (col < 0)
                col = curCol;
        } else if (key == Key_Right) {
            while (col < numCols() && isColumnHidden(col))
                ++col;
            if (col == numCols())
                col = curCol;
        }
    }
}

/*! \reimp
*/

void MDATable::keyPressEvent(QKeyEvent* e)
{
    long long tmpRow = curRow;
    long long tmpCol = curCol;
    long long oldRow = tmpRow;
    long long oldCol = tmpCol;

    bool navigationKey = false;
    long long r;
    switch (e->key()) {
    case Key_Left:
        tmpCol = qMax(0LL, tmpCol - 1);
        navigationKey = true;
        break;
    case Key_Right:
        tmpCol = qMin(numCols() - 1, tmpCol + 1);
        navigationKey = true;
        break;
    case Key_Up:
        tmpRow = qMax(0LL, tmpRow - 1);
        navigationKey = true;
        break;
    case Key_Down:
        tmpRow = qMin(numRows() - 1, tmpRow + 1);
        navigationKey = true;
        break;
    case Key_PageUp:
        r = qMax(0LL, rowAt(rowPos(tmpRow) - viewport()->height()));
        if (r < tmpRow || tmpRow < 0)
            tmpRow = r;
        navigationKey = true;
        break;
    case Key_PageDown:
        r = qMin(numRows() - 1, rowAt(rowPos(tmpRow) + viewport()->height()));
        if (r > tmpRow)
            tmpRow = r;
        else
            tmpRow = numRows() - 1;
        navigationKey = true;
        break;
    case Key_Home:
        tmpRow = 0;
        navigationKey = true;
        break;
    case Key_End:
        tmpRow = numRows() - 1;
        navigationKey = true;
        break;
    case Key_Enter: case Key_Return:
        activateNextCell();
        return;
    case Key_Tab: case Key_Backtab:
        if ((e->key() == Key_Tab) && !(e->modifiers() & ShiftModifier)) {
            if (currentColumn() >= numCols() - 1)
                return;
            long long cc  = qMin(numCols() - 1, currentColumn() + 1);
            while (cc < numCols()) {
                MDATableItem *i = item(currentRow(), cc);
                if (!isColumnHidden(cc) && (!i || i->isEnabled()))
                    break;
                ++cc;
            }
            setCurrentCell(currentRow(), cc);
        } else { // Key_BackTab
            if (currentColumn() <= 0)
                return;
            long long cc  = qMax(0LL, currentColumn() - 1);
            while (cc >= 0) {
                MDATableItem *i = item(currentRow(), cc);
                if (!isColumnHidden(cc) && (!i || i->isEnabled()))
                    break;
                --cc;
            }
            setCurrentCell(currentRow(), cc);
        }
        return;
    case Key_Escape:
        e->ignore();
        return;
    case Key_C:
        if (e->modifiers() & ControlModifier) {
            e->accept();
            copy();
        } else {
            e->ignore();
        }
        return;
    default: // ... or start in-place editing
        e->ignore();
        return;
    }

    if (navigationKey) {
        fixCell(tmpRow, tmpCol, e->key());
        if (tmpRow != -1 && tmpCol != -1) {
            if ((e->modifiers() & ShiftModifier) == ShiftModifier) {
                bool justCreated = false;
                setCurrentCell(tmpRow, tmpCol, false, true);
                if (!currentSel) {
                    justCreated = true;
                    currentSel = new MDATableSelection();
                    selections.append(currentSel);
                    currentSel->init(oldRow, oldCol);
                }
                MDATableSelection oldSelection = *currentSel;
                currentSel->expandTo(tmpRow, tmpCol);
                repaintSelections(justCreated ? 0 : &oldSelection, currentSel);
                emit selectionChanged();
            } else {
                setCurrentCell(tmpRow, tmpCol, false, true);
                bool currentInSelection = isSelected(tmpRow, tmpCol, false);
                if (!currentInSelection) {
                    bool b = signalsBlocked();
                    blockSignals(true);
                    clearSelection();
                    blockSignals(b);
                    currentSel = new MDATableSelection();
                    selections.append(currentSel);
                    currentSel->init(tmpRow, tmpCol);
                    repaintSelections(0, currentSel);
                    emit selectionChanged();
                }
            }
        }
    } else if (tmpRow != -1 && tmpCol != -1) {
        setCurrentCell(tmpRow, tmpCol, false, true);
    }
}

/*! \reimp
*/

void MDATable::focusInEvent(QFocusEvent*)
{
    d->inMenuMode = false;
    if (curRow == -1 && curCol == -1)
        return;
    updateCell(curRow, curCol);
    if (style()->styleHint(QStyle::SH_ItemView_ChangeHighlightOnFocus))
        repaintSelections();
}


/*! \reimp
*/

void MDATable::focusOutEvent(QFocusEvent *e)
{
    if (curRow != -1 && curCol != -1)
        updateCell(curRow, curCol);
    if (style()->styleHint(QStyle::SH_ItemView_ChangeHighlightOnFocus)) {
        d->inMenuMode =
            e->reason() == Qt::PopupFocusReason ||
            (qApp->focusWidget() && qApp->focusWidget()->inherits("QMenuBar"));
        if (!d->inMenuMode)
            repaintSelections();
    }
}

/*! \reimp
*/

QSize MDATable::sizeHint() const
{
    ensurePolished();

    QSize s = tableSize();
    QSize sh;
    if (s.width() < 500 && s.height() < 500) {
        sh = QSize(tableSize().width() + viewportMargins.left() + 5,
                    tableSize().height() + viewportMargins.top() + 5);
    } else {
            sh = QScrollArea::sizeHint();
            if (!topHeader->isHidden())
                sh.setHeight( sh.height() + viewportMargins.top());
            if (!leftHeader->isHidden())
                sh.setWidth(sh.width() + viewportMargins.left());
    }
    return sh;
}

/*! \reimp
*/

void MDATable::resizeEvent(QResizeEvent *e)
{
    QScrollArea::resizeEvent(e);
    updateScrollBars();
    updateGeometries();
}

/*!
 *  Updates the horizontal and vertical scrollbars' maximum values based
 *  on the table and viewport sizes. Additionally sets single step and
 *  page sizes to scroll a single or group of cells.
 */

void MDATable::updateScrollBars()
{
    const QSize scrollBounds(tableSize() - viewport()->size());
    horizontalScrollBar()->setMaximum(qMax(0, scrollBounds.width()));
    verticalScrollBar()->setMaximum(qMax(0, scrollBounds.height()));

    // A single step should scroll a single cell
    horizontalScrollBar()->setSingleStep(topHeader->sectionSize());
    verticalScrollBar()->setSingleStep(leftHeader->sectionSize());

    // A page step is typically 10x single step
    horizontalScrollBar()->setPageStep(10 * horizontalScrollBar()->singleStep());
    verticalScrollBar()->setPageStep(10 * verticalScrollBar()->singleStep());
}

/*! \reimp
*/

void MDATable::showEvent(QShowEvent *e)
{
    QScrollArea::showEvent(e);
    updateScrollBars();
    updateGeometries();
}

/*! \reimp
*/

void MDATable::paintEvent(QPaintEvent *e)
{
    QScrollArea::paintEvent(e);

    QPainter p(viewport());
    drawContents(&p, e->rect());
}

static bool inUpdateCell = false;

/*!
    Repaints the cell at \a row, \a col.
*/

void MDATable::updateCell(long long row, long long col)
{
    if (inUpdateCell || row < 0 || col < 0)
        return;
    inUpdateCell = true;
    QRect cg = cellGeometry(row, col);
    QRect r((QPoint(cg.x() - 2, cg.y() - 2)),
             QSize(cg.width() + 4, cg.height() + 4));
    viewport()->update(r);
    inUpdateCell = false;
}

void MDATable::repaintCell(long long row, long long col)
{
    if (row == -1 || col == -1)
        return;
    QRect cg = cellGeometry(row, col);
    QRect r(QPoint(cg.x() - 2, cg.y() - 2),
             QSize(cg.width() + 4, cg.height() + 4));
    viewport()->repaint(r);
}

/*!
    This function should be called whenever the column width of \a col
    has been changed. It updates the geometry of any affected columns
    and repaints the table to reflect the changes it has made.
*/

void MDATable::columnWidthChanged()
{
    updateScrollBars();
    viewport()->update();
    delayedUpdateGeometries();
}

/*!
    This function should be called whenever the row height of \a row
    has been changed. It updates the geometry of any affected rows and
    repaints the table to reflect the changes it has made.
*/

void MDATable::rowHeightChanged()
{
    updateScrollBars();
    viewport()->update();
    delayedUpdateGeometries();
}

static bool inUpdateGeometries = false;

void MDATable::delayedUpdateGeometries()
{
    d->geomTimer->start(0);
}

void MDATable::updateGeometriesSlot()
{
    updateGeometries();
}

/*!
    This function updates the geometries of the left and top header.
    You do not normally need to call this function.
*/

void MDATable::updateGeometries()
{
    if (inUpdateGeometries)
        return;
    inUpdateGeometries = true;
    QSize ts = tableSize();
    if (topHeader->offset() &&
         ts.width() < topHeader->offset() + topHeader->width())
        horizontalScrollBar()->setValue(ts.width() - topHeader->width());
    if (leftHeader->offset() &&
         ts.height() < leftHeader->offset() + leftHeader->height())
        verticalScrollBar()->setValue(ts.height() - leftHeader->height());

    leftHeader->setGeometry(QStyle::visualRect(layoutDirection(), rect(), QRect(frameWidth(), viewportMargins.top() + frameWidth(),
                             viewportMargins.left(), viewport()->height())));
    topHeader->setGeometry(QStyle::visualRect(layoutDirection(), rect(), QRect(viewportMargins.left() + frameWidth(), frameWidth(),
                                                      viewport()->width(), viewportMargins.top())));
    horizontalScrollBar()->raise();
    verticalScrollBar()->raise();
    inUpdateGeometries = false;
}

/*!
    Returns the width of column \a col.

    \sa setColumnWidth() rowHeight()
*/

int MDATable::columnWidth() const
{
    return topHeader->sectionSize();
}

/*!
    Returns the height of row \a row.

    \sa setRowHeight() columnWidth()
*/

int MDATable::rowHeight() const
{
    return leftHeader->sectionSize();
}

/*!
    Returns the x-coordinate of the column \a col in content
    coordinates.

    \sa columnAt() rowPos()
*/

int MDATable::columnPos(long long col) const
{
    return topHeader->sectionPos(col) - topHeader->offset();
}

/*!
    Returns the y-coordinate of the row \a row in content coordinates.

    \sa rowAt() columnPos()
*/

int MDATable::rowPos(long long row) const
{
    return leftHeader->sectionPos(row) - leftHeader->offset();
}

/*!
    Returns the number of the column at position \a x. \a x must be
    given in content coordinates.

    \sa columnPos() rowAt()
*/

long long MDATable::columnAt(int x) const
{
    return topHeader->sectionAt(topHeader->offset() + x);
}

/*!
    Returns the number of the row at position \a y. \a y must be given
    in content coordinates.

    \sa rowPos() columnAt()
*/

long long MDATable::rowAt(int y) const
{
    return leftHeader->sectionAt(leftHeader->offset() + y);
}

/*!
    Returns the bounding rectangle of the cell at \a row, \a col in
    content coordinates.
*/

QRect MDATable::cellGeometry(long long row, long long col) const
{
    int w = isColumnHidden(col) ? 0 : columnWidth();
    int h = isRowHidden(row) ? 0 : rowHeight();
    return QRect(columnPos(col), rowPos(row), w, h);
}

/*!
    Returns the size of the table.

    This is the same as the coordinates of the bottom-right edge of
    the last table cell.
*/

QSize MDATable::tableSize() const
{
    return QSize(topHeader->headerWidth(),
                  leftHeader->headerWidth());
}

/*!
    \property MDATable::numRows
    \brief The number of rows in the table

    \sa numCols
*/

long long MDATable::numRows() const
{
    return leftHeader->count();
}

/*!
    \property MDATable::numCols
    \brief The number of columns in the table

    \sa numRows
*/

long long MDATable::numCols() const
{
    return topHeader->count();
}

void MDATable::saveContents(QVector<MDATableItem*> &tmp)
{
    long long nCols = numCols();
    tmp.resize(contents.size());
    int i;
    for (i = 0; i < (int)tmp.size(); ++i) {
        MDATableItem *item = contents[ i ];
        if (item && (item->row() * nCols) + item->col() == i)
            tmp[i] = item;
        else
            tmp[i] = 0;
    }
}

void MDATable::updateHeaderAndResizeContents(MDATableHeader *header,
                                            long long num, long long rowCol,
                                            int /* width */, bool &updateBefore)
{
    updateBefore = rowCol < num;
    clearSelection(false);
    header->setCount(rowCol);

    sparseContents.clear();
    contents.clear();
    resizeData(numRows() * numCols());
}

void MDATable::restoreContents(QVector<MDATableItem*> &tmp)
{
    int i;
    long long nCols = numCols();
    for (i = 0; i < (int)tmp.size(); ++i) {
        MDATableItem *it = tmp[ i ];
        if (it) {
            int idx = (it->row() * nCols) + it->col();
            if (idx < contents.size() &&
                 it->row() == idx /  nCols && it->col() == idx % nCols) {
                contents[idx] = it;
            } else {
                delete it;
            }
        }
    }
}

void MDATable::finishContentsResze(bool /* updateBefore */)
{
    updateScrollBars();
    updateGeometries();
    viewport()->update();
}

void MDATable::setNumRows(long long r)
{
    if (r < 0)
        return;

    QVector<MDATableItem*> tmp;
    saveContents(tmp);

    bool updateBefore;
    updateHeaderAndResizeContents(leftHeader, numRows(), r, 20, updateBefore);

    restoreContents(tmp);

    finishContentsResze(updateBefore);

    if (curRow >= numRows())
        setCurrentCell(numRows() - 1, (numRows() == 0) ? - 1 : curCol);

    if (curRow == -1 && curCol == -1 &&
         numRows() > 0 && numCols () > 0) {
        setCurrentCell(0, 0);
    }
}

void MDATable::setNumCols(long long c)
{
    if (c < 0)
        return;

    QVector<MDATableItem*> tmp;
    saveContents(tmp);

    bool updateBefore;
    updateHeaderAndResizeContents(topHeader, numCols(), c, 100, updateBefore);

    restoreContents(tmp);

    finishContentsResze(updateBefore);

    if (curCol >= numCols())
        setCurrentCell((numCols() == 0) ? - 1 : curRow, numCols() - 1);
    if (curRow == -1 && curCol == -1 &&
         numRows() > 0 && numCols () > 0) {
        setCurrentCell(0, 0);
    }
}

/*!
    Returns a single integer which identifies a particular \a row and \a
    col by mapping the 2D table to a 1D array.

    This is useful, for example, if you have a sparse table and want to
    use a Q3IntDict to map integers to the cells that are used.
*/

long long MDATable::indexOf(long long row, long long col) const
{
    return (row * numCols()) + col;
}

/*! \internal
*/

void MDATable::repaintSelections(MDATableSelection *oldSelection,
                                MDATableSelection *newSelection,
                                bool /* updateVertical */, bool /* updateHorizontal */)
{
    if (!oldSelection && !newSelection)
        return;
    if (oldSelection && newSelection && *oldSelection == *newSelection)
        return;
    if (oldSelection && !oldSelection->isActive())
         oldSelection = 0;

    bool optimizeOld = false;
    bool optimizeNew = false;

    QRect old;
    if (oldSelection)
        old = rangeGeometry(oldSelection->topRow(),
                             oldSelection->leftCol(),
                             oldSelection->bottomRow(),
                             oldSelection->rightCol(),
                             optimizeOld);
    else
        old = QRect(0, 0, 0, 0);

    QRect cur;
    if (newSelection)
        cur = rangeGeometry(newSelection->topRow(),
                             newSelection->leftCol(),
                             newSelection->bottomRow(),
                             newSelection->rightCol(),
                             optimizeNew);
    else
        cur = QRect(0, 0, 0, 0);
    int i;

    if (!optimizeOld || !optimizeNew ||
         old.width() > SHRT_MAX || old.height() > SHRT_MAX ||
         cur.width() > SHRT_MAX || cur.height() > SHRT_MAX) {
        QRect rr = cur.united(old);
        viewport()->repaint(rr);
    } else {
        QRegion r1(old);
        QRegion r2(cur);
        QRegion r3 = r1.subtracted(r2);
        QRegion r4 = r2.subtracted(r1);

        foreach (const QRect& r, r3)
            viewport()->repaint(r);
        foreach (const QRect& r, r4)
            viewport()->repaint(r);
    }
}

/*!
    Repaints all selections
*/

void MDATable::repaintSelections()
{
    if (selections.isEmpty())
        return;

    QRect r;
    QListIterator<MDATableSelection*> it(selections);
    while (it.hasNext()) {
        MDATableSelection *s = it.next();
        bool b;
        r = r.united(rangeGeometry(s->topRow(),
                                    s->leftCol(),
                                    s->bottomRow(),
                                    s->rightCol(), b));
    }

    viewport()->repaint(r);
}

/*!
    Clears all selections and repaints the appropriate regions if \a
    repaint is true.

    \sa removeSelection()
*/

void MDATable::clearSelection(bool repaint)
{
    if (selections.isEmpty())
        return;

    QRect r;
    QListIterator<MDATableSelection*> it(selections);
    while (it.hasNext()) {
        MDATableSelection *s = it.next();
        bool b;
        r = r.united(rangeGeometry(s->topRow(),
                                   s->leftCol(),
                                   s->bottomRow(),
                                   s->rightCol(), b));
    }

    currentSel = 0;
    qDeleteAll(selections);
    selections.clear();

    if (repaint)
        viewport()->repaint(r);

    emit selectionChanged();
}

/*! \internal
*/

QRect MDATable::rangeGeometry(long long topRow, long long leftCol,
                              long long bottomRow, long long rightCol, bool &optimize)
{
    Q_ASSERT(topRow >= 0 && leftCol >= 0 && bottomRow < numRows() && rightCol < numCols());

    topRow = qMax(topRow, rowAt(0));
    leftCol = qMax(leftCol, columnAt(0));
    long long ra = rowAt(viewport()->height());
    if (ra != -1)
        bottomRow = qMin(bottomRow, ra);
    long long ca = columnAt(viewport()->width());
    if (ca != -1)
        rightCol = qMin(rightCol, ca);
    optimize = true;
    QRect rect;
    for (long long r = topRow; r <= bottomRow; ++r) {
        for (long long c = leftCol; c <= rightCol; ++c) {
            rect = rect.united(cellGeometry(r, c));
        }
    }
    return rect;
}

/*!
    This function is called to activate the next cell if in-place
    editing was finished by pressing the Enter key.

    The default behaviour is to move from top to bottom, i.e. move to
    the cell beneath the cell being edited. Reimplement this function
    if you want different behaviour, e.g. moving from left to right.
*/

void MDATable::activateNextCell()
{
    if (curRow == -1 && curCol == -1)
        return;

    long long firstRow = 0;
    while (isRowHidden(firstRow))
        ++firstRow;
    long long firstCol = 0;
    while (isColumnHidden(firstCol))
        ++firstCol;
    long long nextRow = curRow;
    long long nextCol = curCol;
    while (isRowHidden(++nextRow)) {}
    if (nextRow >= numRows()) {
        nextRow = firstRow;
        while (isColumnHidden(++nextCol)) {}
        if (nextCol >= numCols())
            nextCol = firstCol;
    }

    if (!currentSel || !currentSel->isActive() ||
         (currentSel->leftCol() == currentSel->rightCol() &&
           currentSel->topRow() == currentSel->bottomRow())) {
        clearSelection();
        setCurrentCell(nextRow, nextCol);
    } else {
        if (curRow < currentSel->bottomRow())
            setCurrentCell(nextRow, curCol);
        else if (curCol < currentSel->rightCol())
            setCurrentCell(currentSel->topRow(), nextCol);
        else
            setCurrentCell(currentSel->topRow(), currentSel->leftCol());
    }

}

/*! \internal
*/

void MDATable::fixRow(long long &row, int y)
{
    if (numRows() == 0) {
        row = -1;
        return;
    }
    if (row == -1) {
        if (y < 0)
            row = 0;
        else
            row = numRows() - 1;
    }
}

/*! \internal
*/

void MDATable::fixCol(long long &col, int x)
{
    if (numCols() == 0) {
        col = -1;
        return;
    }
    if (col == -1) {
        if (x < 0)
            col = 0;
        else
            col = numCols() - 1;
    }
}

/*!
    Hides row \a row.

    \sa showRow() hideColumn()
*/

void MDATable::hideRow(long long row)
{
    leftHeader->hideSection(row);
    if (curRow == row) {
        long long r = curRow;
        long long c = curCol;
        int k = (r >= numRows() - 1 ? Key_Up : Key_Down);
        fixCell(r, c, k);
        if (numRows() > 0)
            setCurrentCell(r, c);
    }
    rowHeightChanged();
}

/*!
    Hides column \a col.

    \sa showColumn() hideRow()
*/

void MDATable::hideColumn(long long col)
{
    topHeader->hideSection(col);
    if (curCol == col) {
        long long r = curRow;
        long long c = curCol;
        int k = (c >= numCols() - 1 ? Key_Left : Key_Right);
        fixCell(r, c, k);
        if (numCols() > 0)
            setCurrentCell(r, c);
    }
    columnWidthChanged();
}


/*!
    Shows row \a row.

    \sa hideRow() showColumn()
*/

void MDATable::showRow(long long row)
{
    leftHeader->showSection(row);
    rowHeightChanged();
}

/*!
    Shows column \a col.

    \sa hideColumn() showRow()
*/

void MDATable::showColumn(long long col)
{
    topHeader->showSection(col);
    columnWidthChanged();
}

void MDATable::hideRows(long long from, long long to)
{
    leftHeader->hideSections(from, to);
    if (curRow >= from && curRow <= to) {
        long long r = curRow;
        long long c = curCol;
        int k = (r >= numRows() - 1 ? Key_Up : Key_Down);
        fixCell(r, c, k);
        if (numRows() > 0)
            setCurrentCell(r, c);
    }
    rowHeightChanged();
}

void MDATable::hideColumns(long long from, long long to)
{
    topHeader->hideSections(from, to);
    if (curCol >= from && curCol <= to) {
        long long r = curRow;
        long long c = curCol;
        int k = (c >= numCols() - 1 ? Key_Left : Key_Right);
        fixCell(r, c, k);
        if (numCols() > 0)
            setCurrentCell(r, c);
    }
    columnWidthChanged();
}

void MDATable::showRows(long long from, long long to)
{
    leftHeader->showSections(from, to);
    rowHeightChanged();
}

void MDATable::showColumns(long long from, long long to)
{
    topHeader->showSections(from, to);
    columnWidthChanged();
}

/*!
    Returns true if row \a row is hidden; otherwise returns
    false.

    \sa hideRow(), isColumnHidden()
*/
bool MDATable::isRowHidden(long long row) const
{
    return leftHeader->isSectionHidden(row);
}

/*!
    Returns true if column \a col is hidden; otherwise returns
    false.

    \sa hideColumn(), isRowHidden()
*/
bool MDATable::isColumnHidden(long long col) const
{
    return topHeader->isSectionHidden(col);
}

/*!
    Resizes column \a col to be \a w pixels wide.

    \sa columnWidth() setRowHeight()
*/

void MDATable::setColumnWidth(int w)
{
    topHeader->resizeSections(w);
}

/*!
    Resizes row \a row to be \a h pixels high.

    \sa rowHeight() setColumnWidth()
*/

void MDATable::setRowHeight(int h)
{
    leftHeader->resizeSections(h);
}

/*!
    Resizes column \a col so that the column width is wide enough to
    display the widest item the column contains.

    \sa adjustRow()
*/

void MDATable::adjustColumnWidth()
{
    int w = 20;
    w = qMax(w, maxColWidth);
    setColumnWidth(w);
}

/*!
    Takes the table item \a i out of the table. This function does \e
    not delete the table item. You must either delete the table item
    yourself or put it into a table (using setItem()) which will then
    take ownership of it.

    Use this function if you want to move an item from one cell in a
    table to another, or to move an item from one table to another,
    reinserting the item with setItem().

    If you want to exchange two cells use swapCells().
*/

void MDATable::takeItem(MDATableItem *i)
{
    if (!i)
        return;
    QRect rect = cellGeometry(i->row(), i->col());
    if (isSparse()) {
        sparseContents.remove(indexOf(i->row(), i->col()));
    } else {
        contents.remove(indexOf(i->row(), i->col()));
    }
    viewport()->repaint(rect);
    i->setRow(-1);
    i->setCol(-1);
    i->t = 0;
}

void MDATable::changeEvent(QEvent *event)
{
    QScrollArea::changeEvent(event);

    if (!isVisible() || event->type() != QEvent::ActivationChange)
        return;

    if (!isActiveWindow() && autoScrollTimer)
        autoScrollTimer->stop();

    if (palette().color(QPalette::Active, QPalette::Window) != palette().color(QPalette::Inactive, QPalette::Window))
        viewport()->update();

}

void MDATable::clearData()
{
    clearSelection(false);
    foreach (MDATableItem *item, sparseContents)
        delete item;
    sparseContents.clear();
    qDeleteAll(contents);
    contents.clear();
    maxColWidth = 0;
    validRegion = QRegion();

    update();
}

void MDATable::clear()
{
    sparse = false;

    clearSelection(false);
    leftHeader->clear();
    topHeader->clear();

    foreach (MDATableItem *item, sparseContents)
        delete item;
    sparseContents.clear();
    qDeleteAll(contents);
    contents.clear();
    resizeData(0);
    validRegion = QRegion();

    maxColWidth = 0;

    finishContentsResze(true);

    curCol = -1;
    curRow = -1;
}

void MDATable::setSparse(bool s)
{
    Q_ASSERT(!s || (numRows() == 0 && numCols() == 0));

    bool old = sparse;
    sparse = s;
    if (old && !sparse) {
        if ((int)contents.size() != numRows() * numCols())
            resizeData(numRows() * numCols());

        long long cols = numCols();

        for (QMap<long long, MDATableItem *>::const_iterator it(sparseContents.begin()); it != sparseContents.end(); ++it) {
            long long key = it.key();
            long long row = key / cols;
            long long col = key % cols;
            contents[ static_cast<int>(indexOf(row, col)) ] = it.value();
        }

        sparseContents.clear();
    }
}

bool MDATable::isSparse() const
{
    return sparse;
}

void MDATable::setLeftHeaderLines(int numLines)
{
    leftHeader->setNumLines(numLines);
}
void MDATable::setTopHeaderLines(int numLines)
{
    topHeader->setNumLines(numLines);
}
void MDATable::setLeftHeaderLineNameAndBounds(int line, const QString& name, long long min, long long max)
{
    leftHeader->setLineNameAndBounds(line, name, min, max);
}
void MDATable::setTopHeaderLineNameAndBounds(int line, const QString& name, long long min, long long max)
{
    topHeader->setLineNameAndBounds(line, name, min, max);
}

void MDATable::addValidRegion(const QRegion& r)
{
    validRegion |= r;
}

/*
    \class MDATableHeader
    \brief The MDATableHeader class allows for creation and manipulation
    of table headers.

    \compat

   MDATable uses this subclass of MDAHeader for its headers. MDATable has a
   horizontalHeader() for displaying column labels, and a
   verticalHeader() for displaying row labels.

*/

/*!
    Creates a new table header called \a name with \a i sections. It
    is a child of widget \a parent and attached to table \a t.
*/

MDATableHeader::MDATableHeader(MDATable *t,
                            QWidget *parent, const char *name)
    : QWidget(parent),
      table(t)
{
    setObjectName(name);
    orient = Horizontal;
    init(0);
}

MDATableHeader::MDATableHeader(long long i, MDATable *t,
                            QWidget *parent, const char *name)
    : QWidget(parent),
      table(t)
{
    setObjectName(name);
    orient = Horizontal;
    init(i);
}

void MDATableHeader::init(long long i)
{
    Q_ASSERT(i >= 0);

    initialised = false;
    fixedExtent = 0;
    sectionCount = i;
    offs = 0;
    sectionSz = 20;
    setBackgroundRole(QPalette::Button);
    setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));

    setNumLines(0);

    initialised = true;
    nameWidth=  0;
    nameHeight = fontMetrics().height();
}

void MDATableHeader::setCount(long long n)
{
    Q_ASSERT(n >= 0);

    sectionCount = n;
    updateSpans();
}

/*! \reimp
*/

void MDATableHeader::paintEvent(QPaintEvent *e)
{
    QPainter p(this);
    p.setPen(palette().buttonText().color());
    int pos = orientation() == Horizontal
                     ? e->rect().left()
                     : e->rect().top();
    long long index = sectionAt(pos + offset());
    if (index < 0) {
       if (pos > 0)
            return;
       else
            index = 0;
    }

    int numLines = bounds.size();
    for (int line = 0; line < numLines; ++line) {
        long long span = bounds[line].span;
        long long mod = bounds[line].max - bounds[line].min + 1;
        long long min = bounds[line].min;

        if (span == 0) continue;

        index /= span;

        long long lim = (count() + span - 1) / span;
        for ( long long i = index; i < lim; ++i) {
            long long index1 = i * span;
            long long index2 = index1 + span - 1;
            long long n = (i % mod) + min;
	    QRect r = sRect(line, index1, index2);
	    p.save();

	    paintSection(&p, index1, index2, r, QString::number(n));
	    p.restore();
	    if ((orientation() == Horizontal && r. right() >= e->rect().right())
	         || (orientation() == Vertical && r. bottom() >= e->rect().bottom()))
	         break;
        }

        if (nameWidth > 0 && nameHeight > 0) { // don't show an ugly thin line if no headers are set
            QRect r = nameRect(line);
            if (r.height() > 0 && r.width() > 0) {
                p.save();
                paintName(&p, r, bounds[line].name);
                p.restore();
            }
        }
    }
}

/*!
    \reimp

    Paints the header section with index \a index into the rectangular
    region \a fr on the painter \a p.
*/

void MDATableHeader::paintSection(QPainter *p, long long section1, long long section2, const QRect& fr, QString label)
{
    Q_ASSERT(section1 >= 0 && section2 >= 0 && section1 < count() && section2 < count());

    if (isSectionHidden(section1, section2))
        return;

    QStyleOptionHeader opt;
    opt.palette = palette();
    opt.rect = fr;
    opt.state = QStyle::State_Off | (orient == Qt::Horizontal ? QStyle::State_Horizontal
                                                              : QStyle::State_None);
    if (isEnabled())
        opt.state |= QStyle::State_Enabled;

    if (!(opt.state & QStyle::State_Sunken))
        opt.state |= QStyle::State_Raised;
    opt.section = static_cast<int>(qMin(section1, static_cast<long long>(INT_MAX)));
    if (count() == 1)
        opt.position = QStyleOptionHeader::OnlyOneSection;
    else if (section1 == 0)
        opt.position = QStyleOptionHeader::Beginning;
    else if (section2 == count() - 1)
        opt.position = QStyleOptionHeader::End;
    else
        opt.position = QStyleOptionHeader::Middle;
    opt.selectedPosition = QStyleOptionHeader::NotAdjacent;

    style()->drawControl(QStyle::CE_HeaderSection, &opt, p, this);
    paintSectionLabel(p, fr, label);
}

/*!
    Paints the label of the section at position \a index, inside
    rectangle \a fr (which uses widget coordinates) using painter \a
    p.

    Called by paintSection()
*/
void MDATableHeader::paintSectionLabel(QPainter *p,  const QRect& fr, QString label)
{
    int dx = 0, dy = 0;
    int x = fr.x(), y = fr.y();
    int w = fr.width(), h = fr.height();
    if (orient == Horizontal) {
        x = qMin(qMax(0, fr.x()), fr.x() + fr.width() - sectionSize());
        w = fr.x() + fr.width() - x;
    } else {
        y = qMin(qMax(0, fr.y()), fr.y() + fr.height() - sectionSize());
        h = fr.y() + fr.height() - y;
    }
    QRect r(x + style()->pixelMetric(QStyle::PM_HeaderMargin) + dx, y + 2 + dy,
             w - 6, h - 4);

    p->save();
    p->setPen(palette().text().color());
    p->drawText(r, Qt::AlignLeft | Qt::TextSingleLine, label);
    p->restore();
}

void MDATableHeader::paintName(QPainter *p, const QRect& fr, QString name)
{
    QStyleOptionHeader opt;
    opt.palette = palette();
    opt.rect = fr;
    opt.state = QStyle::State_Off | (orient == Qt::Horizontal ? QStyle::State_Horizontal
                                                              : QStyle::State_None);
    if (isEnabled())
        opt.state |= QStyle::State_Enabled;
    if (!(opt.state & QStyle::State_Sunken))
        opt.state |= QStyle::State_Raised;
    opt.position = QStyleOptionHeader::OnlyOneSection;
    opt.selectedPosition = QStyleOptionHeader::NotAdjacent;

    style()->drawControl(QStyle::CE_HeaderSection, &opt, p, this);
    paintSectionLabel(p, fr, name);
}

/*!
    \reimp

    Returns the size of section \a section in pixels or -1 if \a
    section is out of range.
*/

int MDATableHeader::sectionSize() const
{
    return sectionSz;
}

void MDATableHeader::resizeSections(int s)
{
    Q_ASSERT(s >= 0);

    if (sectionSz != s) {
        sectionSz = s;
        update();
        emit sectionSizeChanged();
    }
}

/*!
    \reimp

    Returns the start position of section \a section in pixels or -1
    if \a section is out of range.

    \sa sectionAt()
*/

int MDATableHeader::sectionPos(long long section) const
{
    Q_ASSERT(section >= 0 && section < count());

    long long pos = map.sectionPos(section) * sectionSize();
    return static_cast<int>(qMin(pos, static_cast<long long>(INT_MAX - 32768)));
}

/*!
    \reimp

    Returns the number of the section at index position \a pos or -1
    if there is no section at the position given.

    \sa sectionPos()
*/

long long MDATableHeader::sectionAt(int pos) const
{
    if (pos < 0)
        return -1;

    long long section = map.sectionAt(pos / sectionSize());
    if (section >= count())
        return -1;

    return section;
}

int MDATableHeader::headerWidth() const
{
    long long width = map.sectionPos(count()) * sectionSize();
    return static_cast<int>(qMin(width, static_cast<long long>(INT_MAX - 32768)));
}

void MDATableHeader::setNumLines(int i)
{
    Q_ASSERT(i >= 0);

    bounds.resize(i);
    updateSpans();
}

int MDATableHeader::numLines() const
{
    return bounds.size();
}

void MDATableHeader::setLineNameAndBounds(int i, const QString& name, long long min, long long max)
{
    Q_ASSERT(i >= 0 && i < (int)bounds.size());

    bounds[i].name = name;
    bounds[i].min = min;
    bounds[i].max = max;
    updateSpans();
}

void MDATableHeader::updateSpans()
{
    long long span = 1;
    int maxw = 0;
    QFontMetrics fm = fontMetrics();
    nameWidth = 0;
    for (int i = 0; i < bounds.size(); ++i) {
        bounds[i].span = span;
        span *= bounds[i].max - bounds[i].min + 1;
        int w = fm.horizontalAdvance(QString::number(bounds[i].max) + 'W') + 6;
        maxw = qMax(maxw, w);
        w = fm.horizontalAdvance(bounds[i].name) + 6;
        nameWidth = qMax(nameWidth, w);
    }

    if (initialised) {
        if (orientation() == Qt::Vertical) {
            int s = qMax((maxw + nameWidth) * bounds.size(), 40 * bounds.size());
            if (s != fixedExtent) {
                fixedExtent = s;
                emit fixedExtentChanged(fixedExtent);
            }

            int h = qMax(20, fontMetrics().height() + 6);
            resizeSections(h);
        } else {
            int s = (fontMetrics().height() + 4 + nameHeight + 4) * bounds.size();
            if (s != fixedExtent) {
                fixedExtent = s;
                emit fixedExtentChanged(fixedExtent);
            }

            int w = 30;
            if (!bounds.isEmpty())
                w = qMax(w, fontMetrics().horizontalAdvance(QString::number(bounds[0].max) + 'W') + 6);
            table->maxColWidth = qMax(table->maxColWidth, w);
            table->adjustColumnWidth();
        }
    }

    update();
}

QRect MDATableHeader::sRect(int line, long long index1, long long index2)
{
    Q_ASSERT(index1 >= 0 && index2 >= 0 && index1 < count() && index2 < count());

    int start = sectionPos(index1);
    int end = sectionPos(index2);
    end += (isSectionHidden(index2) ? 0 : sectionSize());
    int numLines = bounds.size();

    if (orientation() == Qt::Horizontal)
        return QRect(start - offset(), fixedExtent * (numLines - line - 1) / numLines + nameHeight + 4, end - start, fixedExtent / numLines - nameHeight - 4);
    else
        return QRect(fixedExtent * (numLines - line - 1) / numLines + nameWidth, start - offset(), fixedExtent / numLines - nameWidth, end - start);
}

QRect MDATableHeader::sRect(long long index)
{
    Q_ASSERT(index >= 0 && index < count());

    int numLines = bounds.size();
    for (int line = 0; line < numLines; ++line)
        index /= bounds[line].span;

    long long span = bounds[numLines - 1].span;
    long long index1 = index * span;
    long long index2 = index1 + span - 1;

    int start = sectionPos(index1);
    int end = sectionPos(index2);
    end += (isSectionHidden(index2) ? 0 : sectionSize());

    if (orientation() == Horizontal)
        return QRect(start - offset(), 0, end - start, fixedExtent);
    else
        return QRect(0, start - offset(), fixedExtent, end - start);
}

QRect MDATableHeader::nameRect(int line)
{
    int numLines = bounds.size();

    if (orientation() == Qt::Horizontal)
        return QRect(0, fixedExtent * (numLines - line - 1) / numLines, qMin(headerWidth(), width() + 4), nameHeight + 4);
    else
        return QRect(fixedExtent * (numLines - line - 1) / numLines, 0, nameWidth, qMin(headerWidth(), height() + 4));
}

void MDATableHeader::clear()
{
    sectionCount = 0;
    map.clear();
    setNumLines(0);
}

void MDATableHeader::setOrientation(Qt::Orientation orientation)
{
    if (orient == orientation)
        return;
    orient = orientation;
    if (orient == Horizontal)
        setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));
    else
        setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred));
    update();
    updateGeometry();
}

Qt::Orientation MDATableHeader::orientation() const
{
    return orient;
}

bool MDATableHeader::isSectionHidden(long long s, long long e) const
{
    Q_ASSERT(s>= 0 && e >= 0 && s < count() && e < count());

    return map.isSectionHidden(s, e);
}

bool MDATableHeader::isSectionHidden(long long s) const
{
    Q_ASSERT(s >= 0 && s < count());

    return map.isSectionHidden(s);
}

bool MDATableHeader::isSectionValid(long long s)
{
    return s >= 0 && s < count();
}

bool MDATableHeader::isSectionValid(long long s, long long e)
{
    return s>= 0 && e >= 0 && s < count() && e < count();
}

void MDATableHeader::hideSection(long long s)
{
    Q_ASSERT(s >= 0 && s < count());

    map.hideSection(s);
    if (orient == Horizontal) {
        int x = sectionPos(s) - offset();
        if (x < width())
            update( x, 0, width() - x, fixedExtent);
    } else {
        int y = sectionPos(s) - offset();
        if (y < height())
            update(0, y, fixedExtent, height() - y);
    }
}

void MDATableHeader::showSection(long long s)
{
    Q_ASSERT(s >= 0 && s < count());

    map.showSection(s);
    if (orient == Horizontal) {
        int x = sectionPos(s) - offset();
        if (x < width())
            update(x, 0, width() - x, fixedExtent);
    } else {
        int y = sectionPos(s) - offset();
        if (y < height())
            update(0, y, fixedExtent, height() - y);
    }
}

void MDATableHeader::hideSections(long long s, long long e)
{
    Q_ASSERT(s >= 0 && s < count());
    Q_ASSERT(e >= 0 && e < count());
    Q_ASSERT(e >= s);

    map.hideSections(s, e);
    if (orient == Horizontal) {
        int x = sectionPos(s) - offset();
        if (x < width())
            update(x, 0, width() - x, fixedExtent);
    } else {
        int y = sectionPos(s) - offset();
        if (y < height())
            update(0, y, fixedExtent, height() - y);
    }
}

void MDATableHeader::showSections(long long s, long long e)
{
    Q_ASSERT(s >= 0 && s < count());
    Q_ASSERT(e >= 0 && e < count());
    Q_ASSERT(e >= s);

    map.showSections(s, e);
    if (orient == Horizontal) {
        int x = sectionPos(s) - offset();
        if (x < width())
            update(x, 0, width() - x, fixedExtent);
    } else {
        int y = sectionPos(s) - offset();
        if (y < height())
            update(0, y, fixedExtent, height() - y);
    }
}

QSize MDATableHeader::sizeHint() const
{
    int width, height;
    if (orient == Horizontal) {
        height = fixedExtent;
        width = headerWidth();
    } else {
        width = fixedExtent;
        height = headerWidth();
    }

    return QSize(width, height);
}

/*!
    \property QHeader::offset
    \brief the header's left-most (or top-most) visible pixel

    Setting this property will scroll the header so that \e offset
    becomes the left-most (or top-most for vertical headers) visible
    pixel.
*/
int MDATableHeader::offset() const
{
    return offs;
}

void MDATableHeader::setOffset(int x)
{
    int oldOff = offset();
    offs = x;
    if (headerWidth() < (orient == Horizontal ? width() : height()))
        offs = 0;
    if (bounds.size() > 1) {
        int numLines = bounds.size();
        if (orient == Horizontal) {
            QRect r(0, fixedExtent * (numLines - 1) / numLines, width(), fixedExtent / numLines);
            scroll(oldOff - offset(), 0, r);
            r = QRect(0, 0, width(), fixedExtent * (numLines - 1) / numLines);
            repaint(r);
        } else {
            QRect r(fixedExtent * (numLines - 1) / numLines, 0, fixedExtent / numLines, height());
            scroll(0, oldOff - offset(), r);
            r = QRect(0, 0, fixedExtent * (numLines - 1) / numLines, height());
            repaint(r);
        }        
    } else {
        if (orient == Horizontal)
            scroll(oldOff - offset(), 0);
        else
            scroll(0, oldOff - offset());
    }
}

/*! \reimp
*/

void MDATableHeader::resizeEvent(QResizeEvent *e)
{
    if (e)
        QWidget::resizeEvent(e);

    if (headerWidth() < width())
        offs = 0;
}

/*!
    \property Q3Header::count
    \brief the number of sections in the header
*/

long long MDATableHeader::count() const
{
    return sectionCount;
}

#include "mdatable.moc"
