text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    A subclass of this is used to drive a ListBox.

    @see ListBox
*/
class JUCE_API  ListBoxModel
{
public:
    //==============================================================================
    /** Destructor. */
    virtual ~ListBoxModel()  {}

    //==============================================================================
    /** This has to return the number of items in the list.
        @see ListBox::getNumRows()
    */
    virtual int getNumRows() = 0;

    /** This method must be implemented to draw a row of the list.
        Note that the rowNumber value may be greater than the number of rows in your
        list, so be careful that you don't assume it's less than getNumRows().
    */
    virtual void paintListBoxItem (int rowNumber,
                                   Graphics& g,
                                   int width, int height,
                                   bool rowIsSelected) = 0;

    /** This is used to create or update a custom component to go in a row of the list.

        Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
        and handle mouse clicks with listBoxItemClicked().

        This method will be called whenever a custom component might need to be updated - e.g.
        when the list is changed, or ListBox::updateContent() is called.

        If you don't need a custom component for the specified row, then return nullptr.
        (Bear in mind that even if you're not creating a new component, you may still need to
        delete existingComponentToUpdate if it's non-null).

        If you do want a custom component, and the existingComponentToUpdate is null, then
        this method must create a suitable new component and return it.

        If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
        by this method. In this case, the method must either update it to make sure it's correctly representing
        the given row (which may be different from the one that the component was created for), or it can
        delete this component and return a new one.

        The component that your method returns will be deleted by the ListBox when it is no longer needed.

        Bear in mind that if you put a custom component inside the row but still want the
        listbox to automatically handle clicking, selection, etc, then you'll need to make sure
        your custom component doesn't intercept all the mouse events that land on it, e.g by
        using Component::setInterceptsMouseClicks().
    */
    virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
                                               Component* existingComponentToUpdate);

    /** This can be overridden to react to the user clicking on a row.
        @see listBoxItemDoubleClicked
    */
    virtual void listBoxItemClicked (int row, const MouseEvent&);

    /** This can be overridden to react to the user double-clicking on a row.
        @see listBoxItemClicked
    */
    virtual void listBoxItemDoubleClicked (int row, const MouseEvent&);

    /** This can be overridden to react to the user clicking on a part of the list where
        there are no rows.
        @see listBoxItemClicked
    */
    virtual void backgroundClicked (const MouseEvent&);

    /** Override this to be informed when rows are selected or deselected.

        This will be called whenever a row is selected or deselected. If a range of
        rows is selected all at once, this will just be called once for that event.

        @param lastRowSelected      the last row that the user selected. If no
                                    rows are currently selected, this may be -1.
    */
    virtual void selectedRowsChanged (int lastRowSelected);

    /** Override this to be informed when the delete key is pressed.

        If no rows are selected when they press the key, this won't be called.

        @param lastRowSelected   the last row that had been selected when they pressed the
                                 key - if there are multiple selections, this might not be
                                 very useful
    */
    virtual void deleteKeyPressed (int lastRowSelected);

    /** Override this to be informed when the return key is pressed.

        If no rows are selected when they press the key, this won't be called.

        @param lastRowSelected   the last row that had been selected when they pressed the
                                 key - if there are multiple selections, this might not be
                                  very useful
    */
    virtual void returnKeyPressed (int lastRowSelected);

    /** Override this to be informed when the list is scrolled.

        This might be caused by the user moving the scrollbar, or by programmatic changes
        to the list position.
    */
    virtual void listWasScrolled();

    /** To allow rows from your list to be dragged-and-dropped, implement this method.

        If this returns a non-null variant then when the user drags a row, the listbox will
        try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
        a drag-and-drop operation, using this string as the source description, with the listbox
        itself as the source component.

        @see DragAndDropContainer::startDragging
    */
    virtual var getDragSourceDescription (const SparseSet<int>& rowsToDescribe);

    /** You can override this to provide tool tips for specific rows.
        @see TooltipClient
    */
    virtual String getTooltipForRow (int row);

    /** You can override this to return a custom mouse cursor for each row. */
    virtual MouseCursor getMouseCursorForRow (int row);

private:
   #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
    // This method's signature has changed to take a MouseEvent parameter - please update your code!
    JUCE_DEPRECATED_WITH_BODY (virtual int backgroundClicked(), { return 0; })
   #endif
};

