put all split widgets inside the same directory

This commit is contained in:
fourtf
2018-06-26 14:39:22 +02:00
parent beaa2e849a
commit 22f528cd21
26 changed files with 41 additions and 60 deletions
+582
View File
@@ -0,0 +1,582 @@
#include "widgets/splits/Split.hpp"
#include "Application.hpp"
#include "Common.hpp"
#include "providers/twitch/EmoteValue.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/SettingsManager.hpp"
#include "singletons/ThemeManager.hpp"
#include "singletons/WindowManager.hpp"
#include "util/StreamLink.hpp"
#include "util/UrlFetch.hpp"
#include "widgets/helper/DebugPopup.hpp"
#include "widgets/helper/SearchPopup.hpp"
#include "widgets/helper/Shortcut.hpp"
#include "widgets/splits/SplitOverlay.hpp"
#include "widgets/QualityPopup.hpp"
#include "widgets/SelectChannelDialog.hpp"
#include "widgets/splits/SplitContainer.hpp"
#include "widgets/TextInputDialog.hpp"
#include "widgets/UserInfoPopup.hpp"
#include "widgets/Window.hpp"
#include <QApplication>
#include <QClipboard>
#include <QDesktopServices>
#include <QDockWidget>
#include <QDrag>
#include <QListWidget>
#include <QMimeData>
#include <QPainter>
#include <QVBoxLayout>
#include <functional>
#include <random>
using namespace chatterino::providers::twitch;
using namespace chatterino::messages;
namespace chatterino {
namespace widgets {
pajlada::Signals::Signal<Qt::KeyboardModifiers> Split::modifierStatusChanged;
Qt::KeyboardModifiers Split::modifierStatus = Qt::NoModifier;
Split::Split(SplitContainer *parent)
: Split(static_cast<QWidget *>(parent))
{
this->container = parent;
}
Split::Split(QWidget *parent)
: BaseWidget(parent)
, container(nullptr)
, channel(Channel::getEmpty())
, vbox(this)
, header(this)
, view(this)
, input(this)
, overlay(new SplitOverlay(this))
{
auto app = getApp();
this->setMouseTracking(true);
this->vbox.setSpacing(0);
this->vbox.setMargin(1);
this->vbox.addWidget(&this->header);
this->vbox.addWidget(&this->view, 1);
this->vbox.addWidget(&this->input);
// Initialize chat widget-wide hotkeys
// CTRL+W: Close Split
CreateShortcut(this, "CTRL+W", &Split::doCloseSplit);
// CTRL+R: Change Channel
CreateShortcut(this, "CTRL+R", &Split::doChangeChannel);
// CTRL+F: Search
CreateShortcut(this, "CTRL+F", &Split::doSearch);
// F12
CreateShortcut(this, "F10", [] {
auto *popup = new DebugPopup;
popup->setAttribute(Qt::WA_DeleteOnClose);
popup->show();
});
// xd
// CreateShortcut(this, "ALT+SHIFT+RIGHT", &Split::doIncFlexX);
// CreateShortcut(this, "ALT+SHIFT+LEFT", &Split::doDecFlexX);
// CreateShortcut(this, "ALT+SHIFT+UP", &Split::doIncFlexY);
// CreateShortcut(this, "ALT+SHIFT+DOWN", &Split::doDecFlexY);
this->input.ui_.textEdit->installEventFilter(parent);
this->view.mouseDown.connect([this](QMouseEvent *) {
//
this->giveFocus(Qt::MouseFocusReason);
});
this->view.selectionChanged.connect([this]() {
if (view.hasSelection()) {
this->input.clearSelection();
}
});
this->input.textChanged.connect([=](const QString &newText) {
if (!app->settings->hideEmptyInput) {
return;
}
if (newText.length() == 0) {
this->input.hide();
} else if (this->input.isHidden()) {
this->input.show();
}
});
app->settings->hideEmptyInput.connect(
[this](const bool &hideEmptyInput, auto) {
if (hideEmptyInput && this->input.getInputText().length() == 0) {
this->input.hide();
} else {
this->input.show();
}
},
this->managedConnections);
this->header.updateModerationModeIcon();
this->overlay->hide();
this->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
this->managedConnect(modifierStatusChanged, [this](Qt::KeyboardModifiers status) {
if ((status == showSplitOverlayModifiers /*|| status == showAddSplitRegions*/) &&
this->isMouseOver) {
this->overlay->show();
} else {
this->overlay->hide();
}
});
this->input.ui_.textEdit->focused.connect([this] { this->focused.invoke(); });
this->input.ui_.textEdit->focusLost.connect([this] { this->focusLost.invoke(); });
}
Split::~Split()
{
this->usermodeChangedConnection.disconnect();
this->roomModeChangedConnection.disconnect();
this->channelIDChangedConnection.disconnect();
this->indirectChannelChangedConnection.disconnect();
}
ChannelView &Split::getChannelView()
{
return this->view;
}
SplitContainer *Split::getContainer()
{
return this->container;
}
bool Split::isInContainer() const
{
return this->container != nullptr;
}
void Split::setContainer(SplitContainer *_container)
{
this->container = _container;
}
IndirectChannel Split::getIndirectChannel()
{
return this->channel;
}
ChannelPtr Split::getChannel()
{
return this->channel.get();
}
void Split::setChannel(IndirectChannel newChannel)
{
this->channel = newChannel;
this->view.setChannel(newChannel.get());
this->usermodeChangedConnection.disconnect();
this->roomModeChangedConnection.disconnect();
this->indirectChannelChangedConnection.disconnect();
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(newChannel.get().get());
if (tc != nullptr) {
this->usermodeChangedConnection =
tc->userStateChanged.connect([this] { this->header.updateModerationModeIcon(); });
this->roomModeChangedConnection =
tc->roomModesChanged.connect([this] { this->header.updateModes(); });
}
this->indirectChannelChangedConnection = newChannel.getChannelChanged().connect([this] { //
QTimer::singleShot(0, [this] { this->setChannel(this->channel); });
});
this->header.updateModerationModeIcon();
this->header.updateChannelText();
this->header.updateModes();
this->channelChanged.invoke();
}
void Split::setModerationMode(bool value)
{
if (value != this->moderationMode) {
this->moderationMode = value;
this->header.updateModerationModeIcon();
this->view.layoutMessages();
}
}
bool Split::getModerationMode() const
{
return this->moderationMode;
}
void Split::showChangeChannelPopup(const char *dialogTitle, bool empty,
std::function<void(bool)> callback)
{
if (this->selectChannelDialog.hasElement()) {
this->selectChannelDialog->raise();
return;
}
SelectChannelDialog *dialog = new SelectChannelDialog(this);
if (!empty) {
dialog->setSelectedChannel(this->getIndirectChannel());
}
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
dialog->closed.connect([=] {
if (dialog->hasSeletedChannel()) {
this->setChannel(dialog->getSelectedChannel());
if (this->isInContainer()) {
this->container->refreshTabTitle();
}
}
callback(dialog->hasSeletedChannel());
this->selectChannelDialog = nullptr;
});
this->selectChannelDialog = dialog;
}
void Split::layoutMessages()
{
this->view.layoutMessages();
}
void Split::updateGifEmotes()
{
this->view.queueUpdate();
}
void Split::updateLastReadMessage()
{
this->view.updateLastReadMessage();
}
void Split::giveFocus(Qt::FocusReason reason)
{
this->input.ui_.textEdit->setFocus(reason);
}
bool Split::hasFocus() const
{
return this->input.ui_.textEdit->hasFocus();
}
void Split::paintEvent(QPaintEvent *)
{
// color the background of the chat
QPainter painter(this);
painter.fillRect(this->rect(), this->themeManager->splits.background);
}
void Split::mouseMoveEvent(QMouseEvent *event)
{
this->handleModifiers(QGuiApplication::queryKeyboardModifiers());
}
void Split::keyPressEvent(QKeyEvent *event)
{
this->view.unsetCursor();
this->handleModifiers(QGuiApplication::queryKeyboardModifiers());
}
void Split::keyReleaseEvent(QKeyEvent *event)
{
this->view.unsetCursor();
this->handleModifiers(QGuiApplication::queryKeyboardModifiers());
}
void Split::resizeEvent(QResizeEvent *event)
{
BaseWidget::resizeEvent(event);
this->overlay->setGeometry(this->rect());
}
void Split::enterEvent(QEvent *event)
{
this->isMouseOver = true;
this->handleModifiers(QGuiApplication::queryKeyboardModifiers());
if (modifierStatus == showSplitOverlayModifiers /*|| modifierStatus == showAddSplitRegions*/) {
this->overlay->show();
}
if (this->container != nullptr) {
this->container->resetMouseStatus();
}
}
void Split::leaveEvent(QEvent *event)
{
this->isMouseOver = false;
this->overlay->hide();
this->handleModifiers(QGuiApplication::queryKeyboardModifiers());
}
void Split::focusInEvent(QFocusEvent *event)
{
this->giveFocus(event->reason());
}
void Split::handleModifiers(Qt::KeyboardModifiers modifiers)
{
if (modifierStatus != modifiers) {
modifierStatus = modifiers;
modifierStatusChanged.invoke(modifiers);
}
}
/// Slots
void Split::doAddSplit()
{
if (this->container) {
this->container->appendNewSplit(true);
}
}
void Split::doCloseSplit()
{
if (this->container) {
this->container->deleteSplit(this);
}
}
void Split::doChangeChannel()
{
this->showChangeChannelPopup("Change channel", false, [](bool) {});
auto popup = this->findChildren<QDockWidget *>();
if (popup.size() && popup.at(0)->isVisible() && !popup.at(0)->isFloating()) {
popup.at(0)->hide();
doOpenViewerList();
}
}
void Split::doPopup()
{
auto app = getApp();
Window &window = app->windows->createWindow(Window::Popup);
Split *split =
new Split(static_cast<SplitContainer *>(window.getNotebook().getOrAddSelectedPage()));
split->setChannel(this->getIndirectChannel());
window.getNotebook().getOrAddSelectedPage()->appendSplit(split);
window.show();
}
void Split::doClearChat()
{
this->view.clearMessages();
}
void Split::doOpenChannel()
{
ChannelPtr _channel = this->getChannel();
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(_channel.get());
if (tc != nullptr) {
QDesktopServices::openUrl("https://twitch.tv/" + tc->name);
}
}
void Split::doOpenPopupPlayer()
{
ChannelPtr _channel = this->getChannel();
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(_channel.get());
if (tc != nullptr) {
QDesktopServices::openUrl("https://player.twitch.tv/?channel=" + tc->name);
}
}
void Split::doOpenStreamlink()
{
try {
streamlink::Start(this->getChannel()->name);
} catch (const streamlink::Exception &ex) {
debug::Log("Error in doOpenStreamlink: {}", ex.what());
}
}
void Split::doOpenViewerList()
{
auto viewerDock = new QDockWidget("Viewer List", this);
viewerDock->setAllowedAreas(Qt::LeftDockWidgetArea);
viewerDock->setFeatures(QDockWidget::DockWidgetVerticalTitleBar |
QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable);
viewerDock->resize(0.5 * this->width(),
this->height() - this->header.height() - this->input.height());
viewerDock->move(0, this->header.height());
auto multiWidget = new QWidget(viewerDock);
auto dockVbox = new QVBoxLayout(viewerDock);
auto searchBar = new QLineEdit(viewerDock);
auto chattersList = new QListWidget();
auto resultList = new QListWidget();
static QStringList labels = {"Moderators", "Staff", "Admins", "Global Moderators", "Viewers"};
static QStringList jsonLabels = {"moderators", "staff", "admins", "global_mods", "viewers"};
QList<QListWidgetItem *> labelList;
for (auto &x : labels) {
auto label = new QListWidgetItem(x);
label->setBackgroundColor(this->themeManager->splits.header.background);
labelList.append(label);
}
auto loadingLabel = new QLabel("Loading...");
util::twitch::get("https://tmi.twitch.tv/group/user/" + this->getChannel()->name + "/chatters",
this, [=](QJsonObject obj) {
QJsonObject chattersObj = obj.value("chatters").toObject();
loadingLabel->hide();
for (int i = 0; i < jsonLabels.size(); i++) {
chattersList->addItem(labelList.at(i));
foreach (const QJsonValue &v,
chattersObj.value(jsonLabels.at(i)).toArray())
chattersList->addItem(v.toString());
}
});
searchBar->setPlaceholderText("Search User...");
QObject::connect(searchBar, &QLineEdit::textEdited, this, [=]() {
auto query = searchBar->text();
if (!query.isEmpty()) {
auto results = chattersList->findItems(query, Qt::MatchStartsWith);
chattersList->hide();
resultList->clear();
for (auto &item : results) {
if (!labels.contains(item->text()))
resultList->addItem(item->text());
}
resultList->show();
} else {
resultList->hide();
chattersList->show();
}
});
QObject::connect(viewerDock, &QDockWidget::topLevelChanged, this,
[=]() { viewerDock->setMinimumWidth(300); });
QObject::connect(chattersList, &QListWidget::doubleClicked, this, [=]() {
if (!labels.contains(chattersList->currentItem()->text())) {
doOpenUserInfoPopup(chattersList->currentItem()->text());
}
});
QObject::connect(resultList, &QListWidget::doubleClicked, this, [=]() {
if (!labels.contains(resultList->currentItem()->text())) {
doOpenUserInfoPopup(resultList->currentItem()->text());
}
});
dockVbox->addWidget(searchBar);
dockVbox->addWidget(loadingLabel);
dockVbox->addWidget(chattersList);
dockVbox->addWidget(resultList);
resultList->hide();
multiWidget->setStyleSheet(this->themeManager->splits.input.styleSheet);
multiWidget->setLayout(dockVbox);
viewerDock->setWidget(multiWidget);
viewerDock->show();
}
void Split::doOpenUserInfoPopup(const QString &user)
{
auto *userPopup = new UserInfoPopup;
userPopup->setData(user, this->getChannel());
userPopup->setAttribute(Qt::WA_DeleteOnClose);
userPopup->move(QCursor::pos() -
QPoint(int(150 * this->getScale()), int(70 * this->getScale())));
userPopup->show();
}
void Split::doCopy()
{
QApplication::clipboard()->setText(this->view.getSelectedText());
}
void Split::doSearch()
{
SearchPopup *popup = new SearchPopup();
popup->setChannel(this->getChannel());
popup->show();
}
template <typename Iter, typename RandomGenerator>
static Iter select_randomly(Iter start, Iter end, RandomGenerator &g)
{
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(g));
return start;
}
template <typename Iter>
static Iter select_randomly(Iter start, Iter end)
{
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start, end, gen);
}
void Split::drag()
{
auto container = dynamic_cast<SplitContainer *>(this->parentWidget());
if (container != nullptr) {
SplitContainer::isDraggingSplit = true;
SplitContainer::draggingSplit = this;
auto originalLocation = container->releaseSplit(this);
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
mimeData->setData("chatterino/split", "xD");
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec(Qt::MoveAction);
if (dropAction == Qt::IgnoreAction) {
container->insertSplit(this,
originalLocation); // SplitContainer::dragOriginalPosition);
}
SplitContainer::isDraggingSplit = false;
}
}
} // namespace widgets
} // namespace chatterino
+158
View File
@@ -0,0 +1,158 @@
#pragma once
#include "Channel.hpp"
#include "messages/layouts/MessageLayout.hpp"
#include "messages/layouts/MessageLayoutElement.hpp"
#include "messages/LimitedQueueSnapshot.hpp"
#include "messages/MessageElement.hpp"
#include "NullablePtr.hpp"
#include "util/SerializeCustom.hpp"
#include "widgets/BaseWidget.hpp"
#include "widgets/helper/ChannelView.hpp"
#include "widgets/helper/RippleEffectLabel.hpp"
#include "widgets/splits/SplitHeader.hpp"
#include "widgets/splits/SplitInput.hpp"
#include <QFont>
#include <QShortcut>
#include <QVBoxLayout>
#include <QWidget>
namespace chatterino {
namespace widgets {
class SplitContainer;
class SplitOverlay;
class SelectChannelDialog;
// Each ChatWidget consists of three sub-elements that handle their own part of the chat widget:
// ChatWidgetHeader
// - Responsible for rendering which channel the ChatWidget is in, and the menu in the top-left of
// the chat widget
// ChatWidgetView
// - Responsible for rendering all chat messages, and the scrollbar
// ChatWidgetInput
// - Responsible for rendering and handling user text input
//
// Each sub-element has a reference to the parent Chat Widget
class Split : public BaseWidget, pajlada::Signals::SignalHolder
{
friend class SplitInput;
Q_OBJECT
public:
explicit Split(SplitContainer *parent);
explicit Split(QWidget *parent);
~Split() override;
pajlada::Signals::NoArgSignal channelChanged;
pajlada::Signals::NoArgSignal focused;
pajlada::Signals::NoArgSignal focusLost;
ChannelView &getChannelView();
SplitContainer *getContainer();
IndirectChannel getIndirectChannel();
ChannelPtr getChannel();
void setChannel(IndirectChannel newChannel);
void setModerationMode(bool value);
bool getModerationMode() const;
void showChangeChannelPopup(const char *dialogTitle, bool empty,
std::function<void(bool)> callback);
void giveFocus(Qt::FocusReason reason);
bool hasFocus() const;
void layoutMessages();
void updateGifEmotes();
void updateLastReadMessage();
void drag();
bool isInContainer() const;
void setContainer(SplitContainer *container);
static pajlada::Signals::Signal<Qt::KeyboardModifiers> modifierStatusChanged;
static Qt::KeyboardModifiers modifierStatus;
protected:
void paintEvent(QPaintEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void keyReleaseEvent(QKeyEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
void focusInEvent(QFocusEvent *event) override;
private:
SplitContainer *container;
IndirectChannel channel;
QVBoxLayout vbox;
SplitHeader header;
ChannelView view;
SplitInput input;
SplitOverlay *overlay;
NullablePtr<SelectChannelDialog> selectChannelDialog;
bool moderationMode = false;
bool isMouseOver = false;
bool isDragging = false;
pajlada::Signals::Connection channelIDChangedConnection;
pajlada::Signals::Connection usermodeChangedConnection;
pajlada::Signals::Connection roomModeChangedConnection;
pajlada::Signals::Connection indirectChannelChangedConnection;
std::vector<pajlada::Signals::ScopedConnection> managedConnections;
void doOpenUserInfoPopup(const QString &user);
void channelNameUpdated(const QString &newChannelName);
void handleModifiers(Qt::KeyboardModifiers modifiers);
public slots:
// Add new split to the notebook page that this chat widget is in
// This is only activated from the menu now. Hotkey is handled in Notebook
void doAddSplit();
// Close current split (chat widget)
void doCloseSplit();
// Show a dialog for changing the current splits/chat widgets channel
void doChangeChannel();
// Open popup copy of this chat widget
// XXX: maybe make current chatwidget a popup instead?
void doPopup();
// Clear chat from all messages
void doClearChat();
// Open link to twitch channel in default browser
void doOpenChannel();
// Open popup player of twitch channel in default browser
void doOpenPopupPlayer();
// Open twitch channel stream through streamlink
void doOpenStreamlink();
// Copy text from chat
void doCopy();
// Open a search popup
void doSearch();
// Open viewer list of the channel
void doOpenViewerList();
};
} // namespace widgets
} // namespace chatterino
+7
View File
@@ -0,0 +1,7 @@
#include "SplitColumn.hpp"
namespace chatterino {
namespace helper {
} // namespace helper
} // namespace chatterino
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include "widgets/splits/Split.hpp"
#include <vector>
namespace chatterino {
namespace helper {
class SplitColumn
{
public:
SplitColumn() = default;
void insert(widgets::Split *split, int index = -1);
void remove(int index);
double getFlex();
void setFlex(double flex);
private:
std::vector<widgets::Split> items;
};
} // namespace helper
} // namespace chatterino
File diff suppressed because it is too large Load Diff
+247
View File
@@ -0,0 +1,247 @@
#pragma once
#include "widgets/BaseWidget.hpp"
#include "widgets/helper/DropPreview.hpp"
#include "widgets/helper/NotebookTab.hpp"
#include "widgets/splits/Split.hpp"
#include <QDragEnterEvent>
#include <QHBoxLayout>
#include <QRect>
#include <QVBoxLayout>
#include <QVector>
#include <QWidget>
#include <algorithm>
#include <functional>
#include <vector>
#include <pajlada/signals/signal.hpp>
#include <pajlada/signals/signalholder.hpp>
class QJsonObject;
namespace chatterino {
namespace widgets {
//
// Note: This class is a spaghetti container. There is a lot of spaghetti code inside but it doesn't
// expose any of it publicly.
//
class SplitContainer : public BaseWidget, pajlada::Signals::SignalHolder
{
Q_OBJECT
public:
struct Node;
// fourtf: !!! preserve the order of left, up, right and down
enum Direction { Left, Above, Right, Below };
struct Position final {
private:
Position() = default;
Position(Node *_relativeNode, Direction _direcion)
: relativeNode(_relativeNode)
, direction(_direcion)
{
}
Node *relativeNode;
Direction direction;
friend struct Node;
friend class SplitContainer;
};
private:
struct DropRect final {
QRect rect;
Position position;
DropRect(const QRect &_rect, const Position &_position)
: rect(_rect)
, position(_position)
{
}
};
struct ResizeRect final {
QRect rect;
Node *node;
bool vertical;
ResizeRect(const QRect &_rect, Node *_node, bool _vertical)
: rect(_rect)
, node(_node)
, vertical(_vertical)
{
}
};
public:
struct Node final {
enum Type { EmptyRoot, _Split, VerticalContainer, HorizontalContainer };
Type getType();
Split *getSplit();
Node *getParent();
qreal getHorizontalFlex();
qreal getVerticalFlex();
const std::vector<std::unique_ptr<Node>> &getChildren();
private:
Type type;
Split *split;
Node *preferedFocusTarget;
Node *parent;
QRectF geometry;
qreal flexH = 1;
qreal flexV = 1;
std::vector<std::unique_ptr<Node>> children;
Node();
Node(Split *_split, Node *_parent);
bool isOrContainsNode(Node *_node);
Node *findNodeContainingSplit(Split *_split);
void insertSplitRelative(Split *_split, Direction _direction);
void nestSplitIntoCollection(Split *_split, Direction _direction);
void _insertNextToThis(Split *_split, Direction _direction);
void setSplit(Split *_split);
Position releaseSplit();
qreal getFlex(bool isVertical);
qreal getSize(bool isVertical);
qreal getChildrensTotalFlex(bool isVertical);
void layout(bool addSpacing, float _scale, std::vector<DropRect> &dropRects,
std::vector<ResizeRect> &resizeRects);
static Type toContainerType(Direction _dir);
friend class SplitContainer;
};
private:
class DropOverlay final : public QWidget
{
public:
DropOverlay(SplitContainer *_parent = nullptr);
void setRects(std::vector<SplitContainer::DropRect> _rects);
pajlada::Signals::NoArgSignal dragEnded;
protected:
void paintEvent(QPaintEvent *event) override;
void dragEnterEvent(QDragEnterEvent *event) override;
void dragMoveEvent(QDragMoveEvent *event) override;
void dragLeaveEvent(QDragLeaveEvent *event) override;
void dropEvent(QDropEvent *event) override;
private:
std::vector<DropRect> rects;
QPoint mouseOverPoint;
SplitContainer *parent;
};
class ResizeHandle final : public QWidget
{
public:
SplitContainer *parent;
Node *node;
void setVertical(bool isVertical);
ResizeHandle(SplitContainer *_parent = nullptr);
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
friend class SplitContainer;
private:
bool vertical;
bool isMouseDown = false;
};
public:
SplitContainer(Notebook *parent);
void appendNewSplit(bool openChannelNameDialog);
void appendSplit(Split *split);
void insertSplit(Split *split, const Position &position);
void insertSplit(Split *split, Direction direction, Split *relativeTo);
void insertSplit(Split *split, Direction direction, Node *relativeTo = nullptr);
Position releaseSplit(Split *split);
Position deleteSplit(Split *split);
void selectNextSplit(Direction direction);
void decodeFromJson(QJsonObject &obj);
int getSplitCount();
const std::vector<Split *> getSplits() const;
void refreshTabTitle();
NotebookTab *getTab() const;
Node *getBaseNode();
void setTab(NotebookTab *tab);
void hideResizeHandles();
void resetMouseStatus();
static bool isDraggingSplit;
static Split *draggingSplit;
protected:
void paintEvent(QPaintEvent *event) override;
void focusInEvent(QFocusEvent *event) override;
void leaveEvent(QEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void dragEnterEvent(QDragEnterEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private:
struct DropRegion {
QRect rect;
std::pair<int, int> position;
DropRegion(QRect rect, std::pair<int, int> position)
{
this->rect = rect;
this->position = position;
}
};
void addSplit(Split *split);
std::vector<DropRect> dropRects;
std::vector<DropRegion> dropRegions;
NotebookPageDropPreview dropPreview;
DropOverlay overlay;
std::vector<std::unique_ptr<ResizeHandle>> resizeHandles;
QPoint mouseOverPoint;
void layout();
Node baseNode;
Split *selected;
void setSelected(Split *selected);
void selectSplitRecursive(Node *node, Direction direction);
void focusSplitRecursive(Node *node, Direction direction);
void setPreferedTargetRecursive(Node *node);
NotebookTab *tab;
std::vector<Split *> splits;
bool isDragging = false;
void decodeNodeRecusively(QJsonObject &obj, Node *node);
};
} // namespace widgets
} // namespace chatterino
+505
View File
@@ -0,0 +1,505 @@
#include "widgets/splits/SplitHeader.hpp"
#include "Application.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/ResourceManager.hpp"
#include "singletons/ThemeManager.hpp"
#include "util/LayoutCreator.hpp"
#include "util/UrlFetch.hpp"
#include "widgets/Label.hpp"
#include "widgets/splits/Split.hpp"
#include "widgets/splits/SplitContainer.hpp"
#include "widgets/TooltipWidget.hpp"
#include <QByteArray>
#include <QDrag>
#include <QInputDialog>
#include <QMimeData>
#include <QPainter>
#ifdef USEWEBENGINE
#include "widgets/StreamView.hpp"
#endif
using namespace chatterino::providers::twitch;
namespace chatterino {
namespace widgets {
SplitHeader::SplitHeader(Split *_split)
: BaseWidget(_split)
, split(_split)
{
this->split->focused.connect([this]() { this->themeRefreshEvent(); });
this->split->focusLost.connect([this]() { this->themeRefreshEvent(); });
auto app = getApp();
util::LayoutCreator<SplitHeader> layoutCreator(this);
auto layout = layoutCreator.emplace<QHBoxLayout>().withoutMargin();
{
// dropdown label
auto dropdown = layout.emplace<RippleEffectButton>(this).assign(&this->dropdownButton);
dropdown->setMouseTracking(true);
dropdown->setPixmap(*app->resources->splitHeaderContext->getPixmap());
this->addDropdownItems(dropdown.getElement());
QObject::connect(dropdown.getElement(), &RippleEffectButton::clicked, this, [this] {
QTimer::singleShot(80, [&, this] {
this->dropdownMenu.move(
this->dropdownButton->mapToGlobal(QPoint(0, this->dropdownButton->height())));
this->dropdownMenu.show();
});
});
// channel name label
auto title = layout.emplace<Label>().assign(&this->titleLabel);
title->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
title->setCentered(true);
title->setHasOffset(false);
// mode button
auto mode = layout.emplace<RippleEffectLabel>(this).assign(&this->modeButton);
this->addModeItems(mode.getElement());
QObject::connect(mode.getElement(), &RippleEffectLabel::clicked, this, [this] {
QTimer::singleShot(80, [&, this] {
ChannelPtr _channel = this->split->getChannel();
if (_channel.get()->isMod() || _channel.get()->isBroadcaster()) {
this->modeMenu.move(
this->modeButton->mapToGlobal(QPoint(0, this->modeButton->height())));
this->modeMenu.show();
}
});
});
mode->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
mode->hide();
// QObject::connect(mode.getElement(), &RippleEffectButton::clicked, this, [this]
// {
// //
// });
// moderation mode
auto moderator = layout.emplace<RippleEffectButton>(this).assign(&this->moderationButton);
QObject::connect(moderator.getElement(), &RippleEffectButton::clicked, this, [this] {
this->split->setModerationMode(!this->split->getModerationMode());
});
this->updateModerationModeIcon();
}
// ---- misc
this->layout()->setMargin(0);
this->scaleChangedEvent(this->getScale());
this->updateChannelText();
this->initializeChannelSignals();
this->split->channelChanged.connect([this]() {
this->initializeChannelSignals(); //
});
this->managedConnect(app->accounts->twitch.currentUserChanged,
[this] { this->updateModerationModeIcon(); });
this->setMouseTracking(true);
}
SplitHeader::~SplitHeader()
{
this->onlineStatusChangedConnection.disconnect();
}
void SplitHeader::addDropdownItems(RippleEffectButton *)
{
// clang-format off
this->dropdownMenu.addAction("Add new split", this->split, &Split::doAddSplit, QKeySequence(tr("Ctrl+T")));
this->dropdownMenu.addAction("Close split", this->split, &Split::doCloseSplit, QKeySequence(tr("Ctrl+W")));
// this->dropdownMenu.addAction("Move split", this, SLOT(menuMoveSplit()));
this->dropdownMenu.addAction("Popup", this->split, &Split::doPopup);
this->dropdownMenu.addAction("Open viewer list", this->split, &Split::doOpenViewerList);
this->dropdownMenu.addAction("Search in messages", this->split, &Split::doSearch, QKeySequence(tr("Ctrl+F")));
this->dropdownMenu.addSeparator();
#ifdef USEWEBENGINE
this->dropdownMenu.addAction("Start watching", this, [this]{
ChannelPtr _channel = this->split->getChannel();
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(_channel.get());
if (tc != nullptr) {
StreamView *view = new StreamView(_channel, "https://player.twitch.tv/?channel=" + tc->name);
view->setAttribute(Qt::WA_DeleteOnClose, true);
view->show();
}
});
#endif
this->dropdownMenu.addAction("Change channel", this->split, &Split::doChangeChannel, QKeySequence(tr("Ctrl+R")));
this->dropdownMenu.addAction("Clear chat", this->split, &Split::doClearChat);
this->dropdownMenu.addAction("Open in web browser", this->split, &Split::doOpenChannel);
#ifndef USEWEBENGINE
this->dropdownMenu.addAction("Open web player", this->split, &Split::doOpenPopupPlayer);
#endif
this->dropdownMenu.addAction("Open in Streamlink", this->split, &Split::doOpenStreamlink);
this->dropdownMenu.addSeparator();
this->dropdownMenu.addAction("Reload channel emotes", this, SLOT(menuReloadChannelEmotes()));
this->dropdownMenu.addAction("Manual reconnect", this, SLOT(menuManualReconnect()));
// this->dropdownMenu.addSeparator();
// this->dropdownMenu.addAction("Show changelog", this, SLOT(menuShowChangelog()));
// clang-format on
}
void SplitHeader::addModeItems(RippleEffectLabel *)
{
QAction *setSub = new QAction("Submode", this);
this->setSub = setSub;
setSub->setCheckable(true);
QObject::connect(setSub, &QAction::triggered, this, [setSub, this]() {
QString sendCommand = "/subscribers";
if (!setSub->isChecked()) {
sendCommand.append("off");
};
this->split->getChannel().get()->sendMessage(sendCommand);
});
QAction *setEmote = new QAction("Emote only", this);
this->setEmote = setEmote;
setEmote->setCheckable(true);
QObject::connect(setEmote, &QAction::triggered, this, [setEmote, this]() {
QString sendCommand = "/emoteonly";
if (!setEmote->isChecked()) {
sendCommand.append("off");
};
this->split->getChannel().get()->sendMessage(sendCommand);
});
QAction *setSlow = new QAction("Slow mode", this);
this->setSlow = setSlow;
setSlow->setCheckable(true);
QObject::connect(setSlow, &QAction::triggered, this, [setSlow, this]() {
if (!setSlow->isChecked()) {
this->split->getChannel().get()->sendMessage("/slowoff");
setSlow->setChecked(false);
return;
};
bool ok;
int slowSec =
QInputDialog::getInt(this, "", "Seconds:", 10, 0, 500, 1, &ok, Qt::FramelessWindowHint);
if (ok) {
this->split->getChannel().get()->sendMessage(QString("/slow %1").arg(slowSec));
} else {
setSlow->setChecked(true);
}
});
QAction *setR9k = new QAction("R9K mode", this);
this->setR9k = setR9k;
setR9k->setCheckable(true);
QObject::connect(setR9k, &QAction::triggered, this, [setR9k, this]() {
QString sendCommand = "/r9kbeta";
if (!setR9k->isChecked()) {
sendCommand.append("off");
};
this->split->getChannel().get()->sendMessage(sendCommand);
});
this->modeMenu.addAction(setEmote);
this->modeMenu.addAction(setSub);
this->modeMenu.addAction(setSlow);
this->modeMenu.addAction(setR9k);
}
void SplitHeader::initializeChannelSignals()
{
// Disconnect any previous signal first
this->onlineStatusChangedConnection.disconnect();
auto channel = this->split->getChannel();
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (twitchChannel) {
this->managedConnections.emplace_back(twitchChannel->updateLiveInfo.connect([this]() {
this->updateChannelText(); //
}));
}
}
void SplitHeader::scaleChangedEvent(float scale)
{
int w = 28 * scale;
this->setFixedHeight(w);
this->dropdownButton->setFixedWidth(w);
this->moderationButton->setFixedWidth(w);
// this->titleLabel->setFont(
// singletons::FontManager::getInstance().getFont(FontStyle::Medium, scale));
}
void SplitHeader::updateChannelText()
{
auto indirectChannel = this->split->getIndirectChannel();
auto channel = this->split->getChannel();
QString title = channel->name;
if (indirectChannel.getType() == Channel::TwitchWatching) {
title = "watching: " + (title.isEmpty() ? "none" : title);
}
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (twitchChannel != nullptr) {
const auto streamStatus = twitchChannel->getStreamStatus();
if (streamStatus.live) {
this->isLive = true;
this->tooltip = "<style>.center { text-align: center; }</style>"
"<p class = \"center\">" +
streamStatus.title + "<br><br>" + streamStatus.game + "<br>" +
(streamStatus.rerun ? "Vod-casting" : "Live") + " for " +
streamStatus.uptime + " with " +
QString::number(streamStatus.viewerCount) +
" viewers"
"</p>";
if (streamStatus.rerun) {
title += " (rerun)";
} else if (streamStatus.streamType.isEmpty()) {
title += " (" + streamStatus.streamType + ")";
} else {
title += " (live)";
}
} else {
this->tooltip = QString();
}
}
if (title.isEmpty()) {
title = "<empty>";
}
this->isLive = false;
this->titleLabel->setText(title);
}
void SplitHeader::updateModerationModeIcon()
{
auto app = getApp();
this->moderationButton->setPixmap(this->split->getModerationMode()
? *app->resources->moderationmode_enabled->getPixmap()
: *app->resources->moderationmode_disabled->getPixmap());
bool modButtonVisible = false;
ChannelPtr channel = this->split->getChannel();
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(channel.get());
if (tc != nullptr && tc->hasModRights()) {
modButtonVisible = true;
}
this->moderationButton->setVisible(modButtonVisible);
}
void SplitHeader::updateModes()
{
TwitchChannel *tc = dynamic_cast<TwitchChannel *>(this->split->getChannel().get());
if (tc == nullptr) {
this->modeButton->hide();
return;
}
TwitchChannel::RoomModes roomModes = tc->getRoomModes();
QString text;
this->setSlow->setChecked(false);
this->setEmote->setChecked(false);
this->setSub->setChecked(false);
this->setR9k->setChecked(false);
if (roomModes.r9k) {
text += "r9k, ";
this->setR9k->setChecked(true);
}
if (roomModes.slowMode) {
text += QString("slow(%1), ").arg(QString::number(roomModes.slowMode));
this->setSlow->setChecked(true);
}
if (roomModes.emoteOnly) {
text += "emote, ";
this->setEmote->setChecked(true);
}
if (roomModes.submode) {
text += "sub, ";
this->setSub->setChecked(true);
}
if (text.length() > 2) {
text = text.mid(0, text.size() - 2);
} else {
if (tc->hasModRights()) {
text = "-";
}
}
if (text.isEmpty()) {
this->modeButton->hide();
} else {
static QRegularExpression commaReplacement("^.+?, .+?,( ).+$");
QRegularExpressionMatch match = commaReplacement.match(text);
if (match.hasMatch()) {
text = text.mid(0, match.capturedStart(1)) + '\n' + text.mid(match.capturedEnd(1));
}
this->modeButton->getLabel().setText(text);
this->modeButton->show();
}
}
void SplitHeader::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), this->themeManager->splits.header.background);
painter.setPen(this->themeManager->splits.header.border);
painter.drawRect(0, 0, width() - 1, height() - 1);
}
void SplitHeader::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
this->dragging = true;
this->dragStart = event->pos();
}
this->doubleClicked = false;
}
void SplitHeader::mouseReleaseEvent(QMouseEvent *event)
{
if (this->dragging && event->button() == Qt::LeftButton) {
QPoint pos = event->globalPos();
if (!showingHelpTooltip) {
this->showingHelpTooltip = true;
QTimer::singleShot(400, this, [this, pos] {
if (this->doubleClicked) {
this->doubleClicked = false;
this->showingHelpTooltip = false;
return;
}
TooltipWidget *widget = new TooltipWidget();
widget->setText("Double click or press <Ctrl+R> to change the channel.\nClick and "
"drag to move the split.");
widget->setAttribute(Qt::WA_DeleteOnClose);
widget->move(pos);
widget->show();
widget->raise();
QTimer::singleShot(3000, widget, [this, widget] {
widget->close();
this->showingHelpTooltip = false;
});
});
}
}
this->dragging = false;
}
void SplitHeader::mouseMoveEvent(QMouseEvent *event)
{
if (this->dragging) {
if (std::abs(this->dragStart.x() - event->pos().x()) > int(12 * this->getScale()) ||
std::abs(this->dragStart.y() - event->pos().y()) > int(12 * this->getScale())) {
this->split->drag();
this->dragging = false;
}
}
}
void SplitHeader::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
this->split->doChangeChannel();
}
this->doubleClicked = true;
}
void SplitHeader::enterEvent(QEvent *event)
{
if (!this->tooltip.isEmpty()) {
auto tooltipWidget = TooltipWidget::getInstance();
tooltipWidget->moveTo(this, this->mapToGlobal(this->rect().bottomLeft()), false);
tooltipWidget->setText(this->tooltip);
tooltipWidget->show();
tooltipWidget->raise();
}
BaseWidget::enterEvent(event);
}
void SplitHeader::leaveEvent(QEvent *event)
{
TooltipWidget::getInstance()->hide();
BaseWidget::leaveEvent(event);
}
void SplitHeader::rightButtonClicked()
{
}
void SplitHeader::themeRefreshEvent()
{
QPalette palette;
if (this->split->hasFocus()) {
palette.setColor(QPalette::Foreground, this->themeManager->splits.header.focusedText);
} else {
palette.setColor(QPalette::Foreground, this->themeManager->splits.header.text);
}
// this->dropdownButton->setPalette(palette);
this->titleLabel->setPalette(palette);
// this->moderationLabel->setPalette(palette);
}
void SplitHeader::menuMoveSplit()
{
}
void SplitHeader::menuReloadChannelEmotes()
{
auto channel = this->split->getChannel();
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (twitchChannel) {
twitchChannel->reloadChannelEmotes();
}
}
void SplitHeader::menuManualReconnect()
{
auto app = getApp();
// fourtf: connection
app->twitch.server->connect();
}
void SplitHeader::menuShowChangelog()
{
}
} // namespace widgets
} // namespace chatterino
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include "widgets/BaseWidget.hpp"
#include "widgets/helper/RippleEffectLabel.hpp"
#include "widgets/helper/SignalLabel.hpp"
#include <QAction>
#include <QHBoxLayout>
#include <QLabel>
#include <QMenu>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPoint>
#include <QWidget>
#include <pajlada/settings/setting.hpp>
#include <pajlada/signals/connection.hpp>
#include <pajlada/signals/signalholder.hpp>
#include <vector>
namespace chatterino {
namespace widgets {
class Split;
class Label;
class SplitHeader : public BaseWidget, pajlada::Signals::SignalHolder
{
Q_OBJECT
public:
explicit SplitHeader(Split *_chatWidget);
virtual ~SplitHeader() override;
// Update channel text from chat widget
void updateChannelText();
void updateModerationModeIcon();
void updateModes();
protected:
virtual void scaleChangedEvent(float) override;
virtual void themeRefreshEvent() override;
virtual void paintEvent(QPaintEvent *) override;
virtual void mousePressEvent(QMouseEvent *event) override;
virtual void mouseReleaseEvent(QMouseEvent *event) override;
virtual void mouseMoveEvent(QMouseEvent *event) override;
virtual void enterEvent(QEvent *) override;
virtual void leaveEvent(QEvent *event) override;
virtual void mouseDoubleClickEvent(QMouseEvent *event) override;
private:
Split *const split;
QPoint dragStart;
bool dragging = false;
bool doubleClicked = false;
bool showingHelpTooltip = false;
pajlada::Signals::Connection onlineStatusChangedConnection;
RippleEffectButton *dropdownButton;
// Label *titleLabel;
Label *titleLabel;
RippleEffectLabel *modeButton;
RippleEffectButton *moderationButton;
QMenu dropdownMenu;
QMenu modeMenu;
QAction *setSub = nullptr;
QAction *setEmote = nullptr;
QAction *setSlow = nullptr;
QAction *setR9k = nullptr;
void rightButtonClicked();
void initializeChannelSignals();
QString tooltip;
bool isLive;
std::vector<pajlada::Signals::ScopedConnection> managedConnections;
public slots:
void addDropdownItems(RippleEffectButton *label);
void addModeItems(RippleEffectLabel *label);
void menuMoveSplit();
void menuReloadChannelEmotes();
void menuManualReconnect();
void menuShowChangelog();
};
} // namespace widgets
} // namespace chatterino
+367
View File
@@ -0,0 +1,367 @@
#include "widgets/splits/SplitInput.hpp"
#include "Application.hpp"
#include "controllers/commands/CommandController.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/IrcManager.hpp"
#include "singletons/SettingsManager.hpp"
#include "singletons/ThemeManager.hpp"
#include "util/LayoutCreator.hpp"
#include "util/UrlFetch.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/splits/Split.hpp"
#include "widgets/splits/SplitContainer.hpp"
#include <QCompleter>
#include <QPainter>
namespace chatterino {
namespace widgets {
SplitInput::SplitInput(Split *_chatWidget)
: BaseWidget(_chatWidget)
, split_(_chatWidget)
{
this->initLayout();
auto completer = new QCompleter(&this->split_->getChannel().get()->completionModel);
this->ui_.textEdit->setCompleter(completer);
this->split_->channelChanged.connect([this] {
auto completer = new QCompleter(&this->split_->getChannel()->completionModel);
this->ui_.textEdit->setCompleter(completer);
});
// misc
this->installKeyPressedEvent();
this->scaleChangedEvent(this->getScale());
}
void SplitInput::initLayout()
{
auto app = getApp();
util::LayoutCreator<SplitInput> layoutCreator(this);
auto layout =
layoutCreator.setLayoutType<QHBoxLayout>().withoutMargin().assign(&this->ui_.hbox);
// input
auto textEdit = layout.emplace<ResizingTextEdit>().assign(&this->ui_.textEdit);
connect(textEdit.getElement(), &ResizingTextEdit::textChanged, this,
&SplitInput::editTextChanged);
// right box
auto box = layout.emplace<QVBoxLayout>().withoutMargin();
box->setSpacing(0);
{
auto textEditLength = box.emplace<QLabel>().assign(&this->ui_.textEditLength);
textEditLength->setAlignment(Qt::AlignRight);
box->addStretch(1);
box.emplace<RippleEffectLabel>().assign(&this->ui_.emoteButton);
}
this->ui_.emoteButton->getLabel().setTextFormat(Qt::RichText);
// ---- misc
// set edit font
this->ui_.textEdit->setFont(
app->fonts->getFont(singletons::FontManager::Type::ChatMedium, this->getScale()));
this->managedConnections_.push_back(app->fonts->fontChanged.connect([=]() {
this->ui_.textEdit->setFont(
app->fonts->getFont(singletons::FontManager::Type::ChatMedium, this->getScale()));
}));
// open emote popup
QObject::connect(this->ui_.emoteButton, &RippleEffectLabel::clicked, [this] {
if (!this->emotePopup_) {
this->emotePopup_ = std::make_unique<EmotePopup>();
this->emotePopup_->linkClicked.connect([this](const messages::Link &link) {
if (link.type == messages::Link::InsertText) {
this->insertText(link.value + " ");
}
});
}
this->emotePopup_->resize(int(300 * this->emotePopup_->getScale()),
int(500 * this->emotePopup_->getScale()));
this->emotePopup_->loadChannel(this->split_->getChannel());
this->emotePopup_->show();
});
// clear channelview selection when selecting in the input
QObject::connect(this->ui_.textEdit, &QTextEdit::copyAvailable, [this](bool available) {
if (available) {
this->split_->view.clearSelection();
}
});
// textEditLength visibility
app->settings->showMessageLength.connect(
[this](const bool &value, auto) { this->ui_.textEditLength->setHidden(!value); },
this->managedConnections_);
}
void SplitInput::scaleChangedEvent(float scale)
{
// update the icon size of the emote button
this->updateEmoteButton();
// set maximum height
this->setMaximumHeight(int(150 * this->getScale()));
this->ui_.textEdit->setFont(getApp()->fonts->getFont(FontStyle::ChatMedium, this->getScale()));
}
void SplitInput::themeRefreshEvent()
{
QPalette palette;
palette.setColor(QPalette::Foreground, this->themeManager->splits.input.text);
this->updateEmoteButton();
this->ui_.textEditLength->setPalette(palette);
this->ui_.textEdit->setStyleSheet(this->themeManager->splits.input.styleSheet);
this->ui_.hbox->setMargin(int((this->themeManager->isLightTheme() ? 4 : 2) * this->getScale()));
this->ui_.emoteButton->getLabel().setStyleSheet("color: #000");
}
void SplitInput::updateEmoteButton()
{
float scale = this->getScale();
QString text = "<img src=':/images/emote.svg' width='xD' height='xD' />";
text.replace("xD", QString::number(int(12 * scale)));
if (this->themeManager->isLightTheme()) {
text.replace("emote", "emote_dark");
}
this->ui_.emoteButton->getLabel().setText(text);
this->ui_.emoteButton->setFixedHeight(int(18 * scale));
}
void SplitInput::installKeyPressedEvent()
{
auto app = getApp();
this->ui_.textEdit->keyPressed.connect([this, app](QKeyEvent *event) {
if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
auto c = this->split_->getChannel();
if (c == nullptr) {
return;
}
QString message = ui_.textEdit->toPlainText();
QString sendMessage = app->commands->execCommand(message, c, false);
sendMessage = sendMessage.replace('\n', ' ');
c->sendMessage(sendMessage);
// don't add duplicate messages to message history
if (this->prevMsg_.isEmpty() || !this->prevMsg_.endsWith(message))
this->prevMsg_.append(message);
event->accept();
if (!(event->modifiers() == Qt::ControlModifier)) {
this->currMsg_ = QString();
this->ui_.textEdit->setText(QString());
this->prevIndex_ = 0;
} else if (this->ui_.textEdit->toPlainText() ==
this->prevMsg_.at(this->prevMsg_.size() - 1)) {
this->prevMsg_.removeLast();
}
this->prevIndex_ = this->prevMsg_.size();
} else if (event->key() == Qt::Key_Up) {
if ((event->modifiers() & Qt::ShiftModifier) != 0) {
return;
}
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page = this->split_->getContainer();
if (page != nullptr) {
page->selectNextSplit(SplitContainer::Above);
}
} else {
if (this->prevMsg_.size() && this->prevIndex_) {
if (this->prevIndex_ == (this->prevMsg_.size())) {
this->currMsg_ = ui_.textEdit->toPlainText();
}
this->prevIndex_--;
this->ui_.textEdit->setText(this->prevMsg_.at(this->prevIndex_));
QTextCursor cursor = this->ui_.textEdit->textCursor();
cursor.movePosition(QTextCursor::End);
this->ui_.textEdit->setTextCursor(cursor);
}
}
} else if (event->key() == Qt::Key_Down) {
if ((event->modifiers() & Qt::ShiftModifier) != 0) {
return;
}
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page = this->split_->getContainer();
if (page != nullptr) {
page->selectNextSplit(SplitContainer::Below);
}
} else {
if (this->prevIndex_ != (this->prevMsg_.size() - 1) &&
this->prevIndex_ != this->prevMsg_.size()) {
this->prevIndex_++;
this->ui_.textEdit->setText(this->prevMsg_.at(this->prevIndex_));
} else {
this->prevIndex_ = this->prevMsg_.size();
this->ui_.textEdit->setText(this->currMsg_);
}
QTextCursor cursor = this->ui_.textEdit->textCursor();
cursor.movePosition(QTextCursor::End);
this->ui_.textEdit->setTextCursor(cursor);
}
} else if (event->key() == Qt::Key_Left) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page = this->split_->getContainer();
if (page != nullptr) {
page->selectNextSplit(SplitContainer::Left);
}
}
} else if (event->key() == Qt::Key_Right) {
if (event->modifiers() == Qt::AltModifier) {
SplitContainer *page = this->split_->getContainer();
if (page != nullptr) {
page->selectNextSplit(SplitContainer::Right);
}
}
} else if (event->key() == Qt::Key_Tab) {
if (event->modifiers() == Qt::ControlModifier) {
SplitContainer *page = static_cast<SplitContainer *>(this->split_->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->selectNextTab();
}
} else if (event->key() == Qt::Key_Backtab) {
if (event->modifiers() == (Qt::ControlModifier | Qt::ShiftModifier)) {
SplitContainer *page = static_cast<SplitContainer *>(this->split_->parentWidget());
Notebook *notebook = static_cast<Notebook *>(page->parentWidget());
notebook->selectPreviousTab();
}
} else if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) {
if (this->split_->view.hasSelection()) {
this->split_->doCopy();
event->accept();
}
}
});
}
void SplitInput::clearSelection()
{
QTextCursor c = this->ui_.textEdit->textCursor();
c.setPosition(c.position());
c.setPosition(c.position(), QTextCursor::KeepAnchor);
this->ui_.textEdit->setTextCursor(c);
}
QString SplitInput::getInputText() const
{
return this->ui_.textEdit->toPlainText();
}
void SplitInput::insertText(const QString &text)
{
this->ui_.textEdit->insertPlainText(text);
}
void SplitInput::editTextChanged()
{
auto app = getApp();
// set textLengthLabel value
QString text = this->ui_.textEdit->toPlainText();
if (text.startsWith("/r ", Qt::CaseInsensitive) &&
this->split_->getChannel()->isTwitchChannel()) //
{
QString lastUser = app->twitch.server->lastUserThatWhisperedMe.get();
if (!lastUser.isEmpty()) {
this->ui_.textEdit->setPlainText("/w " + lastUser + text.mid(2));
this->ui_.textEdit->moveCursor(QTextCursor::EndOfBlock);
}
} else {
this->textChanged.invoke(text);
text = text.trimmed();
static QRegularExpression spaceRegex("\\s\\s+");
text = text.replace(spaceRegex, " ");
text = app->commands->execCommand(text, this->split_->getChannel(), true);
}
QString labelText;
if (text.length() == 0) {
labelText = "";
} else {
labelText = QString::number(text.length());
}
this->ui_.textEditLength->setText(labelText);
}
void SplitInput::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (this->themeManager->isLightTheme()) {
int s = int(3 * this->getScale());
QRect rect = this->rect().marginsRemoved(QMargins(s, s, s, s));
painter.fillRect(rect, this->themeManager->splits.input.background);
painter.setPen(QColor("#ccc"));
painter.drawRect(rect);
} else {
int s = int(1 * this->getScale());
QRect rect = this->rect().marginsRemoved(QMargins(s, s, s, s));
painter.fillRect(rect, this->themeManager->splits.input.background);
painter.setPen(QColor("#333"));
painter.drawRect(rect);
}
// int offset = 2;
// painter.fillRect(offset, this->height() - offset, this->width() - 2 * offset, 1,
// getApp()->themes->splits.input.focusedLine);
}
void SplitInput::resizeEvent(QResizeEvent *)
{
if (this->height() == this->maximumHeight()) {
this->ui_.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
} else {
this->ui_.textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
}
void SplitInput::mousePressEvent(QMouseEvent *)
{
this->split_->giveFocus(Qt::MouseFocusReason);
}
} // namespace widgets
} // namespace chatterino
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "widgets/helper/ResizingTextEdit.hpp"
#include "widgets/BaseWidget.hpp"
#include "widgets/EmotePopup.hpp"
#include "widgets/helper/RippleEffectLabel.hpp"
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPaintEvent>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QWidget>
namespace chatterino {
namespace widgets {
class Split;
class SplitInput : public BaseWidget
{
Q_OBJECT
public:
SplitInput(Split *_chatWidget);
void clearSelection();
QString getInputText() const;
void insertText(const QString &text);
pajlada::Signals::Signal<const QString &> textChanged;
protected:
virtual void scaleChangedEvent(float scale) override;
virtual void themeRefreshEvent() override;
virtual void paintEvent(QPaintEvent *) override;
virtual void resizeEvent(QResizeEvent *) override;
virtual void mousePressEvent(QMouseEvent *event) override;
private:
Split *const split_;
std::unique_ptr<EmotePopup> emotePopup_;
struct {
ResizingTextEdit *textEdit;
QLabel *textEditLength;
RippleEffectLabel *emoteButton;
QHBoxLayout *hbox;
} ui_;
std::vector<pajlada::Signals::ScopedConnection> managedConnections_;
QStringList prevMsg_;
QString currMsg_;
int prevIndex_ = 0;
void initLayout();
void installKeyPressedEvent();
void updateEmoteButton();
private slots:
void editTextChanged();
friend class Split;
};
} // namespace widgets
} // namespace chatterino
+215
View File
@@ -0,0 +1,215 @@
#include "SplitOverlay.hpp"
#include <QEvent>
#include <QGraphicsBlurEffect>
#include <QGraphicsEffect>
#include <QGraphicsOpacityEffect>
#include <QGridLayout>
#include <QPainter>
#include <QPushButton>
#include "Application.hpp"
#include "singletons/ResourceManager.hpp"
#include "widgets/splits/Split.hpp"
#include "widgets/splits/SplitContainer.hpp"
namespace chatterino {
namespace widgets {
SplitOverlay::SplitOverlay(Split *parent)
: BaseWidget(parent)
, split(parent)
{
QGridLayout *layout = new QGridLayout(this);
this->_layout = layout;
layout->setMargin(1);
layout->setSpacing(1);
layout->setRowStretch(1, 1);
layout->setRowStretch(3, 1);
layout->setColumnStretch(1, 1);
layout->setColumnStretch(3, 1);
QPushButton *move = new QPushButton(getApp()->resources->split.move, QString());
QPushButton *left = this->_left = new QPushButton(getApp()->resources->split.left, QString());
QPushButton *right = this->_right =
new QPushButton(getApp()->resources->split.right, QString());
QPushButton *up = this->_up = new QPushButton(getApp()->resources->split.up, QString());
QPushButton *down = this->_down = new QPushButton(getApp()->resources->split.down, QString());
move->setGraphicsEffect(new QGraphicsOpacityEffect(this));
left->setGraphicsEffect(new QGraphicsOpacityEffect(this));
right->setGraphicsEffect(new QGraphicsOpacityEffect(this));
up->setGraphicsEffect(new QGraphicsOpacityEffect(this));
down->setGraphicsEffect(new QGraphicsOpacityEffect(this));
move->setFlat(true);
left->setFlat(true);
right->setFlat(true);
up->setFlat(true);
down->setFlat(true);
layout->addWidget(move, 2, 2);
layout->addWidget(left, 2, 0);
layout->addWidget(right, 2, 4);
layout->addWidget(up, 0, 2);
layout->addWidget(down, 4, 2);
move->installEventFilter(new ButtonEventFilter(this, SplitMove));
left->installEventFilter(new ButtonEventFilter(this, SplitLeft));
right->installEventFilter(new ButtonEventFilter(this, SplitRight));
up->installEventFilter(new ButtonEventFilter(this, SplitUp));
down->installEventFilter(new ButtonEventFilter(this, SplitDown));
move->setFocusPolicy(Qt::NoFocus);
left->setFocusPolicy(Qt::NoFocus);
right->setFocusPolicy(Qt::NoFocus);
up->setFocusPolicy(Qt::NoFocus);
down->setFocusPolicy(Qt::NoFocus);
move->setCursor(Qt::SizeAllCursor);
left->setCursor(Qt::PointingHandCursor);
right->setCursor(Qt::PointingHandCursor);
up->setCursor(Qt::PointingHandCursor);
down->setCursor(Qt::PointingHandCursor);
this->managedConnect(this->scaleChanged, [=](float _scale) {
int a = int(_scale * 30);
QSize size(a, a);
move->setIconSize(size);
left->setIconSize(size);
right->setIconSize(size);
up->setIconSize(size);
down->setIconSize(size);
});
this->setMouseTracking(true);
this->setCursor(Qt::ArrowCursor);
}
void SplitOverlay::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (this->themeManager->isLightTheme()) {
painter.fillRect(this->rect(), QColor(255, 255, 255, 200));
} else {
painter.fillRect(this->rect(), QColor(0, 0, 0, 150));
}
QRect rect;
switch (this->hoveredElement) {
case SplitLeft: {
rect = QRect(0, 0, this->width() / 2, this->height());
} break;
case SplitRight: {
rect = QRect(this->width() / 2, 0, this->width() / 2, this->height());
} break;
case SplitUp: {
rect = QRect(0, 0, this->width(), this->height() / 2);
} break;
case SplitDown: {
rect = QRect(0, this->height() / 2, this->width(), this->height() / 2);
} break;
default:;
}
rect.setRight(rect.right() - 1);
rect.setBottom(rect.bottom() - 1);
if (!rect.isNull()) {
painter.setPen(getApp()->themes->splits.dropPreviewBorder);
painter.setBrush(getApp()->themes->splits.dropPreview);
painter.drawRect(rect);
}
}
void SplitOverlay::resizeEvent(QResizeEvent *event)
{
float _scale = this->getScale();
bool wideEnough = event->size().width() > 150 * _scale;
bool highEnough = event->size().height() > 150 * _scale;
this->_left->setVisible(wideEnough);
this->_right->setVisible(wideEnough);
this->_up->setVisible(highEnough);
this->_down->setVisible(highEnough);
}
void SplitOverlay::mouseMoveEvent(QMouseEvent *event)
{
BaseWidget::mouseMoveEvent(event);
// qDebug() << QGuiApplication::queryKeyboardModifiers();
// if ((QGuiApplication::queryKeyboardModifiers() & Qt::AltModifier) == Qt::AltModifier) {
// this->hide();
// }
}
SplitOverlay::ButtonEventFilter::ButtonEventFilter(SplitOverlay *_parent, HoveredElement _element)
: QObject(_parent)
, parent(_parent)
, hoveredElement(_element)
{
}
bool SplitOverlay::ButtonEventFilter::eventFilter(QObject *watched, QEvent *event)
{
switch (event->type()) {
case QEvent::Enter: {
QGraphicsOpacityEffect *effect =
dynamic_cast<QGraphicsOpacityEffect *>(((QWidget *)watched)->graphicsEffect());
if (effect != nullptr) {
effect->setOpacity(0.99);
}
this->parent->hoveredElement = this->hoveredElement;
this->parent->update();
} break;
case QEvent::Leave: {
QGraphicsOpacityEffect *effect =
dynamic_cast<QGraphicsOpacityEffect *>(((QWidget *)watched)->graphicsEffect());
if (effect != nullptr) {
effect->setOpacity(0.7);
}
this->parent->hoveredElement = HoveredElement::None;
this->parent->update();
} break;
case QEvent::MouseButtonPress: {
if (this->hoveredElement == HoveredElement::SplitMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
this->parent->split->drag();
}
return true;
}
} break;
case QEvent::MouseButtonRelease: {
if (this->hoveredElement != HoveredElement::SplitMove) {
SplitContainer *container = this->parent->split->getContainer();
if (container != nullptr) {
auto *_split = new Split(container);
auto dir = SplitContainer::Direction(this->hoveredElement +
SplitContainer::Left - SplitLeft);
container->insertSplit(_split, dir, this->parent->split);
this->parent->hide();
}
}
} break;
default:;
}
return QObject::eventFilter(watched, event);
}
} // namespace widgets
} // namespace chatterino
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <QGridLayout>
#include <QPushButton>
#include "pajlada/signals/signalholder.hpp"
#include "widgets/BaseWidget.hpp"
namespace chatterino {
namespace widgets {
class Split;
class SplitOverlay : public BaseWidget, pajlada::Signals::SignalHolder
{
public:
explicit SplitOverlay(Split *parent = nullptr);
protected:
// bool event(QEvent *event) override;
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
private:
// fourtf: !!! preserve the order of left, up, right and down
enum HoveredElement { None, SplitMove, SplitLeft, SplitUp, SplitRight, SplitDown };
HoveredElement hoveredElement = None;
Split *split;
QGridLayout *_layout;
QPushButton *_left;
QPushButton *_up;
QPushButton *_right;
QPushButton *_down;
class ButtonEventFilter : public QObject
{
SplitOverlay *parent;
HoveredElement hoveredElement;
public:
ButtonEventFilter(SplitOverlay *parent, HoveredElement hoveredElement);
protected:
bool eventFilter(QObject *watched, QEvent *event) override;
};
friend class ButtonEventFilter;
};
} // namespace widgets
} // namespace chatterino