12#include <QApplication>
15#include <QPainterPath>
18#include <QStyledItemDelegate>
43 : QStyledItemDelegate(parent), themeManager_(themeManager)
51 QSize
sizeHint(
const QStyleOptionViewItem& option,
const QModelIndex& index)
const override
62 void paint(QPainter* painter,
const QStyleOptionViewItem& option,
63 const QModelIndex& index)
const override
66 painter->setRenderHint(QPainter::Antialiasing);
69 bool isSelected = option.state & QStyle::State_Selected;
75 paintSeparator(painter, option.rect, index.data(Qt::DisplayRole).toString(), c);
81 QRect bgRect = option.rect.adjusted(4, 2, -4, -2);
85 path.addRoundedRect(bgRect, 4, 4);
86 painter->fillPath(path, c.
accent);
88 else if (option.state & QStyle::State_MouseOver)
91 path.addRoundedRect(bgRect, 4, 4);
105 QString icon = index.data(Qt::DecorationRole).toString();
108 QFont iconFont = painter->font();
109 iconFont.setPointSize(themeManager_->scaledFontSize(12));
110 painter->setFont(iconFont);
111 painter->setPen(textColor);
112 painter->drawText(bgRect.adjusted(8, 0, 0, 0), Qt::AlignVCenter | Qt::AlignLeft, icon);
116 QString label = index.data(Qt::DisplayRole).toString();
117 QFont labelFont = painter->font();
118 labelFont.setPointSize(themeManager_->scaledFontSize(11));
119 painter->setFont(labelFont);
120 painter->setPen(textColor);
121 int labelX = icon.isEmpty() ? 12 : 36;
122 QRect labelRect = bgRect.adjusted(labelX, 0, -80, 0);
124 labelRect, Qt::AlignVCenter | Qt::AlignLeft,
125 painter->fontMetrics().elidedText(label, Qt::ElideRight, labelRect.width()));
129 if (!shortcut.isEmpty())
131 QFont shortcutFont = painter->font();
132 shortcutFont.setPointSize(themeManager_->scaledFontSize(9));
133 painter->setFont(shortcutFont);
134 painter->setPen(mutedColor);
137 QFontMetrics fm(shortcutFont);
138 int shortcutWidth = fm.horizontalAdvance(shortcut) + 12;
139 QRect shortcutRect(bgRect.right() - shortcutWidth - 8, bgRect.center().y() - 10,
147 scPath.addRoundedRect(shortcutRect, 3, 3);
148 painter->fillPath(scPath, scBg);
151 painter->drawText(shortcutRect, Qt::AlignCenter, shortcut);
158 void paintSeparator(QPainter* painter,
const QRect& rect,
const QString& category,
162 QFont font = painter->font();
165 painter->setFont(font);
167 painter->drawText(rect.adjusted(12, 4, 0, 0), Qt::AlignVCenter | Qt::AlignLeft,
171 int lineY = rect.bottom() - 2;
174 painter->setPen(linePen);
175 painter->drawLine(rect.left() + 12, lineY, rect.right() - 12, lineY);
190 QString lowerQuery = query.toLower();
191 QString lowerLabel =
label.toLower();
192 QString lowerCategory =
category.toLower();
195 if (lowerLabel.startsWith(lowerQuery))
201 QStringList words = lowerLabel.split(
' ', Qt::SkipEmptyParts);
202 for (
const QString& word : words)
204 if (word.startsWith(lowerQuery))
212 int consecutiveBonus = 0;
213 int lastMatchIdx = -2;
215 for (
int i = 0; i < lowerLabel.length() && queryIdx < lowerQuery.length(); ++i)
217 if (lowerLabel[i] == lowerQuery[queryIdx])
219 if (i == lastMatchIdx + 1)
221 consecutiveBonus += 50;
228 if (queryIdx == lowerQuery.length())
231 int score = 500 + consecutiveBonus +
priority;
233 score += (100 - std::min(100,
static_cast<int>(lowerLabel.length())));
238 if (lowerCategory.contains(lowerQuery))
251 : QDialog(parent, Qt::FramelessWindowHint | Qt::Popup), mainWindow_(parent),
252 themeManager_(themeManager ? themeManager : &
ThemeManager::instance())
254 setObjectName(
"CommandPalette");
255 setAttribute(Qt::WA_TranslucentBackground);
260 recentCommands_ = settings.value(
"CommandPalette/RecentCommands").toStringList();
272 settings.setValue(
"CommandPalette/RecentCommands", recentCommands_);
275void CommandPalette::setupUI()
278 auto* mainLayout =
new QVBoxLayout(
this);
279 mainLayout->setContentsMargins(8, 8, 8, 8);
280 mainLayout->setSpacing(0);
283 auto* container =
new QWidget(
this);
284 container->setObjectName(
"CommandPaletteContainer");
285 auto* containerLayout =
new QVBoxLayout(container);
286 containerLayout->setContentsMargins(0, 0, 0, 0);
287 containerLayout->setSpacing(0);
290 searchEdit_ =
new QLineEdit(container);
291 searchEdit_->setObjectName(
"CommandPaletteSearch");
292 searchEdit_->setPlaceholderText(
"Type a command...");
293 searchEdit_->setClearButtonEnabled(
true);
294 searchEdit_->installEventFilter(
this);
295 containerLayout->addWidget(searchEdit_);
298 resultsList_ =
new QListWidget(container);
299 resultsList_->setObjectName(
"CommandPaletteResults");
301 resultsList_->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
302 resultsList_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
303 resultsList_->setFocusPolicy(Qt::NoFocus);
304 resultsList_->setMouseTracking(
true);
305 containerLayout->addWidget(resultsList_);
308 hintLabel_ =
new QLabel(container);
309 hintLabel_->setObjectName(
"CommandPaletteHint");
310 hintLabel_->setText(
"Press Enter to execute, Escape to close");
311 hintLabel_->setAlignment(Qt::AlignCenter);
312 containerLayout->addWidget(hintLabel_);
314 mainLayout->addWidget(container);
317 searchDebounceTimer_ =
new QTimer(
this);
318 searchDebounceTimer_->setSingleShot(
true);
319 connect(searchDebounceTimer_, &QTimer::timeout,
this,
320 [
this]() { populateResults(searchEdit_->text()); });
323 connect(searchEdit_, &QLineEdit::textChanged,
this, &CommandPalette::onSearchTextChanged);
324 connect(resultsList_, &QListWidget::itemActivated,
this, &CommandPalette::onItemActivated);
325 connect(resultsList_, &QListWidget::itemDoubleClicked,
this,
326 &CommandPalette::onItemDoubleClicked);
330 setMinimumHeight(100);
331 setMaximumHeight(500);
334void CommandPalette::applyTheme()
336 const ThemeColors& c = themeManager_->colors();
339 QString containerStyle = QString(
"#CommandPaletteContainer {"
340 " background-color: %1;"
341 " border: 1px solid %2;"
342 " border-radius: 8px;"
347 QString searchStyle = QString(
"#CommandPaletteSearch {"
348 " background-color: %1;"
350 " border-bottom: 1px solid %2;"
351 " border-radius: 8px 8px 0 0;"
352 " padding: 12px 16px;"
356 "#CommandPaletteSearch::placeholder {"
361 .arg(themeManager_->scaledFontSize(14));
364 QString resultsStyle = QString(
"#CommandPaletteResults {"
365 " background-color: %1;"
369 "#CommandPaletteResults::item {"
376 QString hintStyle = QString(
"#CommandPaletteHint {"
377 " background-color: %1;"
378 " border-top: 1px solid %2;"
379 " border-radius: 0 0 8px 8px;"
385 .arg(themeManager_->scaledFontSize(10));
387 setStyleSheet(containerStyle + searchStyle + resultsStyle + hintStyle);
393 auto it = std::find_if(staticCommands_.begin(), staticCommands_.end(),
395 if (it != staticCommands_.end())
401 staticCommands_.push_back(cmd);
407 for (
const auto& cmd : commands)
415 staticCommands_.erase(std::remove_if(staticCommands_.begin(), staticCommands_.end(),
417 staticCommands_.end());
422 staticCommands_.erase(std::remove_if(staticCommands_.begin(), staticCommands_.end(),
424 { return c.category == category; }),
425 staticCommands_.end());
430 staticCommands_.clear();
435 dynamicProviders_.push_back(std::move(provider));
443 QPoint parentCenter = parentWidget()->mapToGlobal(QPoint(parentWidget()->width() / 2, 0));
444 move(parentCenter.x() - width() / 2, parentCenter.y() + 50);
449 QScreen* screen = QApplication::primaryScreen();
452 QRect screenGeom = screen->availableGeometry();
453 move(screenGeom.center().x() - width() / 2, screenGeom.top() + 100);
457 searchEdit_->clear();
460 searchEdit_->setFocus();
465 QDialog::showEvent(event);
466 searchEdit_->setFocus();
471 switch (event->key())
477 selectPreviousItem();
484 if (resultsList_->currentItem())
486 onItemActivated(resultsList_->currentItem());
490 QDialog::keyPressEvent(event);
496 if (obj == searchEdit_ && event->type() == QEvent::KeyPress)
498 auto* keyEvent =
static_cast<QKeyEvent*
>(event);
499 switch (keyEvent->key())
502 selectPreviousItem();
509 if (resultsList_->currentItem())
511 onItemActivated(resultsList_->currentItem());
518 return QDialog::eventFilter(obj, event);
521void CommandPalette::onSearchTextChanged(
const QString& text)
524 searchDebounceTimer_->start(SEARCH_DEBOUNCE_MS);
527void CommandPalette::onItemActivated(QListWidgetItem* item)
529 if (!item || item->data(IsSeparatorRole).toBool())
534 QString commandId = item->data(CommandIdRole).toString();
535 bool isEnabled = item->data(CommandEnabledRole).toBool();
543 executeCommand(commandId);
546void CommandPalette::onItemDoubleClicked(QListWidgetItem* item)
548 onItemActivated(item);
551void CommandPalette::populateResults(
const QString& query)
553 resultsList_->clear();
556 std::vector<PaletteCommand> allCommands = staticCommands_;
559 for (
const auto& provider : dynamicProviders_)
561 auto dynamicCmds = provider();
562 allCommands.insert(allCommands.end(), dynamicCmds.begin(), dynamicCmds.end());
568 const PaletteCommand* cmd;
572 std::vector<ScoredCommand> scoredCommands;
574 for (
const auto& cmd : allCommands)
576 if (!cmd.shouldShow())
581 int score = cmd.matchScore(query);
582 if (score > 0 || query.isEmpty())
584 bool isRecent = recentCommands_.contains(cmd.id);
585 scoredCommands.push_back({&cmd, score, isRecent});
590 std::sort(scoredCommands.begin(), scoredCommands.end(),
591 [&query](
const ScoredCommand& a,
const ScoredCommand& b)
596 if (a.isRecent != b.isRecent)
598 return a.isRecent > b.isRecent;
602 if (a.score != b.score)
604 return a.score > b.score;
607 return a.cmd->label < b.cmd->label;
611 QString lastCategory;
613 constexpr int MAX_ITEMS = 20;
615 for (
const auto& scored : scoredCommands)
617 if (itemCount >= MAX_ITEMS)
627 auto* separator =
new QListWidgetItem(cmd.
category);
629 separator->setFlags(Qt::NoItemFlags);
630 resultsList_->addItem(separator);
634 resultsList_->addItem(createCommandItem(cmd));
639 for (
int i = 0; i < resultsList_->count(); ++i)
641 QListWidgetItem* item = resultsList_->item(i);
644 resultsList_->setCurrentItem(item);
651 int separatorHeight = 24;
653 for (
int i = 0; i < resultsList_->count(); ++i)
655 QListWidgetItem* item = resultsList_->item(i);
656 totalHeight += item->data(
IsSeparatorRole).toBool() ? separatorHeight : itemHeight;
660 int fixedHeight = 50 + 30;
661 int contentHeight = std::min(totalHeight, 350);
662 setFixedHeight(fixedHeight + contentHeight + 16);
665QListWidgetItem* CommandPalette::createCommandItem(
const PaletteCommand& cmd)
667 auto* item =
new QListWidgetItem();
668 item->setText(cmd.
label);
669 item->setData(Qt::DecorationRole, cmd.
icon);
670 item->setData(CommandIdRole, cmd.
id);
671 item->setData(CommandCategoryRole, cmd.
category);
672 item->setData(CommandShortcutRole, cmd.
shortcut);
673 item->setData(CommandEnabledRole, cmd.
enabled());
674 item->setData(IsSeparatorRole,
false);
678 item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
689void CommandPalette::executeCommand(
const QString& commandId)
692 const PaletteCommand* foundCmd =
nullptr;
694 for (
const auto& cmd : staticCommands_)
696 if (cmd.
id == commandId)
706 for (
const auto& provider : dynamicProviders_)
708 auto dynamicCmds = provider();
709 for (
const auto& cmd : dynamicCmds)
711 if (cmd.
id == commandId)
716 addToRecentCommands(commandId);
725 if (foundCmd && foundCmd->
action)
727 addToRecentCommands(commandId);
732void CommandPalette::addToRecentCommands(
const QString& commandId)
735 recentCommands_.removeAll(commandId);
738 recentCommands_.prepend(commandId);
741 while (recentCommands_.size() > MAX_RECENT_COMMANDS)
743 recentCommands_.removeLast();
747void CommandPalette::selectNextItem()
749 int current = resultsList_->currentRow();
750 for (
int i = current + 1; i < resultsList_->count(); ++i)
752 QListWidgetItem* item = resultsList_->item(i);
753 if (!item->data(IsSeparatorRole).toBool())
755 resultsList_->setCurrentRow(i);
761void CommandPalette::selectPreviousItem()
763 int current = resultsList_->currentRow();
764 for (
int i = current - 1; i >= 0; --i)
766 QListWidgetItem* item = resultsList_->item(i);
767 if (!item->data(IsSeparatorRole).toBool())
769 resultsList_->setCurrentRow(i);
777 return recentCommands_.mid(0, limit);
CommandItemDelegate(QObject *parent, ThemeManager *themeManager)
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
void clearCommands()
Clear all registered commands.
void showPalette()
Show the palette and focus the search field.
void unregisterCategory(const QString &category)
Remove all commands in a category.
void registerCommands(const std::vector< PaletteCommand > &commands)
Register multiple commands at once.
void keyPressEvent(QKeyEvent *event) override
void unregisterCommand(const QString &id)
Remove a command by ID.
bool eventFilter(QObject *obj, QEvent *event) override
void registerCommand(const PaletteCommand &cmd)
Register a single command.
void showEvent(QShowEvent *event) override
void registerDynamicProvider(std::function< std::vector< PaletteCommand >()> provider)
Register a provider for dynamic commands.
CommandPalette(MainWindow *parent, ThemeManager *themeManager=nullptr)
~CommandPalette() override
QStringList getRecentCommands(int limit=5) const
Get the list of recently used command IDs.
void themeChanged()
Emitted when theme or accent color changes.
int scaledFontSize(int baseSize) const
Get scaled font size for given base size.
constexpr int IsSeparatorRole
constexpr int CommandEnabledRole
constexpr int CommandCategoryRole
constexpr int CommandIdRole
constexpr int CommandShortcutRole
Represents a single command in the palette.
int matchScore(const QString &query) const
std::function< void()> action