//==============================================================================
/**
    A list of items that can be scrolled vertically.

    To create a list, you'll need to create a subclass of ListBoxModel. This can
    either paint each row of the list and respond to events via callbacks, or for
    more specialised tasks, it can supply a custom component to fill each row.

    @see ComboBox, TableListBox
*/
class JUCE_API  ListBox  : public Component,
                           public SettableTooltipClient
{
public:
    //==============================================================================
    /** Creates a ListBox.

        The model pointer passed-in can be null, in which case you can set it later
        with setModel().
    */
    ListBox (const String& componentName = String(),
             ListBoxModel* model = nullptr);

    /** Destructor. */
    ~ListBox();

    //==============================================================================
    /** Changes the current data model to display. */
    void setModel (ListBoxModel* newModel);

    /** Returns the current list model. */
    ListBoxModel* getModel() const noexcept                     { return model; }

    //==============================================================================
    /** Causes the list to refresh its content.

        Call this when the number of rows in the list changes, or if you want it
        to call refreshComponentForRow() on all the row components.

        This must only be called from the main message thread.
    */
    void updateContent();

    //==============================================================================
    /** Turns on multiple-selection of rows.

        By default this is disabled.

        When your row component gets clicked you'll need to call the
        selectRowsBasedOnModifierKeys() method to tell the list that it's been
        clicked and to get it to do the appropriate selection based on whether
        the ctrl/shift keys are held down.
    */
    void setMultipleSelectionEnabled (bool shouldBeEnabled) noexcept;

    /** If enabled, this makes the listbox flip the selection status of
        each row that the user clicks, without affecting other selected rows.

        (This only has an effect if multiple selection is also enabled).
        If not enabled, you can still get the same row-flipping behaviour by holding
        down CMD or CTRL when clicking.
    */
    void setClickingTogglesRowSelection (bool flipRowSelection) noexcept;

    /** Sets whether a row should be selected when the mouse is pressed or released.
        By default this is true, but you may want to turn it off.
    */
    void setRowSelectedOnMouseDown (bool isSelectedOnMouseDown) noexcept;

    /** Makes the list react to mouse moves by selecting the row that the mouse if over.

        This function is here primarily for the ComboBox class to use, but might be
        useful for some other purpose too.
    */
    void setMouseMoveSelectsRows (bool shouldSelect);

    //==============================================================================
    /** Selects a row.

        If the row is already selected, this won't do anything.

        @param rowNumber                the row to select
        @param dontScrollToShowThisRow  if true, the list's position won't change; if false and
                                        the selected row is off-screen, it'll scroll to make
                                        sure that row is on-screen
        @param deselectOthersFirst      if true and there are multiple selections, these will
                                        first be deselected before this item is selected
        @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
             deselectAllRows, selectRangeOfRows
    */
    void selectRow (int rowNumber,
                    bool dontScrollToShowThisRow = false,
                    bool deselectOthersFirst = true);

    /** Selects a set of rows.

        This will add these rows to the current selection, so you might need to
        clear the current selection first with deselectAllRows()

        @param firstRow                       the first row to select (inclusive)
        @param lastRow                        the last row to select (inclusive)
        @param dontScrollToShowThisRange      if true, the list's position won't change; if false and
                                              the selected range is off-screen, it'll scroll to make
                                              sure that the range of rows is on-screen
    */
    void selectRangeOfRows (int firstRow,
                            int lastRow,
                            bool dontScrollToShowThisRange = false);

    /** Deselects a row.
        If it's not currently selected, this will do nothing.
        @see selectRow, deselectAllRows
    */
    void deselectRow (int rowNumber);

    /** Deselects any currently selected rows.
        @see deselectRow
    */
    void deselectAllRows();

    /** Selects or deselects a row.
        If the row's currently selected, this deselects it, and vice-versa.
    */
    void flipRowSelection (int rowNumber);

    /** Returns a sparse set indicating the rows that are currently selected.
        @see setSelectedRows
    */
    SparseSet<int> getSelectedRows() const;

    /** Sets the rows that should be selected, based on an explicit set of ranges.

        If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
        method will be called. If it's false, no notification will be sent to the model.

        @see getSelectedRows
    */
    void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
                          NotificationType sendNotificationEventToModel = sendNotification);

    /** Checks whether a row is selected.
    */
    bool isRowSelected (int rowNumber) const;

    /** Returns the number of rows that are currently selected.
        @see getSelectedRow, isRowSelected, getLastRowSelected
    */
    int getNumSelectedRows() const;

    /** Returns the row number of a selected row.

        This will return the row number of the Nth selected row. The row numbers returned will
        be sorted in order from low to high.

        @param index    the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
        @returns        the row number, or -1 if the index was out of range or if there aren't any rows
                        selected
        @see getNumSelectedRows, isRowSelected, getLastRowSelected
    */
    int getSelectedRow (int index = 0) const;

    /** Returns the last row that the user selected.

        This isn't the same as the highest row number that is currently selected - if the user
        had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.

        If nothing is selected, it will return -1.
    */
    int getLastRowSelected() const;

    /** Multiply-selects rows based on the modifier keys.

        If no modifier keys are down, this will select the given row and
        deselect any others.

        If the ctrl (or command on the Mac) key is down, it'll flip the
        state of the selected row.

        If the shift key is down, it'll select up to the given row from the
        last row selected.

        @see selectRow
    */
    void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
                                        ModifierKeys modifiers,
                                        bool isMouseUpEvent);

    //==============================================================================
    /** Scrolls the list to a particular position.

        The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
        1.0 scrolls to the bottom.

        If the total number of rows all fit onto the screen at once, then this
        method won't do anything.

        @see getVerticalPosition
    */
    void setVerticalPosition (double newProportion);

    /** Returns the current vertical position as a proportion of the total.

        This can be used in conjunction with setVerticalPosition() to save and restore
        the list's position. It returns a value in the range 0 to 1.

        @see setVerticalPosition
    */
    double getVerticalPosition() const;

    /** Scrolls if necessary to make sure that a particular row is visible. */
    void scrollToEnsureRowIsOnscreen (int row);

    /** Returns a reference to the vertical scrollbar. */
    ScrollBar& getVerticalScrollBar() const noexcept;

    /** Returns a reference to the horizontal scrollbar. */
    ScrollBar& getHorizontalScrollBar() const noexcept;

    /** Finds the row index that contains a given x,y position.
        The position is relative to the ListBox's top-left.
        If no row exists at this position, the method will return -1.
        @see getComponentForRowNumber
    */
    int getRowContainingPosition (int x, int y) const noexcept;

    /** Finds a row index that would be the most suitable place to insert a new
        item for a given position.

        This is useful when the user is e.g. dragging and dropping onto the listbox,
        because it lets you easily choose the best position to insert the item that
        they drop, based on where they drop it.

        If the position is out of range, this will return -1. If the position is
        beyond the end of the list, it will return getNumRows() to indicate the end
        of the list.

        @see getComponentForRowNumber
    */
    int getInsertionIndexForPosition (int x, int y) const noexcept;

    /** Returns the position of one of the rows, relative to the top-left of
        the listbox.

        This may be off-screen, and the range of the row number that is passed-in is
        not checked to see if it's a valid row.
    */
    Rectangle<int> getRowPosition (int rowNumber,
                                   bool relativeToComponentTopLeft) const noexcept;

    /** Finds the row component for a given row in the list.

        The component returned will have been created using ListBoxModel::refreshComponentForRow().

        If the component for this row is off-screen or if the row is out-of-range,
        this will return nullptr.

        @see getRowContainingPosition
    */
    Component* getComponentForRowNumber (int rowNumber) const noexcept;

    /** Returns the row number that the given component represents.
        If the component isn't one of the list's rows, this will return -1.
    */
    int getRowNumberOfComponent (Component* rowComponent) const noexcept;

    /** Returns the width of a row (which may be less than the width of this component
        if there's a scrollbar).
    */
    int getVisibleRowWidth() const noexcept;

    //==============================================================================
    /** Sets the height of each row in the list.
        The default height is 22 pixels.
        @see getRowHeight
    */
    void setRowHeight (int newHeight);

    /** Returns the height of a row in the list.
        @see setRowHeight
    */
    int getRowHeight() const noexcept                   { return rowHeight; }

    /** Returns the number of rows actually visible.

        This is the number of whole rows which will fit on-screen, so the value might
        be more than the actual number of rows in the list.
    */
    int getNumRowsOnScreen() const noexcept;

    //==============================================================================
    /** A set of colour IDs to use to change the colour of various aspects of the label.

        These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
        methods.

        @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
    */
    enum ColourIds
    {
        backgroundColourId      = 0x1002800, /**< The background colour to fill the list with.
                                                  Make this transparent if you don't want the background to be filled. */
        outlineColourId         = 0x1002810, /**< An optional colour to use to draw a border around the list.
                                                  Make this transparent to not have an outline. */
        textColourId            = 0x1002820  /**< The preferred colour to use for drawing text in the listbox. */
    };

    /** Sets the thickness of a border that will be drawn around the box.

        To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
        @see outlineColourId
    */
    void setOutlineThickness (int outlineThickness);

    /** Returns the thickness of outline that will be drawn around the listbox.
        @see setOutlineColour
    */
    int getOutlineThickness() const noexcept            { return outlineThickness; }

    /** Sets a component that the list should use as a header.

        This will position the given component at the top of the list, maintaining the
        height of the component passed-in, but rescaling it horizontally to match the
        width of the items in the listbox.

        The component will be deleted when setHeaderComponent() is called with a
        different component, or when the listbox is deleted.
    */
    void setHeaderComponent (Component* newHeaderComponent);

    /** Returns whatever header component was set with setHeaderComponent(). */
    Component* getHeaderComponent() const noexcept      { return headerComponent; }

    /** Changes the width of the rows in the list.

        This can be used to make the list's row components wider than the list itself - the
        width of the rows will be either the width of the list or this value, whichever is
        greater, and if the rows become wider than the list, a horizontal scrollbar will
        appear.

        The default value for this is 0, which means that the rows will always
        be the same width as the list.
    */
    void setMinimumContentWidth (int newMinimumWidth);

    /** Returns the space currently available for the row items, taking into account
        borders, scrollbars, etc.
    */
    int getVisibleContentWidth() const noexcept;

    /** Repaints one of the rows.

        This does not invoke updateContent(), it just invokes a straightforward repaint
        for the area covered by this row.
    */
    void repaintRow (int rowNumber) noexcept;

    /** This fairly obscure method creates an image that shows the row components specified
        in rows (for example, these could be the currently selected row components).

        It's a handy method for doing drag-and-drop, as it can be passed to the
        DragAndDropContainer for use as the drag image.

        Note that it will make the row components temporarily invisible, so if you're
        using custom components this could affect them if they're sensitive to that
        sort of thing.

        @see Component::createComponentSnapshot
    */
    virtual Image createSnapshotOfRows (const SparseSet<int>& rows, int& x, int& y);

    /** Returns the viewport that this ListBox uses.

        You may need to use this to change parameters such as whether scrollbars
        are shown, etc.
    */
    Viewport* getViewport() const noexcept;

    //==============================================================================
    /** @internal */
    bool keyPressed (const KeyPress&) override;
    /** @internal */
    bool keyStateChanged (bool isKeyDown) override;
    /** @internal */
    void paint (Graphics&) override;
    /** @internal */
    void paintOverChildren (Graphics&) override;
    /** @internal */
    void resized() override;
    /** @internal */
    void visibilityChanged() override;
    /** @internal */
    void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
    /** @internal */
    void mouseUp (const MouseEvent&) override;
    /** @internal */
    void colourChanged() override;
    /** @internal */
    void parentHierarchyChanged() override;
    /** @internal */
    void startDragAndDrop (const MouseEvent&, const SparseSet<int>& rowsToDrag,
                           const var& dragDescription, bool allowDraggingToOtherWindows);

