Debian Codegraph @

Source/Core/VideoCommon/NetPlayChatUI.cpp

raw symbols SCIP
1 // Copyright 2019 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "VideoCommon/NetPlayChatUI.h"
5
6 #include <imgui.h>
7
8 constexpr float DEFAULT_WINDOW_WIDTH = 220.0f;
9 constexpr float DEFAULT_WINDOW_HEIGHT = 400.0f;
10
11 constexpr size_t MAX_BACKLOG_SIZE = 100;
12
13 std::unique_ptr<NetPlayChatUI> g_netplay_chat_ui;
14
15 NetPlayChatUI::NetPlayChatUI(std::function<void(const std::string&)> callback)
16 : m_message_callback{std::move(callback)}
17 {
18 }
19
20 NetPlayChatUI::~NetPlayChatUI() = default;
21
22 void NetPlayChatUI::Display()
23 {
24 const float scale = ImGui::GetIO().DisplayFramebufferScale.x;
25
26 ImGui::SetNextWindowPos(ImVec2(10.0f * scale, 10.0f * scale), ImGuiCond_FirstUseEver);
27 ImGui::SetNextWindowSizeConstraints(
28 ImVec2(DEFAULT_WINDOW_WIDTH * scale, DEFAULT_WINDOW_HEIGHT * scale),
29 ImGui::GetIO().DisplaySize);
30
31 if (!ImGui::Begin("Chat", nullptr, ImGuiWindowFlags_None))
32 {
33 ImGui::End();
34 return;
35 }
36
37 ImGui::BeginChild("Scrolling", ImVec2(0, -30 * scale), true, ImGuiWindowFlags_None);
38 for (const auto& [text, color] : m_messages)
39 {
40 ImGui::PushTextWrapPos(0.0f);
41 ImGui::TextColored(ImVec4(color[0], color[1], color[2], 1.0f), "%s", text.c_str());
42 ImGui::PopTextWrapPos();
43 }
44
45 if (m_scroll_to_bottom)
46 {
47 ImGui::SetScrollHereY(1.0f);
48 m_scroll_to_bottom = false;
49 }
50
51 m_is_scrolled_to_bottom = ImGui::GetScrollY() == ImGui::GetScrollMaxY();
52
53 ImGui::EndChild();
54
55 ImGui::Spacing();
56
57 ImGui::PushItemWidth(-50.0f * scale);
58
59 if (ImGui::InputText("##NetplayMessageBuffer", m_message_buf, IM_ARRAYSIZE(m_message_buf),
60 ImGuiInputTextFlags_EnterReturnsTrue))
61 {
62 SendChatMessage();
63 }
64
65 if (m_activate)
66 {
67 ImGui::SetKeyboardFocusHere(-1);
68 m_activate = false;
69 }
70
71 ImGui::PopItemWidth();
72
73 ImGui::SameLine();
74
75 if (ImGui::Button("Send"))
76 SendChatMessage();
77
78 ImGui::End();
79 }
80
81 void NetPlayChatUI::AppendChat(std::string message, Color color)
82 {
83 if (m_messages.size() > MAX_BACKLOG_SIZE)
84 m_messages.pop_front();
85
86 m_messages.emplace_back(std::move(message), color);
87
88 // Only scroll to bottom, if we were at the bottom previously
89 if (m_is_scrolled_to_bottom)
90 m_scroll_to_bottom = true;
91 }
92
93 void NetPlayChatUI::SendChatMessage()
94 {
95 // Check whether the input field is empty
96 if (m_message_buf[0] != '\0')
97 {
98 if (m_message_callback)
99 m_message_callback(m_message_buf);
100
101 // 'Empty' the buffer
102 m_message_buf[0] = '\0';
103 }
104 }
105
106 void NetPlayChatUI::Activate()
107 {
108 if (ImGui::IsItemFocused())
109 ImGui::SetWindowFocus(nullptr);
110 else
111 m_activate = true;
112 }