game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
terminalpanel.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// terminalpanel.cpp
4// ==============================================================================
5// Embedded terminal panel implementation using QTermWidget
6// ==============================================================================
7
9#include <QFile>
10#include <QStandardItemModel>
11#include <QStandardPaths>
12#include <QTimer>
13#include <csignal>
14#include <qtermwidget6/qtermwidget.h>
15
16// Static member initialization
17QStringList TerminalPanel::cachedColorSchemes_;
18bool TerminalPanel::colorSchemesCached_ = false;
19
20// ==============================================================================
21// Constructor / Destructor
22// ==============================================================================
23
24TerminalPanel::TerminalPanel(QWidget* parent) : QWidget(parent)
25{
26 setupUI();
27}
28
29// Terminal widget cleanup is handled by Qt parent-child relationship.
31
32// ==============================================================================
33// Public Methods
34// ==============================================================================
35
40
41void TerminalPanel::startCommand(const QString& command)
42{
43 if (!terminal_)
44 {
45 return;
46 }
47
48 currentCommand_ = command;
49
50 // Start a new session with the command
51 // QTermWidget needs the shell to run the command
52 terminal_->startShellProgram();
53
54 // Send the command to the terminal after a short delay to ensure shell is ready
55 QTimer::singleShot(100, this,
56 [this, command]()
57 {
58 if (terminal_)
59 {
60 terminal_->sendText(command + "\n");
61 }
62 });
63}
64
66{
67 QString path = QStandardPaths::findExecutable("btop");
68 return !path.isEmpty();
69}
70
72{
73 QString path = QStandardPaths::findExecutable("htop");
74 return !path.isEmpty();
75}
76
78{
79 if (isBtopAvailable())
80 {
81 return "btop";
82 }
83 else if (isHtopAvailable())
84 {
85 return "htop";
86 }
87 else
88 {
89 return "top";
90 }
91}
92
94{
95 if (isPaused_ || !terminal_)
96 {
97 return;
98 }
99
100 // Send SIGSTOP to pause the terminal's child process (btop/htop)
101 // This stops CPU consumption when the panel is hidden
102 int pid = terminal_->getShellPID();
103 if (pid > 0)
104 {
105 // Send stop signal to process group to catch btop and any children
106 ::kill(-pid, SIGSTOP);
107 isPaused_ = true;
108 }
109}
110
112{
113 if (!isPaused_ || !terminal_)
114 {
115 return;
116 }
117
118 // Send SIGCONT to resume the terminal's child process
119 int pid = terminal_->getShellPID();
120 if (pid > 0)
121 {
122 ::kill(-pid, SIGCONT);
123 isPaused_ = false;
124 }
125}
126
127// ==============================================================================
128// Private Slots
129// ==============================================================================
130
131void TerminalPanel::onMonitorChanged(int index)
132{
133 QString command;
134 switch (index)
135 {
136 case 0:
137 command = "btop";
138 break;
139 case 1:
140 command = "htop";
141 break;
142 case 2:
143 command = "top";
144 break;
145 case 3:
146 // Respect the user's login shell ($SHELL) rather than hard-coding
147 // bash. Picking "Shell" on a zsh/fish machine previously nested a
148 // bash inside the existing shell, which was unexpected.
149 command = QString::fromLocal8Bit(qgetenv("SHELL"));
150 if (command.isEmpty())
151 command = QStringLiteral("/bin/bash");
152 break;
153 default:
154 command = getBestMonitorCommand();
155 }
156
157 // Clear and restart with new command
158 if (terminal_)
159 {
160 // Send exit to current process and start new one
161 terminal_->sendText("exit\n");
162 QTimer::singleShot(200, this, [this, command]() { startCommand(command); });
163 }
164}
165
166void TerminalPanel::onRestartClicked()
167{
168 if (terminal_ && !currentCommand_.isEmpty())
169 {
170 // Send Ctrl+C to stop current process, then restart
171 terminal_->sendText("\x03"); // Ctrl+C
172 QTimer::singleShot(100, this,
173 [this]()
174 {
175 if (terminal_)
176 {
177 terminal_->sendText(currentCommand_ + "\n");
178 }
179 });
180 }
181}
182
183void TerminalPanel::onTerminalFinished()
184{
185 emit processFinished(0);
186}
187
188// ==============================================================================
189// Private Methods
190// ==============================================================================
191
192void TerminalPanel::setupUI()
193{
194 layout_ = new QVBoxLayout(this);
195 layout_->setContentsMargins(0, 0, 0, 0);
196 layout_->setSpacing(0);
197
198 // Create terminal widget (no internal toolbar - controls are in main toolbar)
199 terminal_ = new QTermWidget(0, this);
200 terminal_->setScrollBarPosition(QTermWidget::ScrollBarRight);
201 terminal_->setTerminalSizeHint(true); // Let widget provide better size hints
202 terminal_->setFocusPolicy(Qt::ClickFocus); // Prevent stealing focus from menu bar
203
204 // Limit scrollback buffer for performance - btop++ doesn't need history
205 // This prevents unbounded memory growth and improves rendering
206 terminal_->setHistorySize(500); // 500 lines is enough for monitor apps
207
208 // Optimized font configuration for performance
209 QFont font("Monospace", 10);
210 font.setStyleHint(QFont::Monospace);
211 font.setFixedPitch(true); // Ensure fixed pitch for terminal
212 font.setKerning(false); // Disable kerning for faster rendering
213 font.setHintingPreference(QFont::PreferNoHinting); // Faster glyph rendering
214 terminal_->setTerminalFont(font);
215
216 // Apply dark theme colors (using cached schemes)
217 applyDarkTheme();
218
219 // Connect signals
220 connect(terminal_, &QTermWidget::finished, this, &TerminalPanel::onTerminalFinished);
221
222 layout_->addWidget(terminal_);
223
224 setLayout(layout_);
225}
226
227void TerminalPanel::setupToolBar()
228{
229 toolBar_ = new QToolBar(this);
230 toolBar_->setIconSize(QSize(16, 16));
231 toolBar_->setMovable(false);
232
233 // Monitor selection combo
234 monitorCombo_ = new QComboBox(this);
235 monitorCombo_->addItem("btop++", "btop");
236 monitorCombo_->addItem("htop", "htop");
237 monitorCombo_->addItem("top", "top");
238 // "Shell" launches the user's login shell ($SHELL), falling back to
239 // /bin/bash only if the env var is unset — keeps zsh/fish users from
240 // unexpectedly landing in bash.
241 QString userShell = QString::fromLocal8Bit(qgetenv("SHELL"));
242 if (userShell.isEmpty())
243 userShell = QStringLiteral("/bin/bash");
244 monitorCombo_->addItem("Shell", userShell);
245
246 // Disable unavailable options
247 if (!isBtopAvailable())
248 {
249 auto* model = qobject_cast<QStandardItemModel*>(monitorCombo_->model());
250 if (model)
251 {
252 QStandardItem* item = model->item(0);
253 if (item)
254 {
255 item->setEnabled(false);
256 item->setText("btop++ (not installed)");
257 }
258 }
259 // Select htop or top as default
260 monitorCombo_->setCurrentIndex(isHtopAvailable() ? 1 : 2);
261 }
262
263 if (!isHtopAvailable())
264 {
265 auto* model = qobject_cast<QStandardItemModel*>(monitorCombo_->model());
266 if (model)
267 {
268 QStandardItem* item = model->item(1);
269 if (item)
270 {
271 item->setEnabled(false);
272 item->setText("htop (not installed)");
273 }
274 }
275 }
276
277 connect(monitorCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
278 &TerminalPanel::onMonitorChanged);
279
280 toolBar_->addWidget(monitorCombo_);
281 toolBar_->addSeparator();
282
283 // Restart action
284 restartAction_ = new QAction("Restart", this);
285 restartAction_->setToolTip("Restart the current monitor");
286 connect(restartAction_, &QAction::triggered, this, &TerminalPanel::onRestartClicked);
287 toolBar_->addAction(restartAction_);
288}
289
290void TerminalPanel::applyDarkTheme()
291{
292 if (!terminal_)
293 {
294 return;
295 }
296
297 // Cache available color schemes on first call (expensive to query repeatedly)
298 if (!colorSchemesCached_)
299 {
300 cachedColorSchemes_ = terminal_->availableColorSchemes();
301 colorSchemesCached_ = true;
302 }
303
304 // Prefer these dark schemes in order
305 static const QStringList preferredSchemes = {"Breeze", "Linux", "GreenOnBlack", "WhiteOnBlack",
306 "DarkPastels"};
307
308 for (const QString& preferred : preferredSchemes)
309 {
310 if (cachedColorSchemes_.contains(preferred))
311 {
312 terminal_->setColorScheme(preferred);
313 return;
314 }
315 }
316
317 // If no preferred scheme found, use first available or set colors manually
318 if (!cachedColorSchemes_.isEmpty())
319 {
320 terminal_->setColorScheme(cachedColorSchemes_.first());
321 }
322}
void processFinished(int exitCode)
Emitted when the terminal process finishes.
void resumeProcess()
Resume the terminal process Call when panel becomes visible again.
void startBtop()
Start or restart the terminal with btop++.
void pauseProcess()
Pause the terminal process (suspends btop/htop to save CPU) Call when panel is hidden or window is mi...
static bool isBtopAvailable()
Check if btop++ is available on the system.
void startCommand(const QString &command)
Start the terminal with a custom command.
TerminalPanel(QWidget *parent=nullptr)
~TerminalPanel() override
static bool isHtopAvailable()
Check if htop is available as a fallback.
static QString getBestMonitorCommand()
Get the best available system monitor command.