private:
    //==============================================================================
    JUCE_PUBLIC_IN_DLL_BUILD (class ListViewport)
    JUCE_PUBLIC_IN_DLL_BUILD (class RowComponent)
    friend class ListViewport;
    friend class TableListBox;
    ListBoxModel* model;
    ScopedPointer<ListViewport> viewport;
    ScopedPointer<Component> headerComponent;
    ScopedPointer<MouseListener> mouseMoveSelector;
    SparseSet<int> selected;
    int totalItems = 0, rowHeight = 22, minimumRowWidth = 0;
    int outlineThickness = 0;
    int lastRowSelected = -1;
    bool multipleSelection = false, alwaysFlipSelection = false, hasDoneInitialUpdate = false, selectOnMouseDown = true;

    void selectRowInternal (int rowNumber, bool dontScrollToShowThisRow,
                            bool deselectOthersFirst, bool isMouseClick);

   #if JUCE_CATCH_DEPRECATED_CODE_MISUSE
    // This method's bool parameter has changed: see the new method signature.
    JUCE_DEPRECATED (void setSelectedRows (const SparseSet<int>&, bool));
    // This method has been replaced by the more flexible method createSnapshotOfRows.
    // Please call createSnapshotOfRows (getSelectedRows(), x, y) to get the same behaviour.
    JUCE_DEPRECATED (virtual void createSnapshotOfSelectedRows (int&, int&)) {}
   #endif

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBox)
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    A progress bar component.

    To use this, just create one and make it visible. It'll run its own timer
    to keep an eye on a variable that you give it, and will automatically
    redraw itself when the variable changes.

    If using LookAndFeel_V4 a circular spinning progress bar will be drawn if
    the width and height of the ProgressBar are equal, otherwise the standard,
    linear ProgressBar will be drawn.

    For an easy way of running a background task with a dialog box showing its
    progress, see the ThreadWithProgressWindow class.

    @see ThreadWithProgressWindow
*/
class JUCE_API  ProgressBar  : public Component,
                               public SettableTooltipClient,
                               private Timer
{
public:
    //==============================================================================
    /** Creates a ProgressBar.

        @param progress     pass in a reference to a double that you're going to
                            update with your task's progress. The ProgressBar will
                            monitor the value of this variable and will redraw itself
                            when the value changes. The range is from 0 to 1.0 and JUCE
                            LookAndFeel classes will draw a spinning animation for values
                            outside this range. Obviously you'd better be careful not to
                            delete this variable while the ProgressBar still exists!
    */
    explicit ProgressBar (double& progress);

    /** Destructor. */
    ~ProgressBar();

    //==============================================================================
    /** Turns the percentage display on or off.

        By default this is on, and the progress bar will display a text string showing
        its current percentage.
    */
    void setPercentageDisplay (bool shouldDisplayPercentage);

    /** Gives the progress bar a string to display inside it.

        If you call this, it will turn off the percentage display.
        @see setPercentageDisplay
    */
    void setTextToDisplay (const String& text);

    //==============================================================================
    /** A set of colour IDs to use to change the colour of various aspects of the bar.

        These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
        methods.

        @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
    */
    enum ColourIds
    {
        backgroundColourId              = 0x1001900,    /**< The background colour, behind the bar. */
        foregroundColourId              = 0x1001a00,    /**< The colour to use to draw the bar itself. LookAndFeel
                                                             classes will probably use variations on this colour. */
    };

    //==============================================================================
    /** This abstract base class is implemented by LookAndFeel classes. */
    struct JUCE_API  LookAndFeelMethods
    {
        virtual ~LookAndFeelMethods() {}

        /** Draws a progress bar.

            If the progress value is less than 0 or greater than 1.0, this should draw a spinning
            bar that fills the whole space (i.e. to say that the app is still busy but the progress
            isn't known). It can use the current time as a basis for playing an animation.

            (Used by progress bars in AlertWindow).
        */
        virtual void drawProgressBar (Graphics&, ProgressBar&, int width, int height,
                                      double progress, const String& textToShow) = 0;

        virtual bool isProgressBarOpaque (ProgressBar&) = 0;
    };

protected:
    //==============================================================================
    /** @internal */
    void paint (Graphics&) override;
    /** @internal */
    void lookAndFeelChanged() override;
    /** @internal */
    void visibilityChanged() override;
    /** @internal */
    void colourChanged() override;

private:
    double& progress;
    double currentValue;
    bool displayPercentage;
    String displayedMessage, currentMessage;
    uint32 lastCallbackTime;

    void timerCallback() override;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgressBar)
};

} // namespace juce

repo_name: fedden/RenderMan

mime_type: text/x-c++


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    An editable text box.

    A TextEditor can either be in single- or multi-line mode, and supports mixed
    fonts and colours.

    @see TextEditor::Listener, Label
