1/*
2 SPDX-FileCopyrightText: 2022 Waqar Ahmed <waqar.17a@gmail.com>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6#include "documentation_tip.h"
7
8#include <QDebug>
9#include <QHBoxLayout>
10#include <QScreen>
11
12DocTip::DocTip(QWidget *parent)
13 : QFrame(parent)
14 , m_textView(new QTextBrowser(this))
15{
16 setFocusPolicy(Qt::NoFocus);
17
18 m_textView->setFrameStyle(QFrame::Box | QFrame::Raised);
19
20 setFixedWidth(250);
21 setFixedHeight(150);
22
23 auto layout = new QHBoxLayout(this);
24 layout->setContentsMargins({});
25 layout->setSpacing(0);
26 setContentsMargins({});
27 layout->addWidget(&m_stack);
28 m_stack.addWidget(w: m_textView);
29}
30
31QWidget *DocTip::currentWidget()
32{
33 return m_stack.currentWidget();
34}
35
36void DocTip::clearWidgets()
37{
38 for (auto *widget : m_widgets) {
39 widget->deleteLater();
40 }
41 m_widgets.clear();
42}
43
44void DocTip::setText(const QString &s)
45{
46 m_textView->setPlainText(s);
47 if (m_stack.currentWidget() != m_textView) {
48 m_stack.removeWidget(w: m_stack.currentWidget());
49 m_stack.addWidget(w: m_textView);
50 }
51 Q_ASSERT(m_stack.count() == 1);
52}
53
54void DocTip::setWidget(QWidget *widget)
55{
56 if (auto w = m_stack.currentWidget()) {
57 if (w != m_textView) {
58 m_widgets.push_back(x: w);
59 }
60 m_stack.removeWidget(w);
61 }
62
63 if (!widget) {
64 return;
65 }
66
67 m_stack.addWidget(w: widget);
68
69 Q_ASSERT(m_stack.count() == 1);
70}
71
72void DocTip::updatePosition(QWidget *completionWidget)
73{
74 auto parent = parentWidget();
75 if (!parent) {
76 qWarning() << Q_FUNC_INFO << "Unexpected null parent!";
77 return;
78 }
79
80 const auto parentRight = parent->geometry().right();
81 auto completionWidgetRight = completionWidget->geometry().right();
82 constexpr int Margin = 8;
83
84 int x = 0;
85 // is the completion widget too far right?
86 if ((completionWidgetRight + this->width()) > parentRight) {
87 // let's hope there is enough available space to the left of completionWidget
88 x = (completionWidget->x() - this->width()) - Margin;
89 } else {
90 // we have enough space on the right
91 x = completionWidget->x() + completionWidget->width() + Margin;
92 }
93 move(ax: x, ay: completionWidget->y());
94}
95

source code of ktexteditor/src/completion/documentation_tip.cpp