@ 261105.1
current
/***************************************************************************
                               syntaxpalette.h
                             -------------------
    begin                : 2026
    copyright            : (C) 2009-2026 by Andre Simon
    email                : a.simon@mailbox.org
 ***************************************************************************/

/*
This file is part of Highlight.

Highlight is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Highlight is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Highlight.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef SYNTAXPALETTE_H
#define SYNTAXPALETTE_H

#include <QFrame>
#include <QSortFilterProxyModel>
#include <QString>

class QAbstractItemModel;
class QLineEdit;
class QListView;

/** Filters syntax names by a search text which must be contained in the
    name or in the file extension (Qt::UserRole); names starting with the
    search text are listed first */
class SyntaxFilterProxyModel : public QSortFilterProxyModel
{
    Q_OBJECT

public:
    explicit SyntaxFilterProxyModel(QObject *parent = nullptr);

public slots:
    void setSearchText(const QString &text);

protected:
    bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
    bool lessThan(const QModelIndex &left, const QModelIndex &right) const override;

private:
    QString searchText;

    int rank(const QModelIndex &index) const;
};

/** Popup with a search field and a filtered list of syntax names,
    similar to the locator of an IDE */
class SyntaxPalette : public QFrame
{
    Q_OBJECT

public:
    /** \param model list of syntax names (display role) and their file extensions (Qt::UserRole)
        \param parent parent widget */
    explicit SyntaxPalette(QAbstractItemModel *model, QWidget *parent = nullptr);

    /** Show the palette below the anchor widget
        \param anchor widget which opened the palette
        \param currentRow source model row of the current syntax */
    void popup(QWidget *anchor, int currentRow);

signals:
    /** Emitted when the user picked a syntax
        \param row source model row of the selected syntax */
    void syntaxSelected(int row);

protected:
    bool eventFilter(QObject *watched, QEvent *event) override;

private slots:
    void onSearchTextChanged(const QString &text);
    void acceptCurrent();

private:
    QLineEdit *leSearch;
    QListView *lvSyntaxes;
    SyntaxFilterProxyModel *proxy;
};

#endif // SYNTAXPALETTE_H