game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
draggable_toolbar.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// qt/draggable_toolbar.cpp
4// ==============================================================================
5
7#include "theme_manager.h"
8
9#include <QApplication>
10#include <QDrag>
11#include <QMimeData>
12#include <QPainter>
13#include <QStyle>
14
15// ==============================================================================
16// ToolbarSpacer Implementation
17// ==============================================================================
18
19ToolbarSpacer::ToolbarSpacer(QWidget* parent) : QWidget(parent)
20{
21 setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
22}
23
24// ==============================================================================
25// DraggableToolbar Implementation
26// ==============================================================================
27
28DraggableToolbar::DraggableToolbar(QWidget* parent, ThemeManager* themeManager)
29 : QWidget(parent), themeManager_(themeManager ? themeManager : &ThemeManager::instance())
30{
31 setAcceptDrops(true);
32 setContextMenuPolicy(Qt::DefaultContextMenu);
33
34 layout_ = new QHBoxLayout(this);
35 layout_->setContentsMargins(4, 2, 4, 2);
36 layout_->setSpacing(2);
37
38 const ThemeColors& c = themeManager_->colors();
39 setStyleSheet(QString("DraggableToolbar { background-color: %1; border-bottom: 1px solid %2; }")
40 .arg(c.panelBackground.name())
41 .arg(c.border.name()));
42}
43
44DraggableToolbarSection* DraggableToolbar::addSection(const QString& id, const QString& displayName)
45{
46 auto* section = new DraggableToolbarSection(id, displayName.isEmpty() ? id : displayName, this,
47 this, themeManager_);
48 sections_[id] = section;
49 orderedSections_.append(section);
50 layout_->addWidget(section);
51 return section;
52}
53
55{
56 auto it = sections_.find(id);
57 return (it != sections_.end()) ? it->second : nullptr;
58}
59
61{
62 QStringList order;
63 for (auto* s : orderedSections_)
64 {
65 // Add spacer marker if there's a spacer before this section
66 if (spacersBefore_.find(s->id()) != spacersBefore_.end())
67 {
68 order << "|";
69 }
70 order << s->id();
71 }
72 return order;
73}
74
75void DraggableToolbar::setSectionOrder(const QStringList& order)
76{
77 // Clear existing spacers
78 for (auto& [id, spacer] : spacersBefore_)
79 {
80 layout_->removeWidget(spacer);
81 delete spacer;
82 }
83 spacersBefore_.clear();
84
85 // Remove all sections from layout
86 for (auto* s : orderedSections_)
87 {
88 layout_->removeWidget(s);
89 }
90
91 // Remove end spacer if exists
92 if (endSpacer_)
93 {
94 layout_->removeWidget(endSpacer_);
95 }
96
97 // Reorder based on saved order, handling spacer markers
98 QList<DraggableToolbarSection*> newOrder;
99 bool nextNeedsSpacer = false;
100
101 for (const QString& id : order)
102 {
103 if (id == "|")
104 {
105 nextNeedsSpacer = true;
106 continue;
107 }
108
109 if (auto* s = section(id))
110 {
111 if (nextNeedsSpacer)
112 {
113 auto* spacer = new ToolbarSpacer(this);
114 spacersBefore_[id] = spacer;
115 nextNeedsSpacer = false;
116 }
117 newOrder.append(s);
118 }
119 }
120
121 // Add any sections not in the saved order at the end
122 for (auto* s : orderedSections_)
123 {
124 if (!newOrder.contains(s))
125 {
126 newOrder.append(s);
127 }
128 }
129
130 orderedSections_ = newOrder;
131
132 // Rebuild the layout
133 rebuildLayout();
134}
135
137{
138 // Create end spacer if not exists
139 if (!endSpacer_)
140 {
141 endSpacer_ = new QWidget(this);
142 endSpacer_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
143 }
144 layout_->addWidget(endSpacer_);
145}
146
147void DraggableToolbar::insertSpacerBefore(const QString& sectionId)
148{
149 if (spacersBefore_.find(sectionId) != spacersBefore_.end())
150 return; // Already has spacer
151
152 auto* spacer = new ToolbarSpacer(this);
153 spacersBefore_[sectionId] = spacer;
154 rebuildLayout();
156}
157
158void DraggableToolbar::removeSpacerBefore(const QString& sectionId)
159{
160 auto it = spacersBefore_.find(sectionId);
161 if (it == spacersBefore_.end())
162 return; // No spacer
163
164 layout_->removeWidget(it->second);
165 delete it->second;
166 spacersBefore_.erase(it);
167 rebuildLayout();
169}
170
171bool DraggableToolbar::hasSpacerBefore(const QString& sectionId) const
172{
173 return spacersBefore_.find(sectionId) != spacersBefore_.end();
174}
175
177{
178 if (locked_ == locked)
179 return;
180
181 locked_ = locked;
182
183 // Update all section cursors
184 for (auto* s : orderedSections_)
185 {
186 if (!s->isFixed())
187 {
188 s->setCursor(locked_ ? Qt::ArrowCursor : Qt::OpenHandCursor);
189 }
190 }
191
192 emit lockedChanged(locked_);
193}
194
195void DraggableToolbar::rebuildLayout()
196{
197 // Remove all widgets from layout
198 while (layout_->count() > 0)
199 {
200 layout_->takeAt(0);
201 }
202
203 // Re-add in order with spacers
204 for (auto* s : orderedSections_)
205 {
206 // Add spacer before section if exists
207 auto it = spacersBefore_.find(s->id());
208 if (it != spacersBefore_.end())
209 {
210 layout_->addWidget(it->second);
211 }
212 layout_->addWidget(s);
213 }
214
215 // Only add end spacer if there are NO custom spacers
216 // (when user adds custom spacers, they're managing alignment themselves)
217 if (endSpacer_ && spacersBefore_.empty())
218 {
219 layout_->addWidget(endSpacer_);
220 }
221}
222
223DraggableToolbarSection* DraggableToolbar::sectionAtPos(const QPoint& pos) const
224{
225 for (auto* s : orderedSections_)
226 {
227 if (s->geometry().contains(pos) && s->isVisible())
228 {
229 return s;
230 }
231 }
232 return nullptr;
233}
234
235void DraggableToolbar::contextMenuEvent(QContextMenuEvent* event)
236{
237 auto* clickedSection = sectionAtPos(event->pos());
238
239 const ThemeColors& c = themeManager_->colors();
240 QString menuStyle =
241 QString("QMenu { background-color: %1; color: %2; border: 1px solid %3; padding: 4px; }"
242 "QMenu::item { padding: 6px 16px; border-radius: 3px; }"
243 "QMenu::item:selected { background-color: %4; color: %5; }"
244 "QMenu::item:disabled { color: %6; }"
245 "QMenu::separator { height: 1px; background: %3; margin: 4px 8px; }")
246 .arg(c.cardBackground.name())
247 .arg(c.textPrimary.name())
248 .arg(c.border.name())
249 .arg(c.accent.name())
250 .arg(c.textOnAccent.name())
251 .arg(c.textMuted.name());
252
253 QMenu menu(this);
254 themeManager_->styleMenu(&menu);
255
256 if (clickedSection && !clickedSection->isFixed())
257 {
258 menu.addAction(QString("\u25A3 %1").arg(clickedSection->displayName()))->setEnabled(false);
259 menu.addSeparator();
260
261 // Alignment options (disabled when locked)
262 QAction* pushRightAction = menu.addAction("\u2192 Push to Right");
263 pushRightAction->setCheckable(true);
264 pushRightAction->setChecked(hasSpacerBefore(clickedSection->id()));
265 pushRightAction->setEnabled(!locked_);
266 connect(pushRightAction, &QAction::triggered, this,
267 [this, clickedSection](bool checked)
268 {
269 if (checked)
270 insertSpacerBefore(clickedSection->id());
271 else
272 removeSpacerBefore(clickedSection->id());
273 });
274
275 // Move options (disabled when locked)
276 menu.addSeparator();
277
278 qsizetype idx = orderedSections_.indexOf(clickedSection);
279 QAction* moveLeftAction = menu.addAction("◀ Move Left");
280 moveLeftAction->setEnabled(!locked_ && idx > 0);
281 connect(moveLeftAction, &QAction::triggered, this,
282 [this, clickedSection, idx]()
283 {
284 if (idx > 0)
285 {
286 moveSection(clickedSection, static_cast<int>(idx - 1));
288 }
289 });
290
291 QAction* moveRightAction = menu.addAction("▶ Move Right");
292 moveRightAction->setEnabled(!locked_ && idx < orderedSections_.size() - 1);
293 connect(moveRightAction, &QAction::triggered, this,
294 [this, clickedSection, idx]()
295 {
296 if (idx < orderedSections_.size() - 1)
297 {
298 moveSection(clickedSection, static_cast<int>(idx + 2));
300 }
301 });
302
303 QAction* moveFirstAction = menu.addAction("\u25C0\u25C0 Move to Start");
304 moveFirstAction->setEnabled(!locked_ && idx > 0);
305 connect(moveFirstAction, &QAction::triggered, this,
306 [this, clickedSection]()
307 {
308 // Find first non-fixed section
309 int firstMovable = 0;
310 for (int i = 0; i < orderedSections_.size(); ++i)
311 {
312 if (!orderedSections_[i]->isFixed())
313 {
314 firstMovable = i;
315 break;
316 }
317 }
318 moveSection(clickedSection, firstMovable);
320 });
321
322 QAction* moveLastAction = menu.addAction("\u25B6\u25B6 Move to End");
323 moveLastAction->setEnabled(!locked_ && idx < orderedSections_.size() - 1);
324 connect(moveLastAction, &QAction::triggered, this,
325 [this, clickedSection]()
326 {
327 moveSection(clickedSection, static_cast<int>(orderedSections_.size()));
329 });
330
331 // Lock option
332 menu.addSeparator();
333 QAction* lockAction =
334 menu.addAction(locked_ ? "\u25CB Unlock Toolbar" : "\u25CF Lock Toolbar");
335 connect(lockAction, &QAction::triggered, this, [this]() { setLocked(!locked_); });
336 }
337 else
338 {
339 // General toolbar menu
340 menu.addAction("\u2699 Toolbar Options")->setEnabled(false);
341 menu.addSeparator();
342
343 // Lock option first
344 QAction* lockAction =
345 menu.addAction(locked_ ? "\u25CB Unlock Toolbar" : "\u25CF Lock Toolbar");
346 connect(lockAction, &QAction::triggered, this, [this]() { setLocked(!locked_); });
347
348 QAction* resetAction = menu.addAction("\u21A9 Reset Layout");
349 resetAction->setEnabled(!locked_);
350 connect(resetAction, &QAction::triggered, this,
351 [this]()
352 {
353 // Clear all spacers
354 for (auto& [id, spacer] : spacersBefore_)
355 {
356 layout_->removeWidget(spacer);
357 delete spacer;
358 }
359 spacersBefore_.clear();
360 rebuildLayout();
362 });
363 }
364
365 menu.exec(event->globalPos());
366}
367
368void DraggableToolbar::dragEnterEvent(QDragEnterEvent* event)
369{
370 if (event->mimeData()->hasFormat("application/x-toolbar-section"))
371 {
372 event->acceptProposedAction();
373 showDropIndicator_ = true;
374 updateDropIndicator(event->position().toPoint());
375 }
376}
377
378void DraggableToolbar::dragMoveEvent(QDragMoveEvent* event)
379{
380 if (event->mimeData()->hasFormat("application/x-toolbar-section"))
381 {
382 event->acceptProposedAction();
383 updateDropIndicator(event->position().toPoint());
384 update();
385 }
386}
387
388void DraggableToolbar::dropEvent(QDropEvent* event)
389{
390 showDropIndicator_ = false;
391 update();
392
393 if (!event->mimeData()->hasFormat("application/x-toolbar-section"))
394 return;
395
396 QString sectionId = QString::fromUtf8(event->mimeData()->data("application/x-toolbar-section"));
397 auto* droppedSection = section(sectionId);
398 if (!droppedSection)
399 return;
400
401 int newIndex = findInsertIndex(event->position().toPoint());
402 moveSection(droppedSection, newIndex);
403
404 event->acceptProposedAction();
406}
407
408void DraggableToolbar::paintEvent(QPaintEvent* event)
409{
410 QWidget::paintEvent(event);
411
412 if (showDropIndicator_ && dropIndicatorIndex_ >= 0)
413 {
414 QPainter painter(this);
415 const ThemeColors& c = themeManager_->colors();
416
417 // Calculate indicator position
418 int x = 0;
419 if (dropIndicatorIndex_ < orderedSections_.size())
420 {
421 x = orderedSections_[dropIndicatorIndex_]->geometry().left() - 2;
422 }
423 else if (!orderedSections_.isEmpty())
424 {
425 x = orderedSections_.last()->geometry().right() + 2;
426 }
427
428 // Draw drop indicator line
429 painter.setPen(QPen(c.accent, 3));
430 painter.drawLine(x, 4, x, height() - 4);
431
432 // Draw small triangles at top and bottom
433 painter.setBrush(c.accent);
434 painter.setPen(Qt::NoPen);
435
436 QPolygon topTriangle;
437 topTriangle << QPoint(x - 5, 2) << QPoint(x + 5, 2) << QPoint(x, 8);
438 painter.drawPolygon(topTriangle);
439
440 QPolygon bottomTriangle;
441 bottomTriangle << QPoint(x - 5, height() - 2) << QPoint(x + 5, height() - 2)
442 << QPoint(x, height() - 8);
443 painter.drawPolygon(bottomTriangle);
444 }
445}
446
447void DraggableToolbar::updateDropIndicator(const QPoint& pos)
448{
449 dropIndicatorIndex_ = findInsertIndex(pos);
450}
451
452int DraggableToolbar::findInsertIndex(const QPoint& pos) const
453{
454 for (qsizetype i = 0; i < orderedSections_.size(); ++i)
455 {
456 QRect rect = orderedSections_[i]->geometry();
457 if (pos.x() < rect.center().x())
458 {
459 return static_cast<int>(i);
460 }
461 }
462 return static_cast<int>(orderedSections_.size());
463}
464
465void DraggableToolbar::moveSection(DraggableToolbarSection* section, int newIndex)
466{
467 qsizetype currentIndex = orderedSections_.indexOf(section);
468 if (currentIndex < 0 || currentIndex == newIndex)
469 return;
470
471 // Adjust index if moving right
472 if (newIndex > currentIndex)
473 --newIndex;
474
475 orderedSections_.removeAt(currentIndex);
476 orderedSections_.insert(newIndex, section);
477
478 // Rebuild the entire layout to handle spacers properly
479 rebuildLayout();
480}
481
483{
484 const ThemeColors& c = themeManager_->colors();
485
486 // Update toolbar background
487 setStyleSheet(QString("DraggableToolbar { background-color: %1; border-bottom: 1px solid %2; }")
488 .arg(c.panelBackground.name())
489 .arg(c.border.name()));
490
491 // Update all sections
492 for (auto* section : orderedSections_)
493 {
494 section->applyTheme();
495 }
496}
497
498// ==============================================================================
499// DraggableToolbarSection Implementation
500// ==============================================================================
501
503 DraggableToolbar* toolbar, QWidget* parent,
504 ThemeManager* themeManager)
505 : QFrame(parent), id_(id), displayName_(displayName), toolbar_(toolbar),
506 themeManager_(themeManager ? themeManager : &ThemeManager::instance())
507{
508 setMouseTracking(true);
509 setFrameShape(QFrame::NoFrame);
510
511 contentLayout_ = new QHBoxLayout(this);
512 contentLayout_->setContentsMargins(6, 2, 6, 2);
513 contentLayout_->setSpacing(4);
514
515 updateStyle();
516}
517
518void DraggableToolbarSection::setResizable(bool resizable, int minWidth, int maxWidth)
519{
520 resizable_ = resizable;
521 minWidth_ = minWidth;
522 maxWidth_ = maxWidth;
523}
524
525void DraggableToolbarSection::updateStyle()
526{
527 const ThemeColors& c = themeManager_->colors();
528
529 QString bgColor = "transparent";
530 QString borderColor = "transparent";
531
532 if (dragging_)
533 {
534 bgColor = c.accent.name();
535 borderColor = c.accent.name();
536 }
537 else if (hovered_ && !fixed_)
538 {
539 bgColor = c.hoverBackground.name();
540 borderColor = c.border.name();
541 }
542
543 setStyleSheet(QString("DraggableToolbarSection { background-color: %1; border: 1px solid %2; "
544 "border-radius: 4px; }")
545 .arg(bgColor)
546 .arg(borderColor));
547}
548
550{
551 updateStyle();
552}
553
555{
556 if (event->button() == Qt::LeftButton)
557 {
558 dragStartPos_ = event->pos();
559
560 if (resizable_ && isOnResizeHandle(event->pos()))
561 {
562 resizing_ = true;
563 resizeStartX_ = event->globalPosition().toPoint().x();
564 originalWidth_ = width();
565 setCursor(Qt::SplitHCursor);
566 }
567 }
568 QFrame::mousePressEvent(event);
569}
570
572{
573 bool toolbarLocked = toolbar_ && toolbar_->isLocked();
574
575 if (resizing_)
576 {
577 int delta = event->globalPosition().toPoint().x() - resizeStartX_;
578 int newWidth = qBound(minWidth_, originalWidth_ + delta, maxWidth_);
579 setFixedWidth(newWidth);
580 emit resized(newWidth);
581 if (toolbar_)
582 emit toolbar_->sectionResized(id_, newWidth);
583 }
584 else if (!fixed_ && !toolbarLocked && (event->buttons() & Qt::LeftButton))
585 {
586 if ((event->pos() - dragStartPos_).manhattanLength() >= DRAG_START_DISTANCE)
587 {
588 startDrag();
589 }
590 }
591 else
592 {
593 // Update cursor based on position
594 if (resizable_ && isOnResizeHandle(event->pos()))
595 setCursor(Qt::SplitHCursor);
596 else if (!fixed_ && !toolbarLocked)
597 setCursor(Qt::OpenHandCursor);
598 else
599 setCursor(Qt::ArrowCursor);
600 }
601
602 QFrame::mouseMoveEvent(event);
603}
604
606{
607 resizing_ = false;
608 dragging_ = false;
609 updateStyle();
610 QFrame::mouseReleaseEvent(event);
611}
612
614{
615 hovered_ = true;
616 updateStyle();
617 bool toolbarLocked = toolbar_ && toolbar_->isLocked();
618 if (!fixed_ && !toolbarLocked)
619 setCursor(Qt::OpenHandCursor);
620 QFrame::enterEvent(event);
621}
622
624{
625 hovered_ = false;
626 updateStyle();
627 setCursor(Qt::ArrowCursor);
628 QFrame::leaveEvent(event);
629}
630
632{
633 QFrame::paintEvent(event);
634
635 // Draw resize handle indicator if resizable
636 if (resizable_ && hovered_)
637 {
638 QPainter painter(this);
639 const ThemeColors& c = themeManager_->colors();
640
641 // Draw dots on the right edge
642 painter.setPen(Qt::NoPen);
643 painter.setBrush(c.textMuted);
644
645 int centerY = height() / 2;
646 int x = width() - 4;
647 painter.drawEllipse(QPoint(x, centerY - 4), 1, 1);
648 painter.drawEllipse(QPoint(x, centerY), 1, 1);
649 painter.drawEllipse(QPoint(x, centerY + 4), 1, 1);
650 }
651}
652
653void DraggableToolbarSection::startDrag()
654{
655 dragging_ = true;
656 updateStyle();
657
658 QDrag* drag = new QDrag(this);
659 QMimeData* mimeData = new QMimeData();
660 mimeData->setData("application/x-toolbar-section", id_.toUtf8());
661 drag->setMimeData(mimeData);
662
663 // Create a semi-transparent pixmap of this section
664 QPixmap pixmap(size());
665 pixmap.fill(Qt::transparent);
666 render(&pixmap);
667
668 // Make it semi-transparent
669 QPixmap transparentPixmap(pixmap.size());
670 transparentPixmap.fill(Qt::transparent);
671 QPainter painter(&transparentPixmap);
672 painter.setOpacity(0.7);
673 painter.drawPixmap(0, 0, pixmap);
674 painter.end();
675
676 drag->setPixmap(transparentPixmap);
677 drag->setHotSpot(dragStartPos_);
678
679 setCursor(Qt::ClosedHandCursor);
680 drag->exec(Qt::MoveAction);
681
682 dragging_ = false;
683 updateStyle();
684 setCursor(Qt::OpenHandCursor);
685}
686
687bool DraggableToolbarSection::isOnResizeHandle(const QPoint& pos) const
688{
689 return pos.x() >= width() - RESIZE_HANDLE_WIDTH;
690}
void leaveEvent(QEvent *event) override
void resized(int newWidth)
void mouseMoveEvent(QMouseEvent *event) override
void setResizable(bool resizable, int minWidth=50, int maxWidth=400)
void paintEvent(QPaintEvent *event) override
void mousePressEvent(QMouseEvent *event) override
DraggableToolbarSection(const QString &id, const QString &displayName, DraggableToolbar *toolbar, QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void mouseReleaseEvent(QMouseEvent *event) override
void enterEvent(QEnterEvent *event) override
void dropEvent(QDropEvent *event) override
void sectionOrderChanged(const QStringList &newOrder)
void setLocked(bool locked)
void dragMoveEvent(QDragMoveEvent *event) override
DraggableToolbarSection * addSection(const QString &id, const QString &displayName=QString())
QStringList sectionOrder() const
void lockedChanged(bool locked)
bool hasSpacerBefore(const QString &sectionId) const
void dragEnterEvent(QDragEnterEvent *event) override
friend class DraggableToolbarSection
DraggableToolbarSection * section(const QString &id) const
void setSectionOrder(const QStringList &order)
DraggableToolbar(QWidget *parent=nullptr, ThemeManager *themeManager=nullptr)
void contextMenuEvent(QContextMenuEvent *event) override
void insertSpacerBefore(const QString &sectionId)
void paintEvent(QPaintEvent *event) override
void removeSpacerBefore(const QString &sectionId)
const ThemeColors & colors() const
Get effective colors (with accent customization applied).
ToolbarSpacer(QWidget *parent=nullptr)
QColor panelBackground
QColor cardBackground
QColor textPrimary
QColor textMuted
QColor hoverBackground
QColor textOnAccent