*/
class JUCE_API  TextEditor  : public Component,
                              public TextInputTarget,
                              public SettableTooltipClient
{
public:
    //==============================================================================
    /** Creates a new, empty text editor.

        @param componentName        the name to pass to the component for it to use as its name
        @param passwordCharacter    if this is not zero, this character will be used as a replacement
                                    for all characters that are drawn on screen - e.g. to create
                                    a password-style textbox containing circular blobs instead of text,
                                    you could set this value to 0x25cf, which is the unicode character
                                    for a black splodge (not all fonts include this, though), or 0x2022,
                                    which is a bullet (probably the best choice for linux).
    */
    explicit TextEditor (const String& componentName = String(),
                         juce_wchar passwordCharacter = 0);

    /** Destructor. */
    ~TextEditor();

    //==============================================================================
    /** Puts the editor into either multi- or single-line mode.

        By default, the editor will be in single-line mode, so use this if you need a multi-line
        editor.

        See also the setReturnKeyStartsNewLine() method, which will also need to be turned
        on if you want a multi-line editor with line-breaks.

        @see isMultiLine, setReturnKeyStartsNewLine
    */
    void setMultiLine (bool shouldBeMultiLine,
                       bool shouldWordWrap = true);

    /** Returns true if the editor is in multi-line mode. */
    bool isMultiLine() const;

    //==============================================================================
    /** Changes the behaviour of the return key.

        If set to true, the return key will insert a new-line into the text; if false
        it will trigger a call to the TextEditor::Listener::textEditorReturnKeyPressed()
        method. By default this is set to false, and when true it will only insert
        new-lines when in multi-line mode (see setMultiLine()).
    */
    void setReturnKeyStartsNewLine (bool shouldStartNewLine);

    /** Returns the value set by setReturnKeyStartsNewLine().
        See setReturnKeyStartsNewLine() for more info.
    */
    bool getReturnKeyStartsNewLine() const                      { return returnKeyStartsNewLine; }

    /** Indicates whether the tab key should be accepted and used to input a tab character,
        or whether it gets ignored.

        By default the tab key is ignored, so that it can be used to switch keyboard focus
        between components.
    */
    void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);

    /** Returns true if the tab key is being used for input.
        @see setTabKeyUsedAsCharacter
    */
    bool isTabKeyUsedAsCharacter() const                        { return tabKeyUsed; }

    /** This can be used to change whether escape and return keypress events are
        propagated up to the parent component.
        The default here is true, meaning that these events are not allowed to reach the
        parent, but you may want to allow them through so that they can trigger other
        actions, e.g. closing a dialog box, etc.
    */
    void setEscapeAndReturnKeysConsumed (bool shouldBeConsumed) noexcept;

    //==============================================================================
    /** Changes the editor to read-only mode.

        By default, the text editor is not read-only. If you're making it read-only, you
        might also want to call setCaretVisible (false) to get rid of the caret.

        The text can still be highlighted and copied when in read-only mode.

        @see isReadOnly, setCaretVisible
    */
    void setReadOnly (bool shouldBeReadOnly);

    /** Returns true if the editor is in read-only mode. */
    bool isReadOnly() const noexcept;

    //==============================================================================
    /** Makes the caret visible or invisible.
        By default the caret is visible.
        @see setCaretColour, setCaretPosition
    */
    void setCaretVisible (bool shouldBeVisible);

    /** Returns true if the caret is enabled.
        @see setCaretVisible
    */
    bool isCaretVisible() const noexcept                            { return caretVisible && ! isReadOnly(); }

    //==============================================================================
    /** Enables/disables a vertical scrollbar.

        (This only applies when in multi-line mode). When the text gets too long to fit
        in the component, a scrollbar can appear to allow it to be scrolled. Even when
        this is enabled, the scrollbar will be hidden unless it's needed.

        By default the scrollbar is enabled.
    */
    void setScrollbarsShown (bool shouldBeEnabled);

    /** Returns true if scrollbars are enabled.
        @see setScrollbarsShown
    */
    bool areScrollbarsShown() const noexcept                        { return scrollbarVisible; }

    /** Changes the password character used to disguise the text.

        @param passwordCharacter    if this is not zero, this character will be used as a replacement
                                    for all characters that are drawn on screen - e.g. to create
                                    a password-style textbox containing circular blobs instead of text,
                                    you could set this value to 0x25cf, which is the unicode character
                                    for a black splodge (not all fonts include this, though), or 0x2022,
                                    which is a bullet (probably the best choice for linux).
    */
    void setPasswordCharacter (juce_wchar passwordCharacter);

    /** Returns the current password character.
        @see setPasswordCharacter
    */
    juce_wchar getPasswordCharacter() const noexcept                { return passwordCharacter; }

    //==============================================================================
    /** Allows a right-click menu to appear for the editor.

        (This defaults to being enabled).

        If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
        of options such as cut/copy/paste, undo/redo, etc.
    */
    void setPopupMenuEnabled (bool menuEnabled);

    /** Returns true if the right-click menu is enabled.
        @see setPopupMenuEnabled
    */
    bool isPopupMenuEnabled() const noexcept                        { return popupMenuEnabled; }

    /** Returns true if a popup-menu is currently being displayed. */
    bool isPopupMenuCurrentlyActive() const noexcept                { return menuActive; }

    //==============================================================================
    /** A set of colour IDs to use to change the colour of various aspects of the editor.

        These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
        methods.

        NB: You can also set the caret colour using CaretComponent::caretColourId

        @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
    */
    enum ColourIds
    {
        backgroundColourId       = 0x1000200, /**< The colour to use for the text component's background - this can be
                                                   transparent if necessary. */

        textColourId             = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
                                                   that because the editor can contain multiple colours, calling this
                                                   method won't change the colour of existing text - to do that, use
                                                   the applyColourToAllText() method */

        highlightColourId        = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
                                                   the text - this can be transparent if you don't want to show any
                                                   highlighting.*/

        highlightedTextColourId  = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */

        outlineColourId          = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
                                                   the edge of the component. */

        focusedOutlineColourId   = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
                                                   the edge of the component when it has focus. */

        shadowColourId           = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
                                                   around the edge of the editor. */
    };

    //==============================================================================
    /** Sets the font to use for newly added text.

        This will change the font that will be used next time any text is added or entered
        into the editor. It won't change the font of any existing text - to do that, use
        applyFontToAllText() instead.

        @see applyFontToAllText
    */
    void setFont (const Font& newFont);

    /** Applies a font to all the text in the editor.

        If the changeCurrentFont argument is true then this will also set the
        new font as the font to be used for any new text that's added.

        @see setFont
    */
    void applyFontToAllText (const Font& newFont, bool changeCurrentFont = true);

    /** Returns the font that's currently being used for new text.

        @see setFont
    */
    const Font& getFont() const noexcept            { return currentFont; }

    /** Applies a colour to all the text in the editor.

        If the changeCurrentTextColour argument is true then this will also set the
        new colour as the colour to be used for any new text that's added.
    */
    void applyColourToAllText (const Colour& newColour, bool changeCurrentTextColour = true);

    //==============================================================================
    /** If set to true, focusing on the editor will highlight all its text.

        (Set to false by default).

        This is useful for boxes where you expect the user to re-enter all the
        text when they focus on the component, rather than editing what's already there.
    */
    void setSelectAllWhenFocused (bool shouldSelectAll);

    /** When the text editor is empty, it can be set to display a message.

        This is handy for things like telling the user what to type in the box - the
        string is only displayed, it's not taken to actually be the contents of
        the editor.
    */
    void setTextToShowWhenEmpty (const String& text, Colour colourToUse);

    //==============================================================================
    /** Changes the size of the scrollbars that are used.
        Handy if you need smaller scrollbars for a small text box.
    */
    void setScrollBarThickness (int newThicknessPixels);

    //==============================================================================
    /**
        Receives callbacks from a TextEditor component when it changes.

        @see TextEditor::addListener
    */
    class JUCE_API  Listener
    {
    public:
        /** Destructor. */
        virtual ~Listener()  {}

        /** Called when the user changes the text in some way. */
        virtual void textEditorTextChanged (TextEditor&) {}

        /** Called when the user presses the return key. */
        virtual void textEditorReturnKeyPressed (TextEditor&) {}

        /** Called when the user presses the escape key. */
        virtual void textEditorEscapeKeyPressed (TextEditor&) {}

        /** Called when the text editor loses focus. */
        virtual void textEditorFocusLost (TextEditor&) {}
    };

    /** Registers a listener to be told when things happen to the text.
        @see removeListener
    */
    void addListener (Listener* newListener);

    /** Deregisters a listener.
        @see addListener
    */
    void removeListener (Listener* listenerToRemove);

    //==============================================================================
    /** Returns the entire contents of the editor. */
    String getText() const;

    /** Returns a section of the contents of the editor. */
    String getTextInRange (const Range<int>& textRange) const override;

    /** Returns true if there are no characters in the editor.
        This is far more efficient than calling getText().isEmpty().
    */
    bool isEmpty() const;

    /** Sets the entire content of the editor.

        This will clear the editor and insert the given text (using the current text colour
        and font). You can set the current text colour using
        @code setColour (TextEditor::textColourId, ...);
        @endcode

        @param newText                  the text to add
        @param sendTextChangeMessage    if true, this will cause a change message to
                                        be sent to all the listeners.
        @see insertTextAtCaret
    */
    void setText (const String& newText,
                  bool sendTextChangeMessage = true);

    /** Returns a Value object that can be used to get or set the text.

        Bear in mind that this operate quite slowly if your text box contains large
        amounts of text, as it needs to dynamically build the string that's involved.
        It's best used for small text boxes.
    */
    Value& getTextValue();

    /** Inserts some text at the current caret position.

        If a section of the text is highlighted, it will be replaced by
        this string, otherwise it will be inserted.

        To delete a section of text, you can use setHighlightedRegion() to
        highlight it, and call insertTextAtCaret (String()).

        @see setCaretPosition, getCaretPosition, setHighlightedRegion
    */
    void insertTextAtCaret (const String& textToInsert) override;

    /** Deletes all the text from the editor. */
    void clear();

    /** Deletes the currently selected region.
        This doesn't copy the deleted section to the clipboard - if you need to do that, call copy() first.
        @see copy, paste, SystemClipboard
    */
    void cut();

    /** Copies the currently selected region to the clipboard.
        @see cut, paste, SystemClipboard
    */
    void copy();

    /** Pastes the contents of the clipboard into the editor at the caret position.
        @see cut, copy, SystemClipboard
    */
    void paste();

    //==============================================================================
    /** Returns the current index of the caret.
        @see setCaretPosition
    */
    int getCaretPosition() const;

    /** Moves the caret to be in front of a given character.
        @see getCaretPosition, moveCaretToEnd
    */
    void setCaretPosition (int newIndex);

    /** Attempts to scroll the text editor so that the caret ends up at
        a specified position.

        This won't affect the caret's position within the text, it tries to scroll
        the entire editor vertically and horizontally so that the caret is sitting
        at the given position (relative to the top-left of this component).

        Depending on the amount of text available, it might not be possible to
        scroll far enough for the caret to reach this exact position, but it
        will go as far as it can in that direction.
    */
    void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);

    /** Get the graphical position of the caret.

        The rectangle returned is relative to the component's top-left corner.
        @see scrollEditorToPositionCaret
    */
    Rectangle<int> getCaretRectangle() override;

    /** Selects a section of the text. */
    void setHighlightedRegion (const Range<int>& newSelection) override;

    /** Returns the range of characters that are selected.
        If nothing is selected, this will return an empty range.
        @see setHighlightedRegion
    */
    Range<int> getHighlightedRegion() const override            { return selection; }

    /** Returns the section of text that is currently selected. */
    String getHighlightedText() const;

    /** Finds the index of the character at a given position.
        The coordinates are relative to the component's top-left.
    */
    int getTextIndexAt (int x, int y);

    /** Counts the number of characters in the text.

        This is quicker than getting the text as a string if you just need to know
        the length.
    */
    int getTotalNumChars() const;

    /** Returns the total width of the text, as it is currently laid-out.

        This may be larger than the size of the TextEditor, and can change when
        the TextEditor is resized or the text changes.
    */
    int getTextWidth() const;

    /** Returns the maximum height of the text, as it is currently laid-out.

        This may be larger than the size of the TextEditor, and can change when
        the TextEditor is resized or the text changes.
    */
    int getTextHeight() const;

    /** Changes the size of the gap at the top and left-edge of the editor.
        By default there's a gap of 4 pixels.
    */
    void setIndents (int newLeftIndent, int newTopIndent);

    /** Changes the size of border left around the edge of the component.
        @see getBorder
    */
    void setBorder (const BorderSize<int>& border);

    /** Returns the size of border around the edge of the component.
        @see setBorder
    */
    BorderSize<int> getBorder() const;

    /** Used to disable the auto-scrolling which keeps the caret visible.

        If true (the default), the editor will scroll when the caret moves offscreen. If
        set to false, it won't.
    */
    void setScrollToShowCursor (bool shouldScrollToShowCaret);

    /** Modifies the horizontal justification of the text within the editor window. */
    void setJustification (Justification newJustification);

    /** Sets the line spacing of the TextEditor.
        The default (and minimum) value is 1.0 and values > 1.0 will increase the line spacing as a
        multiple of the line height e.g. for double-spacing call this method with an argument of 2.0.
    */
    void setLineSpacing (float newLineSpacing) noexcept             { lineSpacing = jmax (1.0f, newLineSpacing); }

    /** Returns the current line spacing of the TextEditor. */
    float getLineSpacing() const noexcept                           { return lineSpacing; }

    //==============================================================================
    void moveCaretToEnd();
    bool moveCaretLeft (bool moveInWholeWordSteps, bool selecting);
    bool moveCaretRight (bool moveInWholeWordSteps, bool selecting);
    bool moveCaretUp (bool selecting);
    bool moveCaretDown (bool selecting);
    bool pageUp (bool selecting);
    bool pageDown (bool selecting);
    bool scrollDown();
    bool scrollUp();
    bool moveCaretToTop (bool selecting);
    bool moveCaretToStartOfLine (bool selecting);
    bool moveCaretToEnd (bool selecting);
    bool moveCaretToEndOfLine (bool selecting);
    bool deleteBackwards (bool moveInWholeWordSteps);
    bool deleteForwards (bool moveInWholeWordSteps);
    bool copyToClipboard();
    bool cutToClipboard();
    bool pasteFromClipboard();
    bool selectAll();
    bool undo();
    bool redo();

    //==============================================================================
    /** This adds the items to the popup menu.

        By default it adds the cut/copy/paste items, but you can override this if
        you need to replace these with your own items.

        If you want to add your own items to the existing ones, you can override this,
        call the base class's addPopupMenuItems() method, then append your own items.

        When the menu has been shown, performPopupMenuAction() will be called to
        perform the item that the user has chosen.

        The default menu items will be added using item IDs from the
        StandardApplicationCommandIDs namespace.

        If this was triggered by a mouse-click, the mouseClickEvent parameter will be
        a pointer to the info about it, or may be null if the menu is being triggered
        by some other means.

        @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
    */
    virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
                                    const MouseEvent* mouseClickEvent);

    /** This is called to perform one of the items that was shown on the popup menu.

        If you've overridden addPopupMenuItems(), you should also override this
        to perform the actions that you've added.

        If you've overridden addPopupMenuItems() but have still left the default items
        on the menu, remember to call the superclass's performPopupMenuAction()
        so that it can perform the default actions if that's what the user clicked on.

        @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
    */
    virtual void performPopupMenuAction (int menuItemID);

    //==============================================================================
    /** Base class for input filters that can be applied to a TextEditor to restrict
        the text that can be entered.
    */
    class JUCE_API  InputFilter
    {
    public:
        InputFilter() {}
        virtual ~InputFilter() {}

        /** This method is called whenever text is entered into the editor.
            An implementation of this class should should check the input string,
            and return an edited version of it that should be used.
        */
        virtual String filterNewText (TextEditor&, const String& newInput) = 0;
    };

    /** An input filter for a TextEditor that limits the length of text and/or the
        characters that it may contain.
    */
    class JUCE_API  LengthAndCharacterRestriction  : public InputFilter
    {
    public:
        /** Creates a filter that limits the length of text, and/or the characters that it can contain.
            @param maxNumChars          if this is > 0, it sets a maximum length limit; if <= 0, no
                                        limit is set
            @param allowedCharacters    if this is non-empty, then only characters that occur in
                                        this string are allowed to be entered into the editor.
        */
        LengthAndCharacterRestriction (int maxNumChars, const String& allowedCharacters);

        String filterNewText (TextEditor&, const String&) override;

    private:
        String allowedCharacters;
        int maxLength;

        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LengthAndCharacterRestriction)
    };

    /** Sets an input filter that should be applied to this editor.
        The filter can be nullptr, to remove any existing filters.
        If takeOwnership is true, then the filter will be owned and deleted by the editor
        when no longer needed.
    */
    void setInputFilter (InputFilter* newFilter, bool takeOwnership);

    /** Returns the current InputFilter, as set by setInputFilter(). */
    InputFilter* getInputFilter() const noexcept                { return inputFilter; }

    /** Sets limits on the characters that can be entered.
        This is just a shortcut that passes an instance of the LengthAndCharacterRestriction
        class to setInputFilter().

        @param maxTextLength        if this is > 0, it sets a maximum length limit; if 0, no
                                    limit is set
        @param allowedCharacters    if this is non-empty, then only characters that occur in
                                    this string are allowed to be entered into the editor.
    */
    void setInputRestrictions (int maxTextLength,
                               const String& allowedCharacters = String());

    void setKeyboardType (VirtualKeyboardType type) noexcept    { keyboardType = type; }

    //==============================================================================
    /** This abstract base class is implemented by LookAndFeel classes to provide
        TextEditor drawing functionality.
    */
    struct JUCE_API  LookAndFeelMethods
    {
        virtual ~LookAndFeelMethods() {}

        virtual void fillTextEditorBackground (Graphics&, int width, int height, TextEditor&) = 0;
        virtual void drawTextEditorOutline (Graphics&, int width, int height, TextEditor&) = 0;

        virtual CaretComponent* createCaretComponent (Component* keyFocusOwner) = 0;
    };

    //==============================================================================
    /** @internal */
    void paint (Graphics&) override;
    /** @internal */
    void paintOverChildren (Graphics&) override;
    /** @internal */
    void mouseDown (const MouseEvent&) override;
    /** @internal */
    void mouseUp (const MouseEvent&) override;
    /** @internal */
    void mouseDrag (const MouseEvent&) override;
    /** @internal */
    void mouseDoubleClick (const MouseEvent&) override;
    /** @internal */
    void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
    /** @internal */
    bool keyPressed (const KeyPress&) override;
    /** @internal */
    bool keyStateChanged (bool) override;
    /** @internal */
    void focusGained (FocusChangeType) override;
    /** @internal */
    void focusLost (FocusChangeType) override;
    /** @internal */
    void resized() override;
    /** @internal */
    void enablementChanged() override;
    /** @internal */
    void lookAndFeelChanged() override;
    /** @internal */
    void parentHierarchyChanged() override;
    /** @internal */
    bool isTextInputActive() const override;
    /** @internal */
    void setTemporaryUnderlining (const Array<Range<int>>&) override;
    /** @internal */
    VirtualKeyboardType getKeyboardType() override    { return keyboardType; }

