File indexing completed on 2024-05-05 05:52:18

0001 /*  This file is part of the Kate project.
0002  *  Based on the snippet plugin from KDevelop 4.
0003  *
0004  *  SPDX-FileCopyrightText: 2007 Robert Gruber <rgruber@users.sourceforge.net>
0005  *  SPDX-FileCopyrightText: 2010 Milian Wolff <mail@milianw.de>
0006  *  SPDX-FileCopyrightText: 2012 Christoph Cullmann <cullmann@kde.org>
0007  *
0008  *  SPDX-License-Identifier: LGPL-2.0-or-later
0009  */
0010 
0011 #include "snippet.h"
0012 #include "katesnippetglobal.h"
0013 #include "ktexteditor/application.h"
0014 #include "ktexteditor/editor.h"
0015 #include "ktexteditor/mainwindow.h"
0016 
0017 #include <KColorScheme>
0018 #include <KLocalizedString>
0019 
0020 #include <QAction>
0021 
0022 Snippet::Snippet()
0023     : QStandardItem(i18n("<empty snippet>"))
0024 {
0025     setIcon(QIcon::fromTheme(QStringLiteral("text-plain")));
0026 }
0027 
0028 Snippet::~Snippet()
0029 {
0030     delete m_action;
0031 }
0032 
0033 QString Snippet::snippet() const
0034 {
0035     return m_snippet;
0036 }
0037 
0038 void Snippet::setSnippet(const QString &snippet)
0039 {
0040     m_snippet = snippet;
0041 }
0042 
0043 void Snippet::registerActionForView(QWidget *view)
0044 {
0045     if (view->actions().contains(m_action)) {
0046         return;
0047     }
0048     view->addAction(m_action);
0049 }
0050 
0051 QAction *Snippet::action()
0052 {
0053     /// TODO: this is quite ugly, or is it? if someone knows how to do it better, please refactor
0054     if (!m_action) {
0055         static int actionCount = 0;
0056         actionCount += 1;
0057         m_action = new QAction(QStringLiteral("insertSnippet%1").arg(actionCount), KateSnippetGlobal::self());
0058         m_action->setData(QVariant::fromValue<Snippet *>(this));
0059         KateSnippetGlobal::self()->connect(m_action, &QAction::triggered, KateSnippetGlobal::self(), &KateSnippetGlobal::insertSnippetFromActionData);
0060     }
0061     m_action->setText(i18n("insert snippet %1", text()));
0062     return m_action;
0063 }
0064 
0065 QVariant Snippet::data(int role) const
0066 {
0067     if (role == Qt::ToolTipRole) {
0068         return m_snippet;
0069     } else if ((role == Qt::ForegroundRole || role == Qt::BackgroundRole) && parent()->checkState() != Qt::Checked) {
0070         /// TODO: make the selected items also "disalbed" so the toggle action is seen directly
0071         KColorScheme scheme(QPalette::Disabled, KColorScheme::View);
0072         if (role == Qt::ForegroundRole) {
0073             return scheme.foreground(KColorScheme::NormalText).color();
0074         } else {
0075             return scheme.background(KColorScheme::NormalBackground).color();
0076         }
0077     }
0078     return QStandardItem::data(role);
0079 }