protected:
    //==============================================================================
    /** Scrolls the minimum distance needed to get the caret into view. */
    void scrollToMakeSureCursorIsVisible();

    /** Used internally to dispatch a text-change message. */
    void textChanged();

    /** Begins a new transaction in the UndoManager. */
    void newTransaction();

    /** Can be overridden to intercept return key presses directly */
    virtual void returnPressed();

    /** Can be overridden to intercept escape key presses directly */
    virtual void escapePressed();

private:
    //==============================================================================
    JUCE_PUBLIC_IN_DLL_BUILD (class UniformTextSection)
    struct Iterator;
    struct TextHolderComponent;
    struct TextEditorViewport;
    struct InsertAction;
    struct RemoveAction;

    ScopedPointer<Viewport> viewport;
    TextHolderComponent* textHolder;
    BorderSize<int> borderSize { 1, 1, 1, 3 };
    Justification justification { Justification::left };

    bool readOnly = false;
    bool caretVisible = true;
    bool multiline = false;
    bool wordWrap = false;
    bool returnKeyStartsNewLine = false;
    bool popupMenuEnabled = true;
    bool selectAllTextWhenFocused = false;
    bool scrollbarVisible = true;
    bool wasFocused = false;
    bool keepCaretOnScreen = true;
    bool tabKeyUsed = false;
    bool menuActive = false;
    bool valueTextNeedsUpdating = false;
    bool consumeEscAndReturnKeys = true;

    UndoManager undoManager;
    ScopedPointer<CaretComponent> caret;
    Range<int> selection;
    int leftIndent = 4, topIndent = 4;
    unsigned int lastTransactionTime = 0;
    Font currentFont { 14.0f };
    mutable int totalNumChars = 0;
    int caretPosition = 0;
    OwnedArray<UniformTextSection> sections;
    String textToShowWhenEmpty;
    Colour colourForTextWhenEmpty;
    juce_wchar passwordCharacter;
    OptionalScopedPointer<InputFilter> inputFilter;
    Value textValue;
    VirtualKeyboardType keyboardType = TextInputTarget::textKeyboard;
    float lineSpacing = 1.0f;

    enum DragType
    {
        notDragging,
        draggingSelectionStart,
        draggingSelectionEnd
    };

    DragType dragType = notDragging;

    ListenerList<Listener> listeners;
    Array<Range<int>> underlinedSections;

    void moveCaret (int newCaretPos);
    void moveCaretTo (int newPosition, bool isSelecting);
    void recreateCaret();
    void handleCommandMessage (int) override;
    void coalesceSimilarSections();
    void splitSection (int sectionIndex, int charToSplitAt);
    void clearInternal (UndoManager*);
    void insert (const String&, int insertIndex, const Font&, Colour, UndoManager*, int newCaretPos);
    void reinsert (int insertIndex, const OwnedArray<UniformTextSection>&);
    void remove (Range<int>, UndoManager*, int caretPositionToMoveTo);
    void getCharPosition (int index, Point<float>&, float& lineHeight) const;
    Rectangle<float> getCaretRectangleFloat() const;
    void updateCaretPosition();
    void updateValueFromText();
    void textWasChangedByValue();
    int indexAtPosition (float x, float y);
    int findWordBreakAfter (int position) const;
    int findWordBreakBefore (int position) const;
    bool moveCaretWithTransaction (int newPos, bool selecting);
    void drawContent (Graphics&);
    void updateTextHolderSize();
    float getWordWrapWidth() const;
    float getJustificationWidth() const;
    void timerCallbackInt();
    void repaintText (Range<int>);
    void scrollByLines (int deltaLines);
    bool undoOrRedo (bool shouldUndo);
    UndoManager* getUndoManager() noexcept;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TextEditor)
};

/** This typedef is just for compatibility with old code - newer code should use the TextEditor::Listener class directly. */
typedef TextEditor::Listener TextEditorListener;

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

ImageComponent::ImageComponent (const String& name)
    : Component (name),
      placement (RectanglePlacement::centred)
{
}

ImageComponent::~ImageComponent()
{
}

void ImageComponent::setImage (const Image& newImage)
{
    if (image != newImage)
    {
        image = newImage;
        repaint();
    }
}

void ImageComponent::setImage (const Image& newImage, RectanglePlacement placementToUse)
{
    if (image != newImage || placement != placementToUse)
    {
        image = newImage;
        placement = placementToUse;
        repaint();
    }
}

void ImageComponent::setImagePlacement (RectanglePlacement newPlacement)
{
    if (placement != newPlacement)
    {
        placement = newPlacement;
        repaint();
    }
}

const Image& ImageComponent::getImage() const
{
    return image;
}

RectanglePlacement ImageComponent::getImagePlacement() const
{
    return placement;
}

void ImageComponent::paint (Graphics& g)
{
    g.setOpacity (1.0f);
    g.drawImage (image, getLocalBounds().toFloat(), placement);
}

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    A component that displays a strip of column headings for a table, and allows these
    to be resized, dragged around, etc.

    This is just the component that goes at the top of a table. You can use it
    directly for custom components, or to create a simple table, use the
    TableListBox class.

    To use one of these, create it and use addColumn() to add all the columns that you need.
    Each column must be given a unique ID number that's used to refer to it.

    @see TableListBox, TableHeaderComponent::Listener
*/
class JUCE_API  TableHeaderComponent   : public Component,
                                         private AsyncUpdater
{
public:
    //==============================================================================
    /** Creates an empty table header.
    */
    TableHeaderComponent();

    /** Destructor. */
    ~TableHeaderComponent();

    //==============================================================================
    /** A combination of these flags are passed into the addColumn() method to specify
        the properties of a column.
    */
    enum ColumnPropertyFlags
    {
        visible                     = 1,    /**< If this is set, the column will be shown; if not, it will be hidden until the user enables it with the pop-up menu. */
        resizable                   = 2,    /**< If this is set, the column can be resized by dragging it. */
        draggable                   = 4,    /**< If this is set, the column can be dragged around to change its order in the table. */
        appearsOnColumnMenu         = 8,    /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
        sortable                    = 16,   /**< If this is set, then clicking on the column header will set it to be the sort column, and clicking again will reverse the order. */
        sortedForwards              = 32,   /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
        sortedBackwards             = 64,   /**< If this is set, the column is currently the one by which the table is sorted (backwards). */

        /** This set of default flags is used as the default parameter value in addColumn(). */
        defaultFlags                = (visible | resizable | draggable | appearsOnColumnMenu | sortable),

        /** A quick way of combining flags for a column that's not resizable. */
        notResizable                = (visible | draggable | appearsOnColumnMenu | sortable),

        /** A quick way of combining flags for a column that's not resizable or sortable. */
        notResizableOrSortable      = (visible | draggable | appearsOnColumnMenu),

        /** A quick way of combining flags for a column that's not sortable. */
        notSortable                 = (visible | resizable | draggable | appearsOnColumnMenu)
    };

    /** Adds a column to the table.

        This will add a column, and asynchronously call the tableColumnsChanged() method of any
        registered listeners.

        @param columnName       the name of the new column. It's ok to have two or more columns with the same name
        @param columnId         an ID for this column. The ID can be any number apart from 0, but every column must have
                                a unique ID. This is used to identify the column later on, after the user may have
                                changed the order that they appear in
        @param width            the initial width of the column, in pixels
        @param maximumWidth     a maximum width that the column can take when the user is resizing it. This only applies
                                if the 'resizable' flag is specified for this column
        @param minimumWidth     a minimum width that the column can take when the user is resizing it. This only applies
                                if the 'resizable' flag is specified for this column
        @param propertyFlags    a combination of some of the values from the ColumnPropertyFlags enum, to define the
                                properties of this column
        @param insertIndex      the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
                                and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
                                all columns, not just the index amongst those that are currently visible
    */
    void addColumn (const String& columnName,
                    int columnId,
                    int width,
                    int minimumWidth = 30,
                    int maximumWidth = -1,
                    int propertyFlags = defaultFlags,
                    int insertIndex = -1);

    /** Removes a column with the given ID.

        If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
        registered listeners.
    */
    void removeColumn (int columnIdToRemove);

    /** Deletes all columns from the table.

        If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
        registered listeners.
    */
    void removeAllColumns();

    /** Returns the number of columns in the table.

        If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
        return the total number of columns, including hidden ones.

        @see isColumnVisible
    */
    int getNumColumns (bool onlyCountVisibleColumns) const;

    /** Returns the name for a column.
        @see setColumnName
    */
    String getColumnName (int columnId) const;

    /** Changes the name of a column. */
    void setColumnName (int columnId, const String& newName);

    /** Moves a column to a different index in the table.

        @param columnId             the column to move
        @param newVisibleIndex      the target index for it, from 0 to the number of columns currently visible.
    */
    void moveColumn (int columnId, int newVisibleIndex);

    /** Returns the width of one of the columns.
    */
    int getColumnWidth (int columnId) const;

    /** Changes the width of a column.

        This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
    */
    void setColumnWidth (int columnId, int newWidth);

    /** Shows or hides a column.

        This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
        @see isColumnVisible
    */
    void setColumnVisible (int columnId, bool shouldBeVisible);

    /** Returns true if this column is currently visible.
        @see setColumnVisible
    */
    bool isColumnVisible (int columnId) const;

    /** Changes the column which is the sort column.

        This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.

        If this method doesn't actually change the column ID, then no re-sort will take place (you can
        call reSortTable() to force a re-sort to happen if you've modified the table's contents).

        @see getSortColumnId, isSortedForwards, reSortTable
    */
    void setSortColumnId (int columnId, bool sortForwards);

    /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.

        @see setSortColumnId, isSortedForwards
    */
    int getSortColumnId() const;

    /** Returns true if the table is currently sorted forwards, or false if it's backwards.
        @see setSortColumnId
    */
    bool isSortedForwards() const;

    /** Triggers a re-sort of the table according to the current sort-column.

        If you modifiy the table's contents, you can call this to signal that the table needs
        to be re-sorted.

        (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
        tableSortOrderChanged() method of any listeners).
    */
    void reSortTable();

    //==============================================================================
    /** Returns the total width of all the visible columns in the table.
    */
    int getTotalWidth() const;

    /** Returns the index of a given column.

        If there's no such column ID, this will return -1.

        If onlyCountVisibleColumns is true, this will return the index amongst the visible columns;
        otherwise it'll return the index amongst all the columns, including any hidden ones.
    */
    int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;

    /** Returns the ID of the column at a given index.

        If onlyCountVisibleColumns is true, this will count the index amongst the visible columns;
        otherwise it'll count it amongst all the columns, including any hidden ones.

        If the index is out-of-range, it'll return 0.
    */
    int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;

    /** Returns the rectangle containing of one of the columns.

        The index is an index from 0 to the number of columns that are currently visible (hidden
        ones are not counted). It returns a rectangle showing the position of the column relative
        to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
    */
    Rectangle<int> getColumnPosition (int index) const;

    /** Finds the column ID at a given x-position in the component.
        If there is a column at this point this returns its ID, or if not, it will return 0.
    */
    int getColumnIdAtX (int xToFind) const;

    /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
        entire width of the component.

        By default this is disabled. Turning it on also means that when resizing a column, those
        on the right will be squashed to fit.
    */
    void setStretchToFitActive (bool shouldStretchToFit);

    /** Returns true if stretch-to-fit has been enabled.
        @see setStretchToFitActive
    */
    bool isStretchToFitActive() const;

    /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
        specified width, keeping their relative proportions the same.

        If the minimum widths of the columns are too wide to fit into this space, it may
        actually end up wider.
    */
    void resizeAllColumnsToFit (int targetTotalWidth);

    //==============================================================================
    /** Enables or disables the pop-up menu.

        The default menu allows the user to show or hide columns. You can add custom
        items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.

        By default the menu is enabled.

        @see isPopupMenuActive, addMenuItems, reactToMenuItem
    */
    void setPopupMenuActive (bool hasMenu);

    /** Returns true if the pop-up menu is enabled.
        @see setPopupMenuActive
    */
    bool isPopupMenuActive() const;

    //==============================================================================
    /** Returns a string that encapsulates the table's current layout.

        This can be restored later using restoreFromString(). It saves the order of
        the columns, the currently-sorted column, and the widths.

        @see restoreFromString
    */
    String toString() const;

    /** Restores the state of the table, based on a string previously created with
        toString().

        @see toString
    */
    void restoreFromString (const String& storedVersion);

    //==============================================================================
    /**
        Receives events from a TableHeaderComponent when columns are resized, moved, etc.

        You can register one of these objects for table events using TableHeaderComponent::addListener()
        and TableHeaderComponent::removeListener().

        @see TableHeaderComponent
    */
    class JUCE_API  Listener
    {
    public:
        //==============================================================================
        Listener() {}

        /** Destructor. */
        virtual ~Listener() {}

        //==============================================================================
        /** This is called when some of the table's columns are added, removed, hidden,
            or rearranged.
        */
        virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;

        /** This is called when one or more of the table's columns are resized. */
        virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;

        /** This is called when the column by which the table should be sorted is changed. */
        virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;

        /** This is called when the user begins or ends dragging one of the columns around.

            When the user starts dragging a column, this is called with the ID of that
            column. When they finish dragging, it is called again with 0 as the ID.
        */
        virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
                                                 int columnIdNowBeingDragged);
    };

    /** Adds a listener to be informed about things that happen to the header. */
    void addListener (Listener* newListener);

    /** Removes a previously-registered listener. */
    void removeListener (Listener* listenerToRemove);

    //==============================================================================
    /** This can be overridden to handle a mouse-click on one of the column headers.

        The default implementation will use this click to call getSortColumnId() and
        change the sort order.
    */
    virtual void columnClicked (int columnId, const ModifierKeys& mods);

    /** This can be overridden to add custom items to the pop-up menu.

        If you override this, you should call the superclass's method to add its
        column show/hide items, if you want them on the menu as well.

        Then to handle the result, override reactToMenuItem().

        @see reactToMenuItem
    */
    virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);

    /** Override this to handle any custom items that you have added to the
        pop-up menu with an addMenuItems() override.

        If the menuReturnId isn't one of your own custom menu items, you'll need to
        call TableHeaderComponent::reactToMenuItem() to allow the base class to
        handle the items that it had added.

        @see addMenuItems
    */
    virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);

    //==============================================================================
    /** A set of colour IDs to use to change the colour of various aspects of the TableHeaderComponent.

        @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
    */
    enum ColourIds
    {
        textColourId                   = 0x1003800, /**< The colour for the text in the header. */
        backgroundColourId             = 0x1003810, /**< The colour of the table header background.
                                                         It's up to the LookAndFeel how this is used. */
        outlineColourId                = 0x1003820, /**< The colour of the table header's outline. */
        highlightColourId              = 0x1003830, /**< The colour of the table header background when
                                                         the mouse is over or down above the the table
                                                         header. It's up to the LookAndFeel to use a
                                                         variant of this colour to destiuish between
                                                         the down and hover state. */
    };

    //==============================================================================
    /** This abstract base class is implemented by LookAndFeel classes. */
    struct JUCE_API  LookAndFeelMethods
    {
        virtual ~LookAndFeelMethods() {}

        virtual void drawTableHeaderBackground (Graphics&, TableHeaderComponent&) = 0;

        virtual void drawTableHeaderColumn (Graphics&, TableHeaderComponent&,
                                            const String& columnName, int columnId,
                                            int width, int height,
                                            bool isMouseOver, bool isMouseDown, int columnFlags) = 0;
    };

    //==============================================================================
    /** @internal */
    void paint (Graphics&) override;
    /** @internal */
    void mouseMove (const MouseEvent&) override;
    /** @internal */
    void mouseEnter (const MouseEvent&) override;
    /** @internal */
    void mouseExit (const MouseEvent&) override;
    /** @internal */
    void mouseDown (const MouseEvent&) override;
    /** @internal */
    void mouseDrag (const MouseEvent&) override;
    /** @internal */
    void mouseUp (const MouseEvent&) override;
    /** @internal */
    MouseCursor getMouseCursor() override;

    /** Can be overridden for more control over the pop-up menu behaviour. */
    virtual void showColumnChooserMenu (int columnIdClicked);

private:
    struct ColumnInfo
    {
        String name;
        int id, propertyFlags, width, minimumWidth, maximumWidth;
        double lastDeliberateWidth;

        bool isVisible() const;
    };

    OwnedArray<ColumnInfo> columns;
    Array<Listener*> listeners;
    ScopedPointer<Component> dragOverlayComp;
    class DragOverlayComp;

    bool columnsChanged = false, columnsResized = false, sortChanged = false;
    bool menuActive = true, stretchToFit = false;
    int columnIdBeingResized = 0, columnIdBeingDragged = 0, initialColumnWidth = 0;
    int columnIdUnderMouse = 0, draggingColumnOffset = 0, draggingColumnOriginalIndex = 0, lastDeliberateWidth = 0;

    ColumnInfo* getInfoForId (int columnId) const;
    int visibleIndexToTotalIndex (int visibleIndex) const;
    void sendColumnsChanged();
    void handleAsyncUpdate() override;
    void beginDrag (const MouseEvent&);
    void endDrag (int finalIndex);
    int getResizeDraggerAt (int mouseX) const;
    void updateColumnUnderMouse (const MouseEvent&);
    void setColumnUnderMouse (int columnId);
    void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableHeaderComponent)
};

/** This typedef is just for compatibility with old code - newer code should use the TableHeaderComponent::Listener class directly. */
typedef TableHeaderComponent::Listener TableHeaderListener;

} // namespace juce