Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 36923e1646 | |||
| a942f8385b | |||
| 1422efdc2f | |||
| 72a2b7edd0 | |||
| d3229c7b64 | |||
| 92168ee5dc | |||
| 2181f254d2 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1 +1,2 @@
|
||||
build/
|
||||
uartscope-git/
|
||||
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(UARTScope VERSION 1.0.0 LANGUAGES CXX)
|
||||
project(UARTScope VERSION 1.1.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -12,6 +12,7 @@ find_package(Qt6 REQUIRED COMPONENTS
|
||||
Gui
|
||||
Widgets
|
||||
SerialPort
|
||||
Network
|
||||
)
|
||||
|
||||
set(SOURCES
|
||||
@@ -23,6 +24,8 @@ set(SOURCES
|
||||
src/tagwidget.cpp
|
||||
src/tagpanel.cpp
|
||||
src/connectdialog.cpp
|
||||
src/v4l2worker.cpp
|
||||
src/videowidget.cpp
|
||||
)
|
||||
|
||||
set(HEADERS
|
||||
@@ -33,9 +36,12 @@ set(HEADERS
|
||||
include/tagwidget.h
|
||||
include/tagpanel.h
|
||||
include/connectdialog.h
|
||||
include/v4l2worker.h
|
||||
include/videowidget.h
|
||||
)
|
||||
|
||||
add_executable(uartscope ${SOURCES} ${HEADERS})
|
||||
qt6_add_resources(RESOURCES resources.qrc)
|
||||
add_executable(uartscope ${SOURCES} ${HEADERS} ${RESOURCES})
|
||||
|
||||
target_include_directories(uartscope PRIVATE include)
|
||||
|
||||
@@ -44,15 +50,22 @@ target_link_libraries(uartscope PRIVATE
|
||||
Qt6::Gui
|
||||
Qt6::Widgets
|
||||
Qt6::SerialPort
|
||||
Qt6::Network
|
||||
)
|
||||
|
||||
# V4L2 uses Linux kernel headers directly (linux/videodev2.h)
|
||||
# These are part of linux-api-headers / linux-libc-dev on all major distros.
|
||||
# No additional library linkage needed.
|
||||
|
||||
# Installation
|
||||
install(TARGETS uartscope DESTINATION bin)
|
||||
|
||||
# Optional: create a .desktop file for Linux app launchers
|
||||
configure_file(
|
||||
${CMAKE_SOURCE_DIR}/uartscope.desktop.in
|
||||
${CMAKE_BINARY_DIR}/uartscope.desktop
|
||||
@ONLY
|
||||
)
|
||||
install(FILES ${CMAKE_BINARY_DIR}/uartscope.desktop DESTINATION share/applications)
|
||||
install(FILES ${CMAKE_SOURCE_DIR}/UartscopeLogo.png
|
||||
DESTINATION share/icons/hicolor/512x512/apps
|
||||
RENAME uartscope.png)
|
||||
|
||||
174
README.md
174
README.md
@@ -1,6 +1,6 @@
|
||||
# UARTScope
|
||||
|
||||
Ein moderner UART-Monitor für Linux mit Qt6-Oberfläche. Gebaut als Ersatz für minicom mit deutlich mehr Komfort – besonders nützlich bei der Entwicklung von Baremetal-Projekten wie [Chica](https://github.com/).
|
||||
Ein moderner UART-Monitor für Linux mit Qt6-Oberfläche. Gebaut als vollwertiger Ersatz für minicom – besonders nützlich bei der Entwicklung von Baremetal-Projekten wie [Chica](https://git.projekt-hirnfrei.de/diabolus/chica) (Amiga-Hardware-Nachbildung auf dem Raspberry Pi).
|
||||
|
||||
---
|
||||
|
||||
@@ -8,35 +8,47 @@ Ein moderner UART-Monitor für Linux mit Qt6-Oberfläche. Gebaut als Ersatz für
|
||||
|
||||
| Feature | Beschreibung |
|
||||
|---|---|
|
||||
| **Unbegrenzter Verlauf** | QPlainTextEdit mit unlimitierter Zeilenzahl – keine Daten gehen verloren |
|
||||
| **Horizontal + vertikal scrollen** | Kein Zeilenumbruch, voller H-Scrollbalken |
|
||||
| **Live-Logging** | Jede empfangene Zeile wird mit Zeitstempel in eine Datei geschrieben |
|
||||
| **Tag-Monitor** | Zeilen mit `[TAG]` werden abgefangen und in eigenen Panels angezeigt |
|
||||
| **Tabellenansicht** | CSV-formatierte UART-Zeilen werden in einer sortierbaren Tabelle dargestellt |
|
||||
| **Unbegrenzter Verlauf** | Kein Zeilenlimit – keine Daten gehen verloren, egal wie viel der Pi sendet |
|
||||
| **Timestamps** | Jede Zeile im Raw-View bekommt automatisch einen `hh:mm:ss.zzz`-Timestamp |
|
||||
| **Auto-Scroll** | Standardmäßig aktiv – springt automatisch ans Ende neuer Ausgaben |
|
||||
| **H + V Scrolling** | Kein Zeilenumbruch, voller horizontaler Scrollbalken |
|
||||
| **Live-Logging** | Alle empfangenen Zeilen werden mit Timestamp in eine Datei geschrieben |
|
||||
| **Tag-Monitor** | Zeilen mit `[TAG]` werden in eigenen Panels angezeigt und aktualisiert |
|
||||
| **Listen-Werte** | `;`-getrennte Werte in einem Tag werden als mehrzeilige Liste dargestellt |
|
||||
| **Tag-Filter** | Tags können aus dem Raw-View ausgeblendet werden – wird dauerhaft gespeichert |
|
||||
| **Tabellenansicht** | CSV-formatierte UART-Zeilen werden in einer Tabelle dargestellt |
|
||||
| **Suche** | Inkrementelle Volltextsuche im Raw-View |
|
||||
| **Dunkles Theme** | Fusion Dark – passt gut zur Terminal-Ästhetik |
|
||||
| **Auto-Reconnect** | Bei Verbindungsabbruch wird automatisch neu verbunden (Intervall einstellbar) |
|
||||
| **ANSI Clear-Screen** | `\033[2J\033[H` aus der Firmware leert Raw-View, Tabelle, Tag-Monitor und Video-Vorschau gleichzeitig |
|
||||
| **Copy-Buttons** | Raw-View und jedes Tag-Panel haben einen „📋 Copy"-Button |
|
||||
| **V4L2 Live Video** | HDMI-Grabber direkt eingebunden – Live-Vorschau unter dem Tag-Monitor |
|
||||
| **Screenshot** | Aktuellen Frame des HDMI-Grabbers als PNG/JPG speichern |
|
||||
| **Format-Referenz** | Eingebauter Guide (mit Kopieren-Button) für KI-kompatible UART-Formatierung |
|
||||
| **Fensterlayout** | Fenstergröße, Position, Splitter-Positionen und Tag-Filter werden beim Beenden gespeichert |
|
||||
|
||||
---
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
```bash
|
||||
# Arch (empfohlen)
|
||||
sudo pacman -S cmake qt6-base qt6-serialport
|
||||
|
||||
# Ubuntu / Debian
|
||||
sudo apt install cmake qt6-base-dev qt6-serialport-dev libqt6serialport6-dev
|
||||
|
||||
# Arch
|
||||
sudo pacman -S cmake qt6-base qt6-serialport
|
||||
|
||||
# Fedora
|
||||
sudo dnf install cmake qt6-qtbase-devel qt6-qtserialport-devel
|
||||
```
|
||||
|
||||
V4L2 benötigt keine zusätzliche Library – `linux/videodev2.h` ist Teil der Standard-Kernel-Header.
|
||||
|
||||
---
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
git clone <repo>
|
||||
git clone https://git.projekt-hirnfrei.de/diabolus/uartscope.git
|
||||
cd uartscope
|
||||
cmake -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j$(nproc)
|
||||
@@ -50,59 +62,105 @@ sudo cmake --install build
|
||||
|
||||
---
|
||||
|
||||
## Berechtigungen
|
||||
|
||||
```bash
|
||||
# UART-Port
|
||||
sudo usermod -aG dialout $USER
|
||||
|
||||
# HDMI-Grabber / V4L2
|
||||
sudo usermod -aG video $USER
|
||||
|
||||
# Einmal ausloggen / neu einloggen
|
||||
```
|
||||
|
||||
Grabber testen:
|
||||
```bash
|
||||
v4l2-ctl --list-devices # alle /dev/video* Geräte
|
||||
v4l2-ctl -d /dev/video0 --list-formats-ext # unterstützte Formate & Auflösungen
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## UART-Ausgabe formatieren
|
||||
|
||||
### Tag-Monitor (`[TAG]`)
|
||||
### Raw-View (immer aktiv)
|
||||
|
||||
Der Tag-Monitor fängt Zeilen ab, die ein Tag der Form `[TAGNAME]` enthalten.
|
||||
Das Tag erscheint weiterhin im Raw-View (eingefärbt), wird aber **zusätzlich** im Tag-Panel aktualisiert.
|
||||
Jede UART-Zeile erscheint im Raw-View mit Timestamp. Keine besondere Formatierung nötig.
|
||||
|
||||
**Watchdog-Beispiel** – dein Watchdog-Handler schickt:
|
||||
```
|
||||
[WDG] uptime=12345 free_heap=43210 load=0.82
|
||||
```
|
||||
→ UARTScope erstellt automatisch ein Panel `[WDG]` mit einer Tabelle:
|
||||
|
||||
| Key | Value |
|
||||
|---|---|
|
||||
| uptime | 12345 |
|
||||
| free_heap | 43210 |
|
||||
| load | 0.82 |
|
||||
|
||||
Jedes Update blinkt kurz grün auf – du siehst sofort, dass neue Daten angekommen sind.
|
||||
|
||||
**Mehrere Tags gleichzeitig:**
|
||||
**Screen leeren** – von der Firmware aus Raw-View, Tabelle, Tag-Monitor und Video-Vorschau gleichzeitig leeren:
|
||||
```c
|
||||
// In deinem Baremetal-Code:
|
||||
uart_printf("[WDG] uptime=%lu free=%lu\n", uptime, heap_free);
|
||||
uart_printf("[VIDEO] line=%d hblank=%d vblank=%d\n", line, hb, vb);
|
||||
uart_printf("[AUDIO] buf=%d underruns=%d\n", audio_buf, underruns);
|
||||
uart_printf("\033[2J\033[H");
|
||||
```
|
||||
Für jeden einzigartigen Tag wird automatisch ein eigenes Panel erstellt.
|
||||
|
||||
### Tag-Monitor
|
||||
|
||||
Zeilen mit `[TAGNAME]` werden im Tag-Monitor-Panel angezeigt **und** im Raw-View hervorgehoben (cyan), sofern der Tag nicht über den Tag-Filter ausgeblendet wurde.
|
||||
|
||||
**Format:** `[TAGNAME] key1=value1 key2=value2 ...`
|
||||
|
||||
- Tag-Name: Buchstaben, Ziffern, Underscore – z.B. `WDG`, `VIDEO`, `KICKSTART`
|
||||
- Key=Value-Paare: Leerzeichen-getrennt, Werte ohne Leerzeichen
|
||||
- Ohne Key=Value-Paare wird der rohe String angezeigt
|
||||
|
||||
**Listen-Werte:** Ein Wert mit `;`-getrennten Einträgen wird als mehrzeilige Liste unter dem Key dargestellt:
|
||||
|
||||
```c
|
||||
uart_printf("[KICKSTART] Devs=trackdisk.device;input.device\n");
|
||||
```
|
||||
|
||||
Im Tag-Monitor erscheint das als:
|
||||
|
||||
```
|
||||
Devs trackdisk.device
|
||||
input.device
|
||||
```
|
||||
|
||||
Jeder weitere Eintrag bekommt seine eigene Tabellenzeile, der Key wird nur einmal angezeigt.
|
||||
|
||||
**Beispiele:**
|
||||
```c
|
||||
uart_printf("[WDG] uptime=%lu free_heap=%lu temp=%d\n",
|
||||
HAL_GetTick(), xPortGetFreeHeapSize(), core_temp);
|
||||
|
||||
uart_printf("[KICKSTART] Libs=graphics.library;intuition.library;dos.library\n");
|
||||
|
||||
uart_printf("[VIDEO] line=%d hblank=%d vblank=%d copper=%d\n",
|
||||
scanline, hblank_ticks, vblank_ticks, copper_dma);
|
||||
```
|
||||
|
||||
Jeder einzigartige Tag bekommt automatisch ein eigenes Panel. Panels aktualisieren sich in-place – kein Scrollen nötig. Listen-Längen können sich von Update zu Update ändern, die Tabelle passt sich automatisch an.
|
||||
|
||||
### Tabellenansicht
|
||||
|
||||
Die Tabellenansicht erwartet CSV-Zeilen. Optionale Header-Zeile mit `#`:
|
||||
Optionale Header-Zeile mit `#`, dann CSV-Datenzeilen:
|
||||
|
||||
```
|
||||
#time_ms,temperature,voltage,current
|
||||
1000,23.5,3.30,0.42
|
||||
2000,23.7,3.31,0.41
|
||||
3000,24.1,3.29,0.43
|
||||
```
|
||||
|
||||
Delimiter ist per Dropdown umschaltbar (`,` `;` `\t` `|` `Space`).
|
||||
Delimiter per Dropdown umschaltbar: `,` `;` `\t` `|` `Space`
|
||||
|
||||
---
|
||||
|
||||
## Serielle Ports – Berechtigungen
|
||||
## Tag-Filter
|
||||
|
||||
Auf den meisten Linux-Distros muss dein User in der Gruppe `dialout` sein:
|
||||
Über „Tag filter…" in der Toolbar lassen sich Tags aus dem Raw-View ausblenden, sodass sie nur noch im Tag-Monitor erscheinen. Ein Tag pro Zeile, ohne Klammern (z.B. `WDG`). Groß-/Kleinschreibung spielt keine Rolle. Der Filter wird sofort beim Schließen des Dialogs gespeichert und beim nächsten Programmstart automatisch wiederhergestellt.
|
||||
|
||||
```bash
|
||||
sudo usermod -aG dialout $USER
|
||||
# Einmal ausloggen / neu einloggen
|
||||
```
|
||||
---
|
||||
|
||||
## Einstellungen
|
||||
|
||||
Beim Beenden werden folgende Einstellungen automatisch gespeichert und beim nächsten Start wiederhergestellt:
|
||||
|
||||
- Fenstergröße und -position
|
||||
- Splitter-Positionen (Haupt-Splitter und Tag/Video-Splitter)
|
||||
- Auto-Reconnect ein/aus und Intervall
|
||||
- Tag-Filter (ausgeblendete Tags)
|
||||
|
||||
Gespeichert unter `~/.config/ChicaDev/UARTScope.conf` (via `QSettings`).
|
||||
|
||||
---
|
||||
|
||||
@@ -111,14 +169,20 @@ sudo usermod -aG dialout $USER
|
||||
```
|
||||
uartscope/
|
||||
├── CMakeLists.txt
|
||||
├── README.md
|
||||
├── resources.qrc
|
||||
├── UartscopeLogo.png
|
||||
├── uartscope.desktop.in
|
||||
├── include/
|
||||
│ ├── mainwindow.h
|
||||
│ ├── serialworker.h ← UART-Empfang im eigenen Thread
|
||||
│ ├── rawview.h ← Unbegrenzter scrollbarer Log
|
||||
│ ├── tableview.h ← CSV → QTableWidget
|
||||
│ ├── mainwindow.h ← Hauptfenster, koordiniert alle Komponenten
|
||||
│ ├── serialworker.h ← UART-Empfang im eigenen QThread, Auto-Reconnect, ANSI-Erkennung
|
||||
│ ├── rawview.h ← Unbegrenzter Log mit Timestamps, Suche, Copy
|
||||
│ ├── tableview.h ← CSV-Parser → QTableWidget
|
||||
│ ├── tagwidget.h ← Container für Tag-Panels
|
||||
│ ├── tagpanel.h ← Ein Panel pro [TAG]
|
||||
│ └── connectdialog.h ← Port-Konfiguration
|
||||
│ ├── tagpanel.h ← Ein Panel pro [TAG], Key=Value-Tabelle mit Listen-Support, Copy
|
||||
│ ├── connectdialog.h ← Port-Konfiguration (Port, Baud, Log-Datei)
|
||||
│ ├── v4l2worker.h ← V4L2-Capture in std::thread, MJPEG/YUYV/NV12
|
||||
│ └── videowidget.h ← Live-Vorschau, Freeze, Screenshot
|
||||
└── src/
|
||||
├── main.cpp
|
||||
├── mainwindow.cpp
|
||||
@@ -127,15 +191,17 @@ uartscope/
|
||||
├── tableview.cpp
|
||||
├── tagwidget.cpp
|
||||
├── tagpanel.cpp
|
||||
└── connectdialog.cpp
|
||||
├── connectdialog.cpp
|
||||
├── v4l2worker.cpp
|
||||
└── videowidget.cpp
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Erweiterungsideen
|
||||
|
||||
- **Protokoll-Filter**: Zeilen anhand von Regex ein-/ausblenden
|
||||
- **Plot-Widget**: numerische Werte aus Tags live als Graph darstellen (Qt Charts)
|
||||
- **UART senden**: TX-Eingabezeile hinzufügen für bidirektionale Kommunikation
|
||||
- **Session-Replay**: gespeicherte Log-Dateien wieder abspielen
|
||||
- **Plot-Widget**: numerische Tag-Werte live als Graph darstellen (Qt Charts)
|
||||
- **UART senden**: TX-Eingabezeile für bidirektionale Kommunikation
|
||||
- **Hex-View**: rohe Bytes als Hex-Dump anzeigen
|
||||
- **Session-Replay**: gespeicherte Log-Dateien abspielen
|
||||
- **Regex-Filter**: Zeilen im Raw-View per regulärem Ausdruck ein-/ausblenden
|
||||
|
||||
BIN
UartscopeLogo.png
Normal file
BIN
UartscopeLogo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
@@ -4,17 +4,32 @@
|
||||
#include <QLineEdit>
|
||||
#include <QDialogButtonBox>
|
||||
#include <QFormLayout>
|
||||
#include <QTabWidget>
|
||||
#include <QSpinBox>
|
||||
#include <QSerialPort>
|
||||
#include <QSerialPortInfo>
|
||||
|
||||
struct SerialConfig {
|
||||
// Which transport to use: a real/virtual serial port, or a plain TCP
|
||||
// connection (e.g. for emulators/firmware that stream their debug
|
||||
// UART over the network, such as FS-UAE piped through socat).
|
||||
enum class ConnectionType { Serial, Network };
|
||||
ConnectionType connectionType = ConnectionType::Serial;
|
||||
|
||||
// Serial-specific
|
||||
QString portName;
|
||||
qint32 baudRate = 115200;
|
||||
QSerialPort::DataBits dataBits = QSerialPort::Data8;
|
||||
QSerialPort::Parity parity = QSerialPort::NoParity;
|
||||
QSerialPort::StopBits stopBits = QSerialPort::OneStop;
|
||||
QSerialPort::FlowControl flowControl = QSerialPort::NoFlowControl;
|
||||
QString logFilePath; // empty = no logging
|
||||
|
||||
// Network-specific
|
||||
QString networkHost;
|
||||
quint16 networkPort = 0;
|
||||
|
||||
// Common
|
||||
QString logFilePath;
|
||||
};
|
||||
|
||||
class ConnectDialog : public QDialog
|
||||
@@ -23,7 +38,6 @@ class ConnectDialog : public QDialog
|
||||
|
||||
public:
|
||||
explicit ConnectDialog(QWidget *parent = nullptr);
|
||||
|
||||
SerialConfig config() const;
|
||||
|
||||
private slots:
|
||||
@@ -31,11 +45,19 @@ private slots:
|
||||
void refreshPorts();
|
||||
|
||||
private:
|
||||
void addPtyPorts();
|
||||
|
||||
QTabWidget *m_modeTabs = nullptr;
|
||||
|
||||
QComboBox *m_portCombo = nullptr;
|
||||
QComboBox *m_baudCombo = nullptr;
|
||||
QComboBox *m_dataBitsCombo = nullptr;
|
||||
QComboBox *m_parityCombo = nullptr;
|
||||
QComboBox *m_stopBitsCombo = nullptr;
|
||||
QComboBox *m_flowCombo = nullptr;
|
||||
|
||||
QLineEdit *m_hostEdit = nullptr;
|
||||
QSpinBox *m_portSpin = nullptr;
|
||||
|
||||
QLineEdit *m_logPathEdit = nullptr;
|
||||
};
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
#pragma once
|
||||
#include <QMainWindow>
|
||||
#include <QCloseEvent>
|
||||
#include <QSettings>
|
||||
#include <QSplitter>
|
||||
#include <QThread>
|
||||
#include <QTabWidget>
|
||||
#include <QSplitter>
|
||||
#include <QStatusBar>
|
||||
#include <QToolBar>
|
||||
#include <QLabel>
|
||||
#include <QAction>
|
||||
#include <QSpinBox>
|
||||
#include <QCheckBox>
|
||||
#include <QSet>
|
||||
|
||||
#include "serialworker.h"
|
||||
#include "rawview.h"
|
||||
#include "tableview.h"
|
||||
#include "tagwidget.h"
|
||||
#include "videowidget.h"
|
||||
#include "connectdialog.h"
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
@@ -24,6 +28,9 @@ public:
|
||||
explicit MainWindow(QWidget *parent = nullptr);
|
||||
~MainWindow();
|
||||
|
||||
protected:
|
||||
void closeEvent(QCloseEvent *event) override;
|
||||
|
||||
private slots:
|
||||
void onConnectClicked();
|
||||
void onDisconnectClicked();
|
||||
@@ -35,34 +42,41 @@ private slots:
|
||||
void onNewLine(const QString &line);
|
||||
void onTagDetected(const QString &tag, const QString &value);
|
||||
void showFormatReference();
|
||||
void configureTagFilter();
|
||||
void showAbout();
|
||||
|
||||
private:
|
||||
void setupUi();
|
||||
void setupToolBar();
|
||||
void setupStatusBar();
|
||||
void clearAllViews();
|
||||
void doShutdown();
|
||||
void saveSettings();
|
||||
void restoreSettings();
|
||||
|
||||
// Worker & thread
|
||||
QThread *m_thread = nullptr;
|
||||
SerialWorker *m_worker = nullptr;
|
||||
|
||||
// Views
|
||||
RawView *m_rawView = nullptr;
|
||||
TableView *m_tableView = nullptr;
|
||||
TagWidget *m_tagWidget = nullptr;
|
||||
RawView *m_rawView = nullptr;
|
||||
TableView *m_tableView = nullptr;
|
||||
TagWidget *m_tagWidget = nullptr;
|
||||
VideoWidget *m_videoWidget= nullptr;
|
||||
|
||||
// Status bar widgets
|
||||
QLabel *m_portLabel = nullptr;
|
||||
QLabel *m_stateLabel = nullptr;
|
||||
QLabel *m_reconnectLabel = nullptr;
|
||||
QLabel *m_portLabel = nullptr;
|
||||
QLabel *m_stateLabel = nullptr;
|
||||
QLabel *m_reconnectLabel = nullptr;
|
||||
|
||||
// Toolbar widgets
|
||||
QCheckBox *m_autoReconnectCb = nullptr;
|
||||
QSpinBox *m_reconnectIntervalSb= nullptr;
|
||||
QCheckBox *m_autoReconnectCb = nullptr;
|
||||
QSpinBox *m_reconnectIntervalSb = nullptr;
|
||||
|
||||
// Actions
|
||||
QAction *m_connectAction = nullptr;
|
||||
QAction *m_disconnectAction = nullptr;
|
||||
|
||||
SerialConfig m_lastConfig;
|
||||
// Splitters (saved/restored via QSettings)
|
||||
QSplitter *m_mainSplitter = nullptr;
|
||||
QSplitter *m_rightSplitter = nullptr;
|
||||
|
||||
SerialConfig m_lastConfig;
|
||||
QSet<QString> m_suppressedTags; // tags hidden from Raw view
|
||||
bool m_shutdownDone = false;
|
||||
};
|
||||
|
||||
@@ -7,14 +7,14 @@
|
||||
#include <QPushButton>
|
||||
#include <QCheckBox>
|
||||
#include <QLabel>
|
||||
#include <QSpinBox>
|
||||
#include <QSet>
|
||||
#include <QRegularExpression>
|
||||
#include <QTextDocument>
|
||||
|
||||
// RawView shows the raw UART output in a QPlainTextEdit with:
|
||||
// - Configurable maximum line count (default: unlimited / very large)
|
||||
// - Auto-scroll that pauses when the user scrolls up
|
||||
// - Horizontal scroll (word wrap off)
|
||||
// - Incremental text search
|
||||
// - Clear button
|
||||
// RawView shows the raw UART output with timestamps, search (with next/
|
||||
// previous navigation and wrap-around), tag suppression, unlimited history,
|
||||
// H+V scrolling and a copy-to-clipboard button.
|
||||
// Auto-scroll is ON by default.
|
||||
class RawView : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
@@ -23,23 +23,36 @@ public:
|
||||
explicit RawView(QWidget *parent = nullptr);
|
||||
|
||||
public slots:
|
||||
void appendLine(const QString &line);
|
||||
void appendLine(const QString &line, const QSet<QString> &suppressedTags = {});
|
||||
void clear();
|
||||
|
||||
private slots:
|
||||
void onSearch(const QString &text);
|
||||
void onScrollValueChanged(int value);
|
||||
void onAutoScrollToggled(bool enabled);
|
||||
void copyToClipboard();
|
||||
void findNext();
|
||||
void findPrevious();
|
||||
|
||||
private:
|
||||
void setupUi();
|
||||
void applyColorScheme();
|
||||
// Searches for `text` starting at the current cursor, honouring `flags`
|
||||
// (e.g. QTextDocument::FindBackward). If nothing is found and
|
||||
// `wrapAllowed` is true, retries once from the start/end of the
|
||||
// document so search wraps around instead of dead-ending.
|
||||
bool searchAndSelect(const QString &text, QTextDocument::FindFlags flags, bool wrapAllowed);
|
||||
|
||||
QPlainTextEdit *m_textEdit = nullptr;
|
||||
QLineEdit *m_searchEdit = nullptr;
|
||||
QPushButton *m_findPrevBtn = nullptr;
|
||||
QPushButton *m_findNextBtn = nullptr;
|
||||
QPushButton *m_clearBtn = nullptr;
|
||||
QPushButton *m_copyBtn = nullptr;
|
||||
QCheckBox *m_autoScrollCb = nullptr;
|
||||
QLabel *m_lineCountLbl = nullptr;
|
||||
bool m_autoScroll = true;
|
||||
bool m_autoScroll = true; // ON by default
|
||||
int m_lineCount = 0;
|
||||
|
||||
static const QRegularExpression s_tagRe;
|
||||
};
|
||||
|
||||
@@ -2,17 +2,27 @@
|
||||
#include <QObject>
|
||||
#include <QThread>
|
||||
#include <QSerialPort>
|
||||
#include <QTcpSocket>
|
||||
#include <QAbstractSocket>
|
||||
#include <QFile>
|
||||
#include <QTextStream>
|
||||
#include <QString>
|
||||
#include <QTimer>
|
||||
|
||||
// SerialWorker lives in its own QThread and owns the QSerialPort.
|
||||
// SerialWorker lives in its own QThread and owns the actual data source,
|
||||
// which is either a QSerialPort (real/virtual serial device) or a
|
||||
// QTcpSocket (for firmware/emulators that send their debug UART over a
|
||||
// TCP connection, e.g. FS-UAE's serial-over-socat setup). Both are
|
||||
// QIODevice subclasses, so the byte-parsing pipeline below (line
|
||||
// buffering, ANSI stripping, tag detection, logging) is shared as-is
|
||||
// between the two transports; only opening/closing/reconnect handling
|
||||
// differs.
|
||||
//
|
||||
// It emits newLine() for every complete line received,
|
||||
// tagDetected() when a line contains a recognised tag like [WDG],
|
||||
// and clearScreen() when the ANSI clear-screen sequence \033[2J is received.
|
||||
// Auto-reconnect: if the port drops unexpectedly (e.g. USB cable pulled),
|
||||
// the worker retries every reconnectIntervalMs until success or closePort().
|
||||
// and clearScreen() when an ANSI clear-screen sequence is received.
|
||||
// Auto-reconnect: if the connection drops unexpectedly, the worker
|
||||
// retries every reconnectIntervalMs until success or closePort().
|
||||
class SerialWorker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
@@ -21,9 +31,8 @@ public:
|
||||
explicit SerialWorker(QObject *parent = nullptr);
|
||||
~SerialWorker();
|
||||
|
||||
// Auto-reconnect configuration (call before openPort, or any time)
|
||||
void setAutoReconnect(bool enabled) { m_autoReconnect = enabled; }
|
||||
void setReconnectInterval(int ms) { m_reconnectIntervalMs = ms; }
|
||||
void setAutoReconnect(bool enabled) { m_autoReconnect = enabled; }
|
||||
void setReconnectInterval(int ms) { m_reconnectIntervalMs = ms; }
|
||||
|
||||
public slots:
|
||||
void openPort(const QString &portName, qint32 baudRate,
|
||||
@@ -31,46 +40,75 @@ public slots:
|
||||
QSerialPort::Parity parity,
|
||||
QSerialPort::StopBits stopBits,
|
||||
QSerialPort::FlowControl flowControl);
|
||||
void closePort(); // explicit user disconnect – stops reconnect
|
||||
void openNetwork(const QString &host, quint16 port);
|
||||
void closePort();
|
||||
void setLogFile(const QString &path);
|
||||
void stopLogging();
|
||||
|
||||
signals:
|
||||
void newLine(const QString &line);
|
||||
void tagDetected(const QString &tag, const QString &value);
|
||||
void clearScreen(); // emitted when \033[2J\033[H (or \033[2J alone) is received
|
||||
void clearScreen();
|
||||
void portOpened();
|
||||
void portClosed();
|
||||
void reconnecting(int attempt); // fired each retry attempt
|
||||
void reconnecting(int attempt);
|
||||
void errorOccurred(const QString &message);
|
||||
|
||||
private slots:
|
||||
void onReadyRead();
|
||||
void onPortError(QSerialPort::SerialPortError err);
|
||||
void onSocketConnected();
|
||||
void onSocketDisconnected();
|
||||
void onSocketError(QAbstractSocket::SocketError err);
|
||||
void tryReconnect();
|
||||
void flushScanTail();
|
||||
|
||||
private:
|
||||
enum class ConnectionMode { Serial, Network };
|
||||
|
||||
void processRawData(const QByteArray &data);
|
||||
void appendToLineBuffer(const QByteArray &toProcess);
|
||||
void processLine(const QString &line);
|
||||
void scheduleReconnect();
|
||||
|
||||
QSerialPort *m_port = nullptr;
|
||||
QFile *m_logFile = nullptr;
|
||||
ConnectionMode m_mode = ConnectionMode::Serial;
|
||||
|
||||
QSerialPort *m_port = nullptr;
|
||||
QTcpSocket *m_socket = nullptr;
|
||||
// Points at whichever of m_port/m_socket is the currently active data
|
||||
// source; onReadyRead() reads from this without caring which it is.
|
||||
QIODevice *m_device = nullptr;
|
||||
|
||||
QFile *m_logFile = nullptr;
|
||||
QTextStream *m_logStream = nullptr;
|
||||
QString m_buffer;
|
||||
QByteArray m_scanTail; // carries partial ANSI sequences across reads
|
||||
|
||||
// Reconnect state
|
||||
QTimer *m_reconnectTimer = nullptr;
|
||||
bool m_autoReconnect = true;
|
||||
bool m_userDisconnected = false; // true only after explicit closePort()
|
||||
int m_reconnectIntervalMs = 2000;
|
||||
int m_reconnectAttempt = 0;
|
||||
// If no further bytes arrive shortly after some data was held back in
|
||||
// m_scanTail (to safely detect a possibly-split ANSI sequence), this
|
||||
// timer fires and flushes that tail through the normal line-processing
|
||||
// path anyway. Without this, the last line(s) of a burst can sit stuck
|
||||
// in m_scanTail indefinitely if the sender goes quiet (e.g. a device
|
||||
// that streams a final line and then stops) and only surface once new
|
||||
// bytes eventually arrive (e.g. after a reboot).
|
||||
QTimer *m_idleFlushTimer = nullptr;
|
||||
static constexpr int kIdleFlushMs = 50;
|
||||
|
||||
// Saved config for reconnect
|
||||
QTimer *m_reconnectTimer = nullptr;
|
||||
bool m_autoReconnect = true;
|
||||
bool m_userDisconnected = false;
|
||||
int m_reconnectIntervalMs = 2000;
|
||||
int m_reconnectAttempt = 0;
|
||||
|
||||
// Serial-specific connection parameters
|
||||
QString m_portName;
|
||||
qint32 m_baudRate = 115200;
|
||||
QSerialPort::DataBits m_dataBits = QSerialPort::Data8;
|
||||
QSerialPort::Parity m_parity = QSerialPort::NoParity;
|
||||
QSerialPort::StopBits m_stopBits = QSerialPort::OneStop;
|
||||
QSerialPort::FlowControl m_flowControl= QSerialPort::NoFlowControl;
|
||||
qint32 m_baudRate = 115200;
|
||||
QSerialPort::DataBits m_dataBits = QSerialPort::Data8;
|
||||
QSerialPort::Parity m_parity = QSerialPort::NoParity;
|
||||
QSerialPort::StopBits m_stopBits = QSerialPort::OneStop;
|
||||
QSerialPort::FlowControl m_flowControl = QSerialPort::NoFlowControl;
|
||||
|
||||
// Network-specific connection parameters
|
||||
QString m_networkHost;
|
||||
quint16 m_networkPort = 0;
|
||||
};
|
||||
|
||||
@@ -10,13 +10,6 @@
|
||||
#include <QComboBox>
|
||||
|
||||
// TableView interprets UART lines as delimited data and shows them in a table.
|
||||
// The first line that matches the column count is used as the header row if it
|
||||
// starts with '#'. Otherwise column names are auto-generated (Col 1, Col 2, …).
|
||||
//
|
||||
// Supported delimiters: comma, semicolon, tab, pipe, space
|
||||
// To use: send lines like:
|
||||
// #time,temp,voltage,current
|
||||
// 1234,23.5,3.3,0.42
|
||||
class TableView : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
@@ -37,16 +30,16 @@ private:
|
||||
void parseHeaders(const QString &line);
|
||||
bool tryAppendRow(const QString &line);
|
||||
|
||||
QTableWidget *m_table = nullptr;
|
||||
QComboBox *m_delimCombo = nullptr;
|
||||
QLineEdit *m_maxRowsEdit = nullptr;
|
||||
QPushButton *m_clearBtn = nullptr;
|
||||
QCheckBox *m_autoScrollCb = nullptr;
|
||||
QTableWidget *m_table = nullptr;
|
||||
QComboBox *m_delimCombo = nullptr;
|
||||
QLineEdit *m_maxRowsEdit = nullptr;
|
||||
QPushButton *m_clearBtn = nullptr;
|
||||
QCheckBox *m_autoScrollCb = nullptr;
|
||||
|
||||
QStringList m_headers;
|
||||
QList<QStringList> m_rows; // raw data for rebuild
|
||||
int m_maxRows = 500;
|
||||
char m_delimiter = ',';
|
||||
QList<QStringList> m_rows;
|
||||
int m_maxRows = 500;
|
||||
char m_delimiter = ',';
|
||||
bool m_autoScroll = true;
|
||||
bool m_headersSet = false;
|
||||
};
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
#pragma once
|
||||
#include <QWidget>
|
||||
#include <QGroupBox>
|
||||
#include <QLabel>
|
||||
#include <QVBoxLayout>
|
||||
#include <QHBoxLayout>
|
||||
#include <QDateTime>
|
||||
#include <QList>
|
||||
#include <QPair>
|
||||
#include <QPushButton>
|
||||
#include <QTableWidget>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QTabWidget>
|
||||
#include <QStringList>
|
||||
#include <QMap>
|
||||
|
||||
// TagPanel displays the most recent data associated with a single tag (e.g. [WDG]).
|
||||
// Values are parsed as key=value pairs, or shown as a raw string if no '=' is found.
|
||||
// Example input line: [WDG] uptime=1234 temp=42.1 load=0.8
|
||||
// TagPanel displays the data received for a single tag (e.g. [WDG]) in two
|
||||
// tabs:
|
||||
// - "Aktuell": the most recent value(s), updating in-place (a table for
|
||||
// key=value pairs, or a plain label for raw/free-form content). If a
|
||||
// value contains ';', it is treated as a LIST: the key is shown once
|
||||
// and each list element gets its own row below it (key cell left empty
|
||||
// for the continuation rows, like a merged-cell look).
|
||||
// Example: Devs=trackdisk.device;input.device
|
||||
// Devs trackdisk.device
|
||||
// input.device
|
||||
// - "Verlauf": every value ever received for this tag, timestamped, in
|
||||
// receive order - so you can see the full runtime history rather than
|
||||
// just the latest snapshot.
|
||||
class TagPanel : public QGroupBox
|
||||
{
|
||||
Q_OBJECT
|
||||
@@ -24,14 +35,32 @@ public:
|
||||
public slots:
|
||||
void update(const QString &value);
|
||||
|
||||
private slots:
|
||||
void copyToClipboard();
|
||||
void clearHistory();
|
||||
|
||||
private:
|
||||
void parseKeyValue(const QString &value);
|
||||
void showRaw(const QString &value);
|
||||
void ensureRow(const QString &key);
|
||||
// Replaces all rows belonging to `key` with one row per value in `values`.
|
||||
void setKeyValues(const QString &key, const QStringList &values);
|
||||
// Appends a timestamped entry for `value` to the "Verlauf" tab.
|
||||
void appendHistory(const QString &value);
|
||||
|
||||
QString m_tag;
|
||||
QTableWidget *m_table = nullptr;
|
||||
QLabel *m_rawLabel = nullptr;
|
||||
QLabel *m_timestampLabel = nullptr;
|
||||
QStringList m_keys; // ordered list for row lookup
|
||||
QTabWidget *m_tabs = nullptr;
|
||||
QTableWidget *m_table = nullptr;
|
||||
QLabel *m_rawLabel = nullptr;
|
||||
QPlainTextEdit *m_historyEdit = nullptr;
|
||||
int m_historyCount = 0;
|
||||
|
||||
// Cap history growth for very chatty/long-running tags so memory use
|
||||
// stays bounded; oldest entries are dropped first (FIFO).
|
||||
static constexpr int kMaxHistoryEntries = 5000;
|
||||
|
||||
// Track which table rows belong to which key, so repeated updates can
|
||||
// replace the previous rows instead of appending duplicates.
|
||||
// Maps key -> (first row index, row count)
|
||||
struct KeyRange { int firstRow; int count; };
|
||||
QMap<QString, KeyRange> m_keyRanges;
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <QVBoxLayout>
|
||||
#include <QHBoxLayout>
|
||||
#include <QPushButton>
|
||||
#include <QLineEdit>
|
||||
#include <QLabel>
|
||||
#include <QMap>
|
||||
#include <QString>
|
||||
|
||||
@@ -25,6 +25,6 @@ public slots:
|
||||
void removeTag(const QString &tag);
|
||||
|
||||
private:
|
||||
QVBoxLayout *m_panelLayout = nullptr;
|
||||
QVBoxLayout *m_panelLayout = nullptr;
|
||||
QMap<QString, TagPanel*> m_panels;
|
||||
};
|
||||
|
||||
49
include/v4l2worker.h
Normal file
49
include/v4l2worker.h
Normal file
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include <QObject>
|
||||
#include <QImage>
|
||||
#include <QString>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
|
||||
class V4l2Worker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit V4l2Worker(QObject *parent = nullptr);
|
||||
~V4l2Worker();
|
||||
|
||||
public slots:
|
||||
void startCapture(const QString &device, int width = 1920, int height = 1080);
|
||||
void stopCapture();
|
||||
|
||||
signals:
|
||||
void newFrame(const QImage &frame);
|
||||
void captureStarted(const QString &device, int width, int height, const QString &format);
|
||||
void captureStopped();
|
||||
void errorOccurred(const QString &message);
|
||||
|
||||
private:
|
||||
void stop();
|
||||
void captureLoop();
|
||||
bool openDevice(const QString &device, int width, int height);
|
||||
void closeDevice();
|
||||
bool initMmap();
|
||||
void freeMmap();
|
||||
QImage convertToImage(const void *data, size_t size, int width, int height);
|
||||
QImage yuyv2Rgb(const uchar *src, int width, int height);
|
||||
QImage nv122Rgb(const uchar *src, int width, int height);
|
||||
|
||||
int m_fd = -1;
|
||||
int m_width = 1920;
|
||||
int m_height = 1080;
|
||||
uint32_t m_pixFmt = 0;
|
||||
|
||||
static constexpr int MMAP_BUFFERS = 4;
|
||||
struct MmapBuffer { void *start = nullptr; size_t length = 0; };
|
||||
MmapBuffer m_buffers[MMAP_BUFFERS];
|
||||
int m_nBuffers = 0;
|
||||
|
||||
std::atomic<bool> m_running{false};
|
||||
std::thread m_captureThread;
|
||||
};
|
||||
79
include/videowidget.h
Normal file
79
include/videowidget.h
Normal file
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
#include <QWidget>
|
||||
#include <QImage>
|
||||
#include <QSize>
|
||||
#include <QLabel>
|
||||
#include <QPushButton>
|
||||
#include <QComboBox>
|
||||
#include <QHBoxLayout>
|
||||
#include <QVBoxLayout>
|
||||
#include <QThread>
|
||||
#include <QProcess>
|
||||
|
||||
#include "v4l2worker.h"
|
||||
|
||||
// VideoWidget shows the live V4L2 preview and can additionally record it
|
||||
// to an MP4 file. Recording works by piping raw BGRA frames into an
|
||||
// external `ffmpeg` process (via QProcess/stdin), which encodes them to
|
||||
// H.264/MP4 - this avoids reimplementing video encoding and just needs
|
||||
// ffmpeg to be installed and on PATH.
|
||||
class VideoWidget : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit VideoWidget(QWidget *parent = nullptr);
|
||||
~VideoWidget();
|
||||
|
||||
public:
|
||||
void shutdown(); // safe to call multiple times, called from MainWindow::closeEvent
|
||||
|
||||
public slots:
|
||||
void onNewFrame(const QImage &frame);
|
||||
void clearFrame(); // blanks the preview (used on ANSI clear-screen)
|
||||
|
||||
private slots:
|
||||
void onStartStop();
|
||||
void onFreeze(bool frozen);
|
||||
void onScreenshot();
|
||||
void onRecordToggled(bool checked);
|
||||
void refreshDeviceList();
|
||||
|
||||
protected:
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
void resizeEvent(QResizeEvent *event) override;
|
||||
|
||||
private:
|
||||
void setupUi();
|
||||
void startCapture();
|
||||
void stopCapture();
|
||||
void updateScaled();
|
||||
void startRecording();
|
||||
void stopRecording();
|
||||
void writeRecordingFrame(const QImage &frame);
|
||||
|
||||
QThread *m_thread = nullptr;
|
||||
V4l2Worker *m_worker = nullptr;
|
||||
|
||||
QImage m_frame;
|
||||
QImage m_scaled;
|
||||
bool m_frozen = false;
|
||||
bool m_running = false;
|
||||
bool m_shutdownDone = false;
|
||||
|
||||
QComboBox *m_deviceCombo = nullptr;
|
||||
QPushButton *m_startBtn = nullptr;
|
||||
QPushButton *m_freezeBtn = nullptr;
|
||||
QPushButton *m_screenshotBtn = nullptr;
|
||||
QPushButton *m_recordBtn = nullptr;
|
||||
QLabel *m_infoLabel = nullptr;
|
||||
|
||||
// Recording state. m_recordProcess is the running ffmpeg instance (or
|
||||
// nullptr when not recording); m_recordSize is the frame size the
|
||||
// recording was started with, so a mid-stream resolution change (which
|
||||
// ffmpeg's raw pipe can't handle) can be detected and the recording
|
||||
// stopped cleanly instead of corrupting the output file.
|
||||
QProcess *m_recordProcess = nullptr;
|
||||
bool m_recording = false;
|
||||
QSize m_recordSize;
|
||||
};
|
||||
5
resources.qrc
Normal file
5
resources.qrc
Normal file
@@ -0,0 +1,5 @@
|
||||
<RCC>
|
||||
<qresource prefix="/icons">
|
||||
<file>UartscopeLogo.png</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -2,34 +2,36 @@
|
||||
#include <QPushButton>
|
||||
#include <QHBoxLayout>
|
||||
#include <QVBoxLayout>
|
||||
#include <QGroupBox>
|
||||
#include <QFileDialog>
|
||||
#include <QLabel>
|
||||
#include <QDir>
|
||||
#include <algorithm>
|
||||
|
||||
ConnectDialog::ConnectDialog(QWidget *parent)
|
||||
: QDialog(parent)
|
||||
{
|
||||
setWindowTitle(tr("Connect to UART"));
|
||||
setMinimumWidth(360);
|
||||
setWindowTitle(tr("Connect to UARTScope input"));
|
||||
setMinimumWidth(380);
|
||||
|
||||
auto *form = new QFormLayout();
|
||||
m_modeTabs = new QTabWidget(this);
|
||||
|
||||
// ── "Seriell" tab: real or virtual (PTY) serial port ────────────────
|
||||
auto *serialTab = new QWidget(m_modeTabs);
|
||||
auto *form = new QFormLayout(serialTab);
|
||||
form->setRowWrapPolicy(QFormLayout::DontWrapRows);
|
||||
form->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
|
||||
|
||||
// ── Port ──────────────────────────────────────────────────────────────────
|
||||
auto *portRow = new QHBoxLayout();
|
||||
m_portCombo = new QComboBox(this);
|
||||
m_portCombo = new QComboBox(serialTab);
|
||||
m_portCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
|
||||
auto *refreshBtn = new QPushButton(tr("↻"), this);
|
||||
auto *refreshBtn = new QPushButton(tr("↻"), serialTab);
|
||||
refreshBtn->setMaximumWidth(30);
|
||||
refreshBtn->setToolTip(tr("Refresh port list"));
|
||||
connect(refreshBtn, &QPushButton::clicked, this, &ConnectDialog::refreshPorts);
|
||||
portRow->addWidget(m_portCombo, 1);
|
||||
portRow->addWidget(refreshBtn);
|
||||
form->addRow(tr("Port:"), portRow);
|
||||
|
||||
// ── Baud rate ─────────────────────────────────────────────────────────────
|
||||
m_baudCombo = new QComboBox(this);
|
||||
m_baudCombo = new QComboBox(serialTab);
|
||||
const QList<int> bauds = {1200, 2400, 4800, 9600, 19200, 38400,
|
||||
57600, 115200, 230400, 460800, 921600};
|
||||
for (int b : bauds)
|
||||
@@ -37,8 +39,7 @@ ConnectDialog::ConnectDialog(QWidget *parent)
|
||||
m_baudCombo->setCurrentText("115200");
|
||||
form->addRow(tr("Baud rate:"), m_baudCombo);
|
||||
|
||||
// ── Data bits ─────────────────────────────────────────────────────────────
|
||||
m_dataBitsCombo = new QComboBox(this);
|
||||
m_dataBitsCombo = new QComboBox(serialTab);
|
||||
m_dataBitsCombo->addItem("5", QSerialPort::Data5);
|
||||
m_dataBitsCombo->addItem("6", QSerialPort::Data6);
|
||||
m_dataBitsCombo->addItem("7", QSerialPort::Data7);
|
||||
@@ -46,8 +47,7 @@ ConnectDialog::ConnectDialog(QWidget *parent)
|
||||
m_dataBitsCombo->setCurrentText("8");
|
||||
form->addRow(tr("Data bits:"), m_dataBitsCombo);
|
||||
|
||||
// ── Parity ────────────────────────────────────────────────────────────────
|
||||
m_parityCombo = new QComboBox(this);
|
||||
m_parityCombo = new QComboBox(serialTab);
|
||||
m_parityCombo->addItem(tr("None"), QSerialPort::NoParity);
|
||||
m_parityCombo->addItem(tr("Even"), QSerialPort::EvenParity);
|
||||
m_parityCombo->addItem(tr("Odd"), QSerialPort::OddParity);
|
||||
@@ -55,21 +55,52 @@ ConnectDialog::ConnectDialog(QWidget *parent)
|
||||
m_parityCombo->addItem(tr("Mark"), QSerialPort::MarkParity);
|
||||
form->addRow(tr("Parity:"), m_parityCombo);
|
||||
|
||||
// ── Stop bits ─────────────────────────────────────────────────────────────
|
||||
m_stopBitsCombo = new QComboBox(this);
|
||||
m_stopBitsCombo = new QComboBox(serialTab);
|
||||
m_stopBitsCombo->addItem("1", QSerialPort::OneStop);
|
||||
m_stopBitsCombo->addItem("1.5", QSerialPort::OneAndHalfStop);
|
||||
m_stopBitsCombo->addItem("2", QSerialPort::TwoStop);
|
||||
form->addRow(tr("Stop bits:"), m_stopBitsCombo);
|
||||
|
||||
// ── Flow control ──────────────────────────────────────────────────────────
|
||||
m_flowCombo = new QComboBox(this);
|
||||
m_flowCombo = new QComboBox(serialTab);
|
||||
m_flowCombo->addItem(tr("None"), QSerialPort::NoFlowControl);
|
||||
m_flowCombo->addItem(tr("RTS/CTS"), QSerialPort::HardwareControl);
|
||||
m_flowCombo->addItem(tr("XON/XOFF"), QSerialPort::SoftwareControl);
|
||||
form->addRow(tr("Flow control:"), m_flowCombo);
|
||||
|
||||
// ── Log file ──────────────────────────────────────────────────────────────
|
||||
m_modeTabs->addTab(serialTab, tr("Seriell"));
|
||||
|
||||
// ── "Netzwerk (TCP)" tab: e.g. FS-UAE's serial-over-socat output ────
|
||||
auto *networkTab = new QWidget(m_modeTabs);
|
||||
auto *netForm = new QFormLayout(networkTab);
|
||||
netForm->setRowWrapPolicy(QFormLayout::DontWrapRows);
|
||||
netForm->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
|
||||
|
||||
m_hostEdit = new QLineEdit(networkTab);
|
||||
m_hostEdit->setPlaceholderText(tr("z. B. localhost oder 192.168.1.50"));
|
||||
m_hostEdit->setText("localhost");
|
||||
netForm->addRow(tr("Host / IP:"), m_hostEdit);
|
||||
|
||||
m_portSpin = new QSpinBox(networkTab);
|
||||
m_portSpin->setRange(1, 65535);
|
||||
m_portSpin->setValue(1234);
|
||||
netForm->addRow(tr("Port:"), m_portSpin);
|
||||
|
||||
auto *netInfoLabel = new QLabel(
|
||||
tr("Für Emulatoren/Firmware, die die UART-Ausgabe über TCP senden "
|
||||
"statt über ein echtes serielles Gerät (z. B. FS-UAE, dessen "
|
||||
"serielle Schnittstelle per <tt>socat</tt> auf einen TCP-Port "
|
||||
"gelegt wird): hier Host und Port statt eines seriellen Ports "
|
||||
"angeben. Baudrate/Parität etc. spielen dabei keine Rolle."),
|
||||
networkTab);
|
||||
netInfoLabel->setWordWrap(true);
|
||||
netInfoLabel->setStyleSheet("color: gray; font-size: 10px;");
|
||||
netForm->addRow(netInfoLabel);
|
||||
|
||||
m_modeTabs->addTab(networkTab, tr("Netzwerk (TCP)"));
|
||||
|
||||
// ── shared: log file (applies to either transport) ──────────────────
|
||||
auto *logForm = new QFormLayout();
|
||||
logForm->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
|
||||
auto *logRow = new QHBoxLayout();
|
||||
m_logPathEdit = new QLineEdit(this);
|
||||
m_logPathEdit->setPlaceholderText(tr("(optional) path/to/output.log"));
|
||||
@@ -78,16 +109,16 @@ ConnectDialog::ConnectDialog(QWidget *parent)
|
||||
connect(browseBtn, &QPushButton::clicked, this, &ConnectDialog::browseLogFile);
|
||||
logRow->addWidget(m_logPathEdit, 1);
|
||||
logRow->addWidget(browseBtn);
|
||||
form->addRow(tr("Log file:"), logRow);
|
||||
logForm->addRow(tr("Log file:"), logRow);
|
||||
|
||||
// ── Buttons ───────────────────────────────────────────────────────────────
|
||||
auto *buttons = new QDialogButtonBox(
|
||||
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
|
||||
connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
|
||||
connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
|
||||
|
||||
auto *mainLayout = new QVBoxLayout(this);
|
||||
mainLayout->addLayout(form);
|
||||
mainLayout->addWidget(m_modeTabs);
|
||||
mainLayout->addLayout(logForm);
|
||||
mainLayout->addWidget(buttons);
|
||||
|
||||
refreshPorts();
|
||||
@@ -101,10 +132,47 @@ void ConnectDialog::refreshPorts()
|
||||
m_portCombo->addItem(
|
||||
QStringLiteral("%1 — %2").arg(info.portName(), info.description()),
|
||||
info.portName());
|
||||
|
||||
// QSerialPortInfo::availablePorts() relies on udev/sysfs and does not
|
||||
// enumerate pseudo-terminals, so PTY slaves (e.g. the ones created by
|
||||
// `qemu -serial pty`) never show up above. Scan /dev/pts/ ourselves and
|
||||
// list the numeric slave nodes as additional selectable "ports". Store
|
||||
// the full path (e.g. "/dev/pts/4") as the item data so it is passed
|
||||
// straight through to QSerialPort::setPortName(), which accepts either
|
||||
// a bare name or a full system location. Baud/parity/etc. settings are
|
||||
// simply no-ops on a PTY, which is fine for this use case.
|
||||
addPtyPorts();
|
||||
|
||||
if (m_portCombo->count() == 0)
|
||||
m_portCombo->addItem(tr("(no ports found)"), QString());
|
||||
}
|
||||
|
||||
void ConnectDialog::addPtyPorts()
|
||||
{
|
||||
QDir ptsDir("/dev/pts");
|
||||
if (!ptsDir.exists())
|
||||
return;
|
||||
|
||||
// Entries are purely numeric device nodes (the "ptmx" master control
|
||||
// device is excluded on purpose - it isn't a connectable endpoint).
|
||||
QStringList nodes = ptsDir.entryList(QDir::System | QDir::NoDotAndDotDot);
|
||||
QList<int> numbers;
|
||||
for (const QString &node : std::as_const(nodes)) {
|
||||
bool ok = false;
|
||||
const int n = node.toInt(&ok);
|
||||
if (ok)
|
||||
numbers << n;
|
||||
}
|
||||
std::sort(numbers.begin(), numbers.end());
|
||||
|
||||
for (int n : std::as_const(numbers)) {
|
||||
const QString path = QStringLiteral("/dev/pts/%1").arg(n);
|
||||
m_portCombo->addItem(
|
||||
QStringLiteral("%1 — pseudo-terminal (e.g. qemu -serial pty)").arg(path),
|
||||
path);
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectDialog::browseLogFile()
|
||||
{
|
||||
const QString path = QFileDialog::getSaveFileName(
|
||||
@@ -117,12 +185,20 @@ void ConnectDialog::browseLogFile()
|
||||
SerialConfig ConnectDialog::config() const
|
||||
{
|
||||
SerialConfig cfg;
|
||||
cfg.connectionType = (m_modeTabs->currentIndex() == 1)
|
||||
? SerialConfig::ConnectionType::Network
|
||||
: SerialConfig::ConnectionType::Serial;
|
||||
|
||||
cfg.portName = m_portCombo->currentData().toString();
|
||||
cfg.baudRate = m_baudCombo->currentData().toInt();
|
||||
cfg.dataBits = static_cast<QSerialPort::DataBits>(m_dataBitsCombo->currentData().toInt());
|
||||
cfg.parity = static_cast<QSerialPort::Parity>(m_parityCombo->currentData().toInt());
|
||||
cfg.stopBits = static_cast<QSerialPort::StopBits>(m_stopBitsCombo->currentData().toInt());
|
||||
cfg.flowControl = static_cast<QSerialPort::FlowControl>(m_flowCombo->currentData().toInt());
|
||||
|
||||
cfg.networkHost = m_hostEdit->text().trimmed();
|
||||
cfg.networkPort = static_cast<quint16>(m_portSpin->value());
|
||||
|
||||
cfg.logFilePath = m_logPathEdit->text().trimmed();
|
||||
return cfg;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
#include <QApplication>
|
||||
#include <QStyleFactory>
|
||||
#include <QIcon>
|
||||
#include "mainwindow.h"
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication app(argc, argv);
|
||||
app.setApplicationName("UARTScope");
|
||||
app.setApplicationVersion("1.0.0");
|
||||
app.setApplicationVersion("1.1.0");
|
||||
app.setOrganizationName("ChicaDev");
|
||||
|
||||
// Prefer Fusion style for consistent cross-distro look
|
||||
app.setStyle(QStyleFactory::create("Fusion"));
|
||||
|
||||
// Optional: dark palette (comment out if you prefer system theme)
|
||||
const QIcon appIcon(":/icons/UartscopeLogo.png");
|
||||
app.setWindowIcon(appIcon);
|
||||
|
||||
QPalette darkPalette;
|
||||
darkPalette.setColor(QPalette::Window, QColor(0x2b, 0x2b, 0x2b));
|
||||
darkPalette.setColor(QPalette::WindowText, QColor(0xdc, 0xdc, 0xdc));
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <QClipboard>
|
||||
#include <QDialog>
|
||||
#include <QDialogButtonBox>
|
||||
#include <QGridLayout>
|
||||
#include <QLabel>
|
||||
#include <QMessageBox>
|
||||
#include <QMetaObject>
|
||||
@@ -13,6 +14,7 @@
|
||||
#include <QVBoxLayout>
|
||||
#include <QHBoxLayout>
|
||||
#include <QFont>
|
||||
#include <QPixmap>
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent)
|
||||
: QMainWindow(parent)
|
||||
@@ -23,8 +25,8 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
setupUi();
|
||||
setupToolBar();
|
||||
setupStatusBar();
|
||||
restoreSettings();
|
||||
|
||||
// ── Worker thread ─────────────────────────────────────────────────────────
|
||||
m_thread = new QThread(this);
|
||||
m_worker = new SerialWorker();
|
||||
m_worker->moveToThread(m_thread);
|
||||
@@ -44,15 +46,40 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
QMetaObject::invokeMethod(m_worker, "closePort", Qt::BlockingQueuedConnection);
|
||||
m_thread->quit();
|
||||
m_thread->wait(3000);
|
||||
doShutdown();
|
||||
}
|
||||
|
||||
void MainWindow::closeEvent(QCloseEvent *event)
|
||||
{
|
||||
doShutdown();
|
||||
event->accept();
|
||||
}
|
||||
|
||||
void MainWindow::doShutdown()
|
||||
{
|
||||
if (m_shutdownDone)
|
||||
return;
|
||||
m_shutdownDone = true;
|
||||
|
||||
saveSettings();
|
||||
|
||||
if (m_videoWidget)
|
||||
m_videoWidget->shutdown();
|
||||
|
||||
if (m_thread && m_thread->isRunning()) {
|
||||
QMetaObject::invokeMethod(m_worker, "closePort", Qt::BlockingQueuedConnection);
|
||||
m_thread->quit();
|
||||
m_thread->wait(5000);
|
||||
if (m_thread->isRunning())
|
||||
m_thread->terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::setupUi()
|
||||
{
|
||||
auto *mainSplitter = new QSplitter(Qt::Horizontal, this);
|
||||
mainSplitter->setHandleWidth(5);
|
||||
m_mainSplitter = new QSplitter(Qt::Horizontal, this);
|
||||
m_mainSplitter->setHandleWidth(5);
|
||||
auto *mainSplitter = m_mainSplitter;
|
||||
|
||||
auto *tabs = new QTabWidget(mainSplitter);
|
||||
tabs->setTabPosition(QTabWidget::South);
|
||||
@@ -63,12 +90,24 @@ void MainWindow::setupUi()
|
||||
m_tableView = new TableView(tabs);
|
||||
tabs->addTab(m_tableView, tr("Table view"));
|
||||
|
||||
m_tagWidget = new TagWidget(mainSplitter);
|
||||
m_tagWidget->setMinimumWidth(220);
|
||||
m_tagWidget->setMaximumWidth(420);
|
||||
m_rightSplitter = new QSplitter(Qt::Vertical, mainSplitter);
|
||||
auto *rightSplitter = m_rightSplitter;
|
||||
rightSplitter->setHandleWidth(5);
|
||||
rightSplitter->setMinimumWidth(240);
|
||||
rightSplitter->setMaximumWidth(480);
|
||||
|
||||
m_tagWidget = new TagWidget(rightSplitter);
|
||||
m_videoWidget = new VideoWidget(rightSplitter);
|
||||
m_videoWidget->setMinimumHeight(160);
|
||||
|
||||
rightSplitter->addWidget(m_tagWidget);
|
||||
rightSplitter->addWidget(m_videoWidget);
|
||||
rightSplitter->setStretchFactor(0, 1);
|
||||
rightSplitter->setStretchFactor(1, 1);
|
||||
rightSplitter->setSizes({330, 330});
|
||||
|
||||
mainSplitter->addWidget(tabs);
|
||||
mainSplitter->addWidget(m_tagWidget);
|
||||
mainSplitter->addWidget(rightSplitter);
|
||||
mainSplitter->setStretchFactor(0, 3);
|
||||
mainSplitter->setStretchFactor(1, 1);
|
||||
|
||||
@@ -78,6 +117,7 @@ void MainWindow::setupUi()
|
||||
void MainWindow::setupToolBar()
|
||||
{
|
||||
auto *tb = addToolBar(tr("Main"));
|
||||
tb->setObjectName("mainToolBar"); // required by QMainWindow::saveState()
|
||||
tb->setMovable(false);
|
||||
|
||||
m_connectAction = tb->addAction(tr("Connect…"));
|
||||
@@ -95,7 +135,6 @@ void MainWindow::setupToolBar()
|
||||
|
||||
tb->addSeparator();
|
||||
|
||||
// ── Auto-reconnect controls ───────────────────────────────────────────────
|
||||
m_autoReconnectCb = new QCheckBox(tr("Auto-reconnect"), tb);
|
||||
m_autoReconnectCb->setChecked(true);
|
||||
m_autoReconnectCb->setToolTip(tr("Automatically reconnect when the port drops"));
|
||||
@@ -113,7 +152,6 @@ void MainWindow::setupToolBar()
|
||||
m_reconnectIntervalSb->setSingleStep(500);
|
||||
m_reconnectIntervalSb->setValue(2000);
|
||||
m_reconnectIntervalSb->setSuffix(tr(" ms"));
|
||||
m_reconnectIntervalSb->setToolTip(tr("Interval between reconnect attempts"));
|
||||
connect(m_reconnectIntervalSb, QOverload<int>::of(&QSpinBox::valueChanged),
|
||||
this, [this](int ms) {
|
||||
QMetaObject::invokeMethod(m_worker, [this, ms] {
|
||||
@@ -124,10 +162,20 @@ void MainWindow::setupToolBar()
|
||||
|
||||
tb->addSeparator();
|
||||
|
||||
// ── Format reference ──────────────────────────────────────────────────────
|
||||
auto *filterAction = tb->addAction(tr("Tag filter…"));
|
||||
filterAction->setToolTip(tr("Choose which tags are hidden from the Raw view"));
|
||||
connect(filterAction, &QAction::triggered, this, &MainWindow::configureTagFilter);
|
||||
|
||||
tb->addSeparator();
|
||||
|
||||
auto *helpAction = tb->addAction(tr("Format reference"));
|
||||
helpAction->setToolTip(tr("Show UARTScope output format guide (copy for AI)"));
|
||||
connect(helpAction, &QAction::triggered, this, &MainWindow::showFormatReference);
|
||||
|
||||
tb->addSeparator();
|
||||
|
||||
auto *aboutAction = tb->addAction(tr("Über UARTScope"));
|
||||
connect(aboutAction, &QAction::triggered, this, &MainWindow::showAbout);
|
||||
}
|
||||
|
||||
void MainWindow::setupStatusBar()
|
||||
@@ -136,7 +184,7 @@ void MainWindow::setupStatusBar()
|
||||
m_reconnectLabel = new QLabel(this);
|
||||
m_portLabel = new QLabel(this);
|
||||
|
||||
m_reconnectLabel->setStyleSheet("color: #e5a50a;"); // amber
|
||||
m_reconnectLabel->setStyleSheet("color: #e5a50a;");
|
||||
|
||||
statusBar()->addWidget(m_stateLabel);
|
||||
statusBar()->addWidget(m_reconnectLabel);
|
||||
@@ -152,9 +200,17 @@ void MainWindow::onConnectClicked()
|
||||
return;
|
||||
|
||||
m_lastConfig = dlg.config();
|
||||
if (m_lastConfig.portName.isEmpty()) {
|
||||
QMessageBox::warning(this, tr("No port"), tr("Please select a valid serial port."));
|
||||
return;
|
||||
|
||||
if (m_lastConfig.connectionType == SerialConfig::ConnectionType::Serial) {
|
||||
if (m_lastConfig.portName.isEmpty()) {
|
||||
QMessageBox::warning(this, tr("No port"), tr("Please select a valid serial port."));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (m_lastConfig.networkHost.isEmpty()) {
|
||||
QMessageBox::warning(this, tr("No host"), tr("Please enter a host/IP to connect to."));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_lastConfig.logFilePath.isEmpty())
|
||||
@@ -162,7 +218,6 @@ void MainWindow::onConnectClicked()
|
||||
Qt::QueuedConnection,
|
||||
Q_ARG(QString, m_lastConfig.logFilePath));
|
||||
|
||||
// Push current reconnect settings to worker before opening
|
||||
const bool autoRec = m_autoReconnectCb->isChecked();
|
||||
const int interval = m_reconnectIntervalSb->value();
|
||||
QMetaObject::invokeMethod(m_worker, [this, autoRec, interval] {
|
||||
@@ -170,14 +225,21 @@ void MainWindow::onConnectClicked()
|
||||
m_worker->setReconnectInterval(interval);
|
||||
}, Qt::QueuedConnection);
|
||||
|
||||
QMetaObject::invokeMethod(m_worker, "openPort",
|
||||
Qt::QueuedConnection,
|
||||
Q_ARG(QString, m_lastConfig.portName),
|
||||
Q_ARG(qint32, m_lastConfig.baudRate),
|
||||
Q_ARG(QSerialPort::DataBits, m_lastConfig.dataBits),
|
||||
Q_ARG(QSerialPort::Parity, m_lastConfig.parity),
|
||||
Q_ARG(QSerialPort::StopBits, m_lastConfig.stopBits),
|
||||
Q_ARG(QSerialPort::FlowControl, m_lastConfig.flowControl));
|
||||
if (m_lastConfig.connectionType == SerialConfig::ConnectionType::Serial) {
|
||||
QMetaObject::invokeMethod(m_worker, "openPort",
|
||||
Qt::QueuedConnection,
|
||||
Q_ARG(QString, m_lastConfig.portName),
|
||||
Q_ARG(qint32, m_lastConfig.baudRate),
|
||||
Q_ARG(QSerialPort::DataBits, m_lastConfig.dataBits),
|
||||
Q_ARG(QSerialPort::Parity, m_lastConfig.parity),
|
||||
Q_ARG(QSerialPort::StopBits, m_lastConfig.stopBits),
|
||||
Q_ARG(QSerialPort::FlowControl, m_lastConfig.flowControl));
|
||||
} else {
|
||||
QMetaObject::invokeMethod(m_worker, "openNetwork",
|
||||
Qt::QueuedConnection,
|
||||
Q_ARG(QString, m_lastConfig.networkHost),
|
||||
Q_ARG(quint16, m_lastConfig.networkPort));
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::onDisconnectClicked()
|
||||
@@ -192,10 +254,17 @@ void MainWindow::onPortOpened()
|
||||
m_stateLabel->setText(tr("● Connected"));
|
||||
m_stateLabel->setStyleSheet("color: #4ec94e;");
|
||||
m_reconnectLabel->clear();
|
||||
m_portLabel->setText(
|
||||
QStringLiteral("%1 @ %2 baud")
|
||||
.arg(m_lastConfig.portName)
|
||||
.arg(m_lastConfig.baudRate));
|
||||
if (m_lastConfig.connectionType == SerialConfig::ConnectionType::Network) {
|
||||
m_portLabel->setText(
|
||||
QStringLiteral("%1:%2 (TCP)")
|
||||
.arg(m_lastConfig.networkHost)
|
||||
.arg(m_lastConfig.networkPort));
|
||||
} else {
|
||||
m_portLabel->setText(
|
||||
QStringLiteral("%1 @ %2 baud")
|
||||
.arg(m_lastConfig.portName)
|
||||
.arg(m_lastConfig.baudRate));
|
||||
}
|
||||
statusBar()->clearMessage();
|
||||
}
|
||||
|
||||
@@ -216,13 +285,13 @@ void MainWindow::onReconnecting(int attempt)
|
||||
|
||||
void MainWindow::onClearScreen()
|
||||
{
|
||||
// ANSI clear-screen received from the firmware: clear ALL three views
|
||||
// (raw output, table, AND the tag monitor) plus the video preview frame.
|
||||
clearAllViews();
|
||||
}
|
||||
|
||||
void MainWindow::onError(const QString &message)
|
||||
{
|
||||
// Only show a dialog for errors that arrive when we are NOT in reconnect
|
||||
// mode – otherwise the amber status text is sufficient feedback.
|
||||
if (!m_autoReconnectCb->isChecked()) {
|
||||
QMessageBox::critical(this, tr("Serial error"), message);
|
||||
onPortClosed();
|
||||
@@ -231,7 +300,7 @@ void MainWindow::onError(const QString &message)
|
||||
|
||||
void MainWindow::onNewLine(const QString &line)
|
||||
{
|
||||
m_rawView->appendLine(line);
|
||||
m_rawView->appendLine(line, m_suppressedTags);
|
||||
m_tableView->appendLine(line);
|
||||
}
|
||||
|
||||
@@ -245,28 +314,32 @@ void MainWindow::clearAllViews()
|
||||
m_rawView->clear();
|
||||
m_tableView->clear();
|
||||
m_tagWidget->clearAll();
|
||||
if (m_videoWidget)
|
||||
m_videoWidget->clearFrame();
|
||||
}
|
||||
|
||||
// ── Format reference dialog ────────────────────────────────────────────────
|
||||
|
||||
void MainWindow::showFormatReference()
|
||||
{
|
||||
static const QString referenceText = R"(
|
||||
static const QString referenceText = R"UARTSCOPE(
|
||||
# UARTScope – Output Format Reference
|
||||
# Give this text to your AI assistant to generate compatible UART output.
|
||||
|
||||
UARTScope reads from a serial UART port and interprets the incoming text in
|
||||
three parallel ways. You can use any combination.
|
||||
UARTScope reads from either a serial UART port OR a plain TCP connection
|
||||
(see the "Netzwerk (TCP)" tab in the Connect dialog - handy for emulators
|
||||
like FS-UAE whose debug UART is piped through socat to a TCP port) and
|
||||
interprets the incoming text in three parallel ways. You can use any
|
||||
combination.
|
||||
|
||||
────────────────────────────────────────────────────────────
|
||||
1. RAW OUTPUT (always active)
|
||||
────────────────────────────────────────────────────────────
|
||||
Every line sent over UART is shown verbatim in the "Raw output" tab.
|
||||
No special formatting needed.
|
||||
Every line sent over UART is shown verbatim (with a timestamp) in the
|
||||
"Raw output" tab. No special formatting needed.
|
||||
|
||||
uart_printf("Boot complete. Version 1.0\n");
|
||||
|
||||
ANSI clear-screen → clears ALL views simultaneously:
|
||||
ANSI clear-screen → clears ALL views simultaneously (raw output, table,
|
||||
tag monitor, and the video preview frame):
|
||||
|
||||
uart_printf("\033[2J\033[H"); // standard VT100 clear-screen + cursor home
|
||||
|
||||
@@ -275,17 +348,25 @@ ANSI clear-screen → clears ALL views simultaneously:
|
||||
────────────────────────────────────────────────────────────
|
||||
Any line that contains [TAGNAME] is intercepted and displayed in a
|
||||
dedicated panel in the Tag Monitor. The line is still shown in Raw output
|
||||
(highlighted in cyan) so nothing is hidden.
|
||||
(highlighted in cyan) unless the tag is added to the Tag Filter.
|
||||
|
||||
TAG FORMAT:
|
||||
[TAGNAME] key1=value1 key2=value2 ...
|
||||
|
||||
Rules:
|
||||
• Tag name: uppercase letters, digits, underscore. Examples: WDG, VIDEO, I2C_BUS
|
||||
• Tag must start the meaningful content (leading whitespace is fine)
|
||||
• Key=value pairs are space-separated; values must not contain spaces
|
||||
• If no key=value pairs are present the raw string is shown as-is
|
||||
|
||||
LIST VALUES: separate multiple items in one value with ';' – they are
|
||||
shown as a multi-line list under the same key in the Tag Monitor:
|
||||
|
||||
uart_printf("[KICKSTART] Devs=trackdisk.device;input.device\n");
|
||||
|
||||
→ Tag Monitor shows:
|
||||
Devs trackdisk.device
|
||||
input.device
|
||||
|
||||
Examples:
|
||||
uart_printf("[WDG] uptime=%lu free_heap=%lu temp=%d\n",
|
||||
uptime_ms, heap_free, cpu_temp);
|
||||
@@ -293,11 +374,7 @@ Examples:
|
||||
uart_printf("[VIDEO] line=%d hblank=%d vblank=%d dma_buf=%d\n",
|
||||
scanline, hblank_cycles, vblank_cycles, dma_remaining);
|
||||
|
||||
uart_printf("[AUDIO] buf=%d underruns=%lu vol=%d\n",
|
||||
audio_buf_level, underrun_count, volume);
|
||||
|
||||
uart_printf("[I2C] addr=0x%02X ack=%d err=%d\n",
|
||||
i2c_addr, ack_received, error_code);
|
||||
uart_printf("[KICKSTART] Libs=graphics.library;intuition.library;dos.library\n");
|
||||
|
||||
Each unique tag gets its own panel. Panels update in-place so repeated
|
||||
messages don't scroll past – perfect for periodic watchdog output.
|
||||
@@ -329,30 +406,25 @@ No special firmware changes needed.
|
||||
5. COMPLETE EXAMPLE (Chica / Amiga hardware emulation)
|
||||
────────────────────────────────────────────────────────────
|
||||
void uart_status_update(void) {
|
||||
// Watchdog heartbeat → Tag Monitor [WDG]
|
||||
uart_printf("[WDG] uptime=%lu free=%lu load=%d temp=%d\n",
|
||||
HAL_GetTick(), xPortGetFreeHeapSize(),
|
||||
cpu_load_percent, core_temp_c);
|
||||
|
||||
// Video timing → Tag Monitor [VIDEO]
|
||||
uart_printf("[VIDEO] line=%d hblank=%d vblank=%d copper=%d\n",
|
||||
current_scanline, hblank_ticks, vblank_ticks, copper_dma);
|
||||
|
||||
// Audio state → Tag Monitor [AUDIO]
|
||||
uart_printf("[AUDIO] ch=%d buf=%d underruns=%lu\n",
|
||||
active_channels, buffer_fill, total_underruns);
|
||||
uart_printf("[KICKSTART] Devs=trackdisk.device;input.device;console.device\n");
|
||||
uart_printf("[KICKSTART] Libs=graphics.library;intuition.library\n");
|
||||
|
||||
// Structured CSV data → Table view
|
||||
uart_printf("%lu,%.1f,%d,%d\n",
|
||||
HAL_GetTick(), vcc_mv / 1000.0f, cpu_load_percent, core_temp_c);
|
||||
}
|
||||
|
||||
// Call from your main loop or a timer ISR, e.g. every 500 ms
|
||||
// Clear screen from firmware when you want a fresh start:
|
||||
// uart_printf("\033[2J\033[H");
|
||||
)";
|
||||
)UARTSCOPE";
|
||||
|
||||
// ── Dialog ────────────────────────────────────────────────────────────────
|
||||
auto *dlg = new QDialog(this);
|
||||
dlg->setWindowTitle(tr("UARTScope – Format Reference"));
|
||||
dlg->resize(720, 620);
|
||||
@@ -392,3 +464,187 @@ void uart_status_update(void) {
|
||||
dlg->exec();
|
||||
dlg->deleteLater();
|
||||
}
|
||||
|
||||
// ── Tag filter dialog ──────────────────────────────────────────────────────
|
||||
|
||||
void MainWindow::configureTagFilter()
|
||||
{
|
||||
auto *dlg = new QDialog(this);
|
||||
dlg->setWindowTitle(tr("Tag filter – Raw view"));
|
||||
dlg->setMinimumWidth(340);
|
||||
|
||||
auto *layout = new QVBoxLayout(dlg);
|
||||
|
||||
auto *infoLabel = new QLabel(
|
||||
tr("Tags listed here are <b>hidden from the Raw view</b> and only "
|
||||
"appear in the Tag Monitor panel.<br>"
|
||||
"Enter one tag name per line, without brackets (e.g. <tt>WDG</tt>)."), dlg);
|
||||
infoLabel->setWordWrap(true);
|
||||
layout->addWidget(infoLabel);
|
||||
|
||||
auto *edit = new QPlainTextEdit(dlg);
|
||||
QFont mono("Monospace");
|
||||
mono.setStyleHint(QFont::Monospace);
|
||||
edit->setFont(mono);
|
||||
QStringList current(m_suppressedTags.values());
|
||||
current.sort();
|
||||
edit->setPlainText(current.join('\n'));
|
||||
layout->addWidget(edit, 1);
|
||||
|
||||
auto *btnBox = new QDialogButtonBox(
|
||||
QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);
|
||||
connect(btnBox, &QDialogButtonBox::accepted, dlg, &QDialog::accept);
|
||||
connect(btnBox, &QDialogButtonBox::rejected, dlg, &QDialog::reject);
|
||||
layout->addWidget(btnBox);
|
||||
|
||||
if (dlg->exec() == QDialog::Accepted) {
|
||||
m_suppressedTags.clear();
|
||||
const QStringList lines = edit->toPlainText().split('\n', Qt::SkipEmptyParts);
|
||||
for (const QString &line : lines) {
|
||||
const QString tag = line.trimmed().toUpper();
|
||||
if (!tag.isEmpty())
|
||||
m_suppressedTags.insert(tag);
|
||||
}
|
||||
// Persist immediately so the filter survives even an unexpected exit.
|
||||
saveSettings();
|
||||
}
|
||||
dlg->deleteLater();
|
||||
}
|
||||
|
||||
// ── About dialog ──────────────────────────────────────────────────────────
|
||||
|
||||
void MainWindow::showAbout()
|
||||
{
|
||||
auto *dlg = new QDialog(this);
|
||||
dlg->setWindowTitle(tr("Über UARTScope"));
|
||||
dlg->setFixedSize(400, 280);
|
||||
|
||||
auto *root = new QVBoxLayout(dlg);
|
||||
root->setContentsMargins(0, 0, 0, 0);
|
||||
root->setSpacing(0);
|
||||
|
||||
auto *header = new QWidget(dlg);
|
||||
header->setFixedHeight(110);
|
||||
header->setStyleSheet("background-color: #1e1e1e;");
|
||||
auto *headerLayout = new QHBoxLayout(header);
|
||||
headerLayout->setContentsMargins(20, 14, 24, 14);
|
||||
headerLayout->setSpacing(16);
|
||||
|
||||
auto *logoLabel = new QLabel(header);
|
||||
const QPixmap logoPix(":/icons/UartscopeLogo.png");
|
||||
logoLabel->setPixmap(logoPix.scaled(72, 72, Qt::KeepAspectRatio, Qt::SmoothTransformation));
|
||||
logoLabel->setStyleSheet("background: transparent;");
|
||||
logoLabel->setFixedSize(72, 72);
|
||||
|
||||
auto *titleBlock = new QVBoxLayout();
|
||||
titleBlock->setSpacing(4);
|
||||
auto *titleLabel = new QLabel("UARTScope", header);
|
||||
titleLabel->setStyleSheet(
|
||||
"color: #ffffff; font-size: 26px; font-weight: bold; background: transparent;");
|
||||
auto *subtitleLabel = new QLabel(tr("UART-Monitor & HDMI-Viewer für Baremetal-Entwicklung"), header);
|
||||
subtitleLabel->setStyleSheet(
|
||||
"color: #56b6c2; font-size: 11px; background: transparent;");
|
||||
titleBlock->addWidget(titleLabel);
|
||||
titleBlock->addWidget(subtitleLabel);
|
||||
|
||||
headerLayout->addWidget(logoLabel);
|
||||
headerLayout->addLayout(titleBlock);
|
||||
root->addWidget(header);
|
||||
|
||||
auto *body = new QWidget(dlg);
|
||||
body->setStyleSheet("background-color: #252526;");
|
||||
auto *grid = new QGridLayout(body);
|
||||
grid->setContentsMargins(24, 20, 24, 20);
|
||||
grid->setVerticalSpacing(10);
|
||||
grid->setHorizontalSpacing(16);
|
||||
grid->setColumnMinimumWidth(0, 90);
|
||||
|
||||
const QString labelStyle = "color: #888888; font-weight: bold; background: transparent;";
|
||||
const QString valueStyle = "color: #d4d4d4; background: transparent;";
|
||||
|
||||
auto addRow = [&](int row, const QString &label, const QString &value) {
|
||||
auto *l = new QLabel(label, body);
|
||||
auto *v = new QLabel(value, body);
|
||||
l->setStyleSheet(labelStyle);
|
||||
v->setStyleSheet(valueStyle);
|
||||
l->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
|
||||
grid->addWidget(l, row, 0);
|
||||
grid->addWidget(v, row, 1);
|
||||
};
|
||||
|
||||
addRow(0, tr("Version"), "1.1.0");
|
||||
addRow(1, tr("Entwickler"), "Dany Thinnes");
|
||||
addRow(2, tr("Projekt"), "Projekt Hirnfrei");
|
||||
addRow(3, tr("Framework"), QString("Qt %1").arg(QT_VERSION_STR));
|
||||
addRow(4, tr("Sprache"), "C++17");
|
||||
|
||||
root->addWidget(body, 1);
|
||||
|
||||
auto *footer = new QWidget(dlg);
|
||||
footer->setStyleSheet("background-color: #252526; border-top: 1px solid #3c3c3c;");
|
||||
auto *footerLayout = new QHBoxLayout(footer);
|
||||
footerLayout->setContentsMargins(16, 10, 16, 10);
|
||||
|
||||
auto *closeBtn = new QPushButton(tr("Schließen"), footer);
|
||||
closeBtn->setDefault(true);
|
||||
closeBtn->setMinimumWidth(90);
|
||||
connect(closeBtn, &QPushButton::clicked, dlg, &QDialog::accept);
|
||||
|
||||
footerLayout->addStretch();
|
||||
footerLayout->addWidget(closeBtn);
|
||||
root->addWidget(footer);
|
||||
|
||||
dlg->exec();
|
||||
dlg->deleteLater();
|
||||
}
|
||||
|
||||
// ── Settings: save / restore ───────────────────────────────────────────────
|
||||
|
||||
void MainWindow::saveSettings()
|
||||
{
|
||||
QSettings s("ChicaDev", "UARTScope");
|
||||
|
||||
s.setValue("window/geometry", saveGeometry());
|
||||
s.setValue("window/state", saveState());
|
||||
|
||||
if (m_mainSplitter)
|
||||
s.setValue("splitter/main", m_mainSplitter->saveState());
|
||||
if (m_rightSplitter)
|
||||
s.setValue("splitter/right", m_rightSplitter->saveState());
|
||||
|
||||
s.setValue("reconnect/enabled", m_autoReconnectCb->isChecked());
|
||||
s.setValue("reconnect/interval", m_reconnectIntervalSb->value());
|
||||
|
||||
QStringList tags(m_suppressedTags.values());
|
||||
tags.sort();
|
||||
s.setValue("tagfilter/suppressed", tags);
|
||||
|
||||
s.sync(); // flush to disk immediately (important since we also call
|
||||
// this mid-session from configureTagFilter())
|
||||
}
|
||||
|
||||
void MainWindow::restoreSettings()
|
||||
{
|
||||
QSettings s("ChicaDev", "UARTScope");
|
||||
|
||||
if (s.contains("window/geometry"))
|
||||
restoreGeometry(s.value("window/geometry").toByteArray());
|
||||
if (s.contains("window/state"))
|
||||
restoreState(s.value("window/state").toByteArray());
|
||||
|
||||
if (m_mainSplitter && s.contains("splitter/main"))
|
||||
m_mainSplitter->restoreState(s.value("splitter/main").toByteArray());
|
||||
if (m_rightSplitter && s.contains("splitter/right"))
|
||||
m_rightSplitter->restoreState(s.value("splitter/right").toByteArray());
|
||||
|
||||
if (s.contains("reconnect/enabled"))
|
||||
m_autoReconnectCb->setChecked(s.value("reconnect/enabled").toBool());
|
||||
if (s.contains("reconnect/interval"))
|
||||
m_reconnectIntervalSb->setValue(s.value("reconnect/interval").toInt());
|
||||
|
||||
const QStringList tags = s.value("tagfilter/suppressed").toStringList();
|
||||
m_suppressedTags.clear();
|
||||
for (const QString &t : tags)
|
||||
if (!t.isEmpty())
|
||||
m_suppressedTags.insert(t);
|
||||
}
|
||||
|
||||
168
src/rawview.cpp
168
src/rawview.cpp
@@ -5,6 +5,19 @@
|
||||
#include <QFont>
|
||||
#include <QPalette>
|
||||
#include <QApplication>
|
||||
#include <QClipboard>
|
||||
#include <QDateTime>
|
||||
#include <QShortcut>
|
||||
#include <QKeySequence>
|
||||
|
||||
// Tag names may contain letters, digits, underscore AND hyphen (e.g.
|
||||
// [I2C-BUS]) - keep this in sync with the tagRe in serialworker.cpp, which
|
||||
// is what actually decides whether a tag is detected/emitted in the first
|
||||
// place. If the two regexes disagree, hyphenated tags can end up detected
|
||||
// by one but not recognised as "having a tag" by the other (breaking either
|
||||
// cyan highlighting or the tag filter).
|
||||
const QRegularExpression RawView::s_tagRe(
|
||||
R"(\[([A-Z][A-Z0-9_-]*)\])", QRegularExpression::CaseInsensitiveOption);
|
||||
|
||||
RawView::RawView(QWidget *parent)
|
||||
: QWidget(parent)
|
||||
@@ -15,49 +28,67 @@ RawView::RawView(QWidget *parent)
|
||||
|
||||
void RawView::setupUi()
|
||||
{
|
||||
auto *mainLayout = new QVBoxLayout(this);
|
||||
auto *mainLayout = new QVBoxLayout(this);
|
||||
mainLayout->setContentsMargins(4, 4, 4, 4);
|
||||
mainLayout->setSpacing(4);
|
||||
|
||||
// ── Toolbar ──────────────────────────────────────────────────────────────
|
||||
auto *toolbar = new QHBoxLayout();
|
||||
|
||||
m_searchEdit = new QLineEdit(this);
|
||||
m_searchEdit->setPlaceholderText(tr("Search… (Enter)"));
|
||||
m_searchEdit->setPlaceholderText(tr("Search…"));
|
||||
m_searchEdit->setClearButtonEnabled(true);
|
||||
connect(m_searchEdit, &QLineEdit::textChanged, this, &RawView::onSearch);
|
||||
connect(m_searchEdit, &QLineEdit::returnPressed, this, &RawView::findNext);
|
||||
|
||||
m_findPrevBtn = new QPushButton(tr("▲"), this);
|
||||
m_findPrevBtn->setMaximumWidth(28);
|
||||
m_findPrevBtn->setToolTip(tr("Previous match (Shift+F3)"));
|
||||
connect(m_findPrevBtn, &QPushButton::clicked, this, &RawView::findPrevious);
|
||||
|
||||
m_findNextBtn = new QPushButton(tr("▼"), this);
|
||||
m_findNextBtn->setMaximumWidth(28);
|
||||
m_findNextBtn->setToolTip(tr("Next match (F3 / Enter)"));
|
||||
connect(m_findNextBtn, &QPushButton::clicked, this, &RawView::findNext);
|
||||
|
||||
auto *nextShortcut = new QShortcut(QKeySequence(Qt::Key_F3), this);
|
||||
connect(nextShortcut, &QShortcut::activated, this, &RawView::findNext);
|
||||
auto *prevShortcut = new QShortcut(QKeySequence(Qt::SHIFT | Qt::Key_F3), this);
|
||||
connect(prevShortcut, &QShortcut::activated, this, &RawView::findPrevious);
|
||||
|
||||
m_autoScrollCb = new QCheckBox(tr("Auto-scroll"), this);
|
||||
m_autoScrollCb->setChecked(true);
|
||||
m_autoScrollCb->setChecked(true); // default ON
|
||||
connect(m_autoScrollCb, &QCheckBox::toggled, this, &RawView::onAutoScrollToggled);
|
||||
|
||||
m_clearBtn = new QPushButton(tr("Clear"), this);
|
||||
connect(m_clearBtn, &QPushButton::clicked, this, &RawView::clear);
|
||||
|
||||
m_lineCountLbl = new QLabel(tr("Lines: 0"), this);
|
||||
m_lineCountLbl->setMinimumWidth(90);
|
||||
|
||||
m_copyBtn = new QPushButton(tr("📋 Copy"), this);
|
||||
m_copyBtn->setToolTip(tr("Copy all raw output to clipboard"));
|
||||
connect(m_copyBtn, &QPushButton::clicked, this, &RawView::copyToClipboard);
|
||||
|
||||
m_clearBtn = new QPushButton(tr("Clear"), this);
|
||||
connect(m_clearBtn, &QPushButton::clicked, this, &RawView::clear);
|
||||
|
||||
toolbar->addWidget(new QLabel(tr("Search:"), this));
|
||||
toolbar->addWidget(m_searchEdit, 1);
|
||||
toolbar->addWidget(m_findPrevBtn);
|
||||
toolbar->addWidget(m_findNextBtn);
|
||||
toolbar->addWidget(m_autoScrollCb);
|
||||
toolbar->addWidget(m_lineCountLbl);
|
||||
toolbar->addWidget(m_copyBtn);
|
||||
toolbar->addWidget(m_clearBtn);
|
||||
mainLayout->addLayout(toolbar);
|
||||
|
||||
// ── Text area ────────────────────────────────────────────────────────────
|
||||
m_textEdit = new QPlainTextEdit(this);
|
||||
m_textEdit->setReadOnly(true);
|
||||
m_textEdit->setLineWrapMode(QPlainTextEdit::NoWrap); // horizontal scroll
|
||||
// Practically unlimited history (Qt uses a block count limit internally)
|
||||
m_textEdit->setMaximumBlockCount(0); // 0 = unlimited
|
||||
m_textEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
|
||||
m_textEdit->setMaximumBlockCount(0);
|
||||
|
||||
// Monospaced font for alignment
|
||||
QFont monoFont("Monospace");
|
||||
monoFont.setStyleHint(QFont::Monospace);
|
||||
monoFont.setPointSize(10);
|
||||
m_textEdit->setFont(monoFont);
|
||||
|
||||
// Don't let the text edit swallow horizontal scroll events from the viewport
|
||||
m_textEdit->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
|
||||
m_textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
|
||||
|
||||
@@ -69,31 +100,36 @@ void RawView::setupUi()
|
||||
|
||||
void RawView::applyColorScheme()
|
||||
{
|
||||
// Dark terminal style
|
||||
QPalette p = m_textEdit->palette();
|
||||
p.setColor(QPalette::Base, QColor(0x1e, 0x1e, 0x1e));
|
||||
p.setColor(QPalette::Text, QColor(0xd4, 0xd4, 0xd4));
|
||||
p.setColor(QPalette::Base, QColor(0x1e, 0x1e, 0x1e));
|
||||
p.setColor(QPalette::Text, QColor(0xd4, 0xd4, 0xd4));
|
||||
m_textEdit->setPalette(p);
|
||||
}
|
||||
|
||||
void RawView::appendLine(const QString &line)
|
||||
void RawView::appendLine(const QString &line, const QSet<QString> &suppressedTags)
|
||||
{
|
||||
if (!suppressedTags.isEmpty()) {
|
||||
const auto match = s_tagRe.match(line);
|
||||
if (match.hasMatch() && suppressedTags.contains(match.captured(1).toUpper()))
|
||||
return;
|
||||
}
|
||||
|
||||
++m_lineCount;
|
||||
m_lineCountLbl->setText(tr("Lines: %1").arg(m_lineCount));
|
||||
|
||||
// Highlight lines that contain a tag like [WDG]
|
||||
static const QRegularExpression tagRe(R"(\[[A-Z][A-Z0-9_]*\])",
|
||||
QRegularExpression::CaseInsensitiveOption);
|
||||
if (tagRe.match(line).hasMatch()) {
|
||||
// Append as HTML so we can colour it differently
|
||||
QTextCursor cursor(m_textEdit->document());
|
||||
cursor.movePosition(QTextCursor::End);
|
||||
QTextCharFormat fmt;
|
||||
fmt.setForeground(QColor(0x56, 0xb6, 0xc2)); // cyan-ish
|
||||
cursor.insertText(line + '\n', fmt);
|
||||
} else {
|
||||
m_textEdit->appendPlainText(line);
|
||||
}
|
||||
const QString ts = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
|
||||
const bool hasTag = s_tagRe.match(line).hasMatch();
|
||||
|
||||
QTextCursor cursor(m_textEdit->document());
|
||||
cursor.movePosition(QTextCursor::End);
|
||||
|
||||
QTextCharFormat tsFmt;
|
||||
tsFmt.setForeground(QColor(0x60, 0x60, 0x60));
|
||||
cursor.insertText(QStringLiteral("[%1] ").arg(ts), tsFmt);
|
||||
|
||||
QTextCharFormat fmt;
|
||||
fmt.setForeground(hasTag ? QColor(0x56, 0xb6, 0xc2) : QColor(0xd4, 0xd4, 0xd4));
|
||||
cursor.insertText(line + '\n', fmt);
|
||||
|
||||
if (m_autoScroll)
|
||||
m_textEdit->verticalScrollBar()->setValue(
|
||||
@@ -107,26 +143,74 @@ void RawView::clear()
|
||||
m_lineCountLbl->setText(tr("Lines: 0"));
|
||||
}
|
||||
|
||||
void RawView::copyToClipboard()
|
||||
{
|
||||
QApplication::clipboard()->setText(m_textEdit->toPlainText());
|
||||
}
|
||||
|
||||
bool RawView::searchAndSelect(const QString &text, QTextDocument::FindFlags flags, bool wrapAllowed)
|
||||
{
|
||||
if (text.isEmpty())
|
||||
return false;
|
||||
|
||||
QTextDocument *doc = m_textEdit->document();
|
||||
QTextCursor cursor = doc->find(text, m_textEdit->textCursor(), flags);
|
||||
|
||||
if (cursor.isNull() && wrapAllowed) {
|
||||
// No further match in the search direction from here - wrap around
|
||||
// to the start (or end, for backward search) and try once more so
|
||||
// the user can keep pressing "next"/"previous" in a loop.
|
||||
QTextCursor wrapCursor(doc);
|
||||
if (flags.testFlag(QTextDocument::FindBackward))
|
||||
wrapCursor.movePosition(QTextCursor::End);
|
||||
cursor = doc->find(text, wrapCursor, flags);
|
||||
}
|
||||
|
||||
if (cursor.isNull())
|
||||
return false;
|
||||
|
||||
m_textEdit->setTextCursor(cursor);
|
||||
return true;
|
||||
}
|
||||
|
||||
void RawView::onSearch(const QString &text)
|
||||
{
|
||||
// Simple incremental search – highlight first match
|
||||
QTextDocument *doc = m_textEdit->document();
|
||||
QTextCursor cursor = doc->find(text);
|
||||
if (!cursor.isNull()) {
|
||||
m_textEdit->setTextCursor(cursor);
|
||||
m_searchEdit->setStyleSheet(QString());
|
||||
} else if (!text.isEmpty()) {
|
||||
m_searchEdit->setStyleSheet("background: #5c2222;");
|
||||
} else {
|
||||
if (text.isEmpty()) {
|
||||
m_searchEdit->setStyleSheet(QString());
|
||||
return;
|
||||
}
|
||||
|
||||
// Whenever the search text itself changes, restart from the top of the
|
||||
// document so editing the query doesn't leave the view stranded at
|
||||
// wherever the cursor happened to be from a previous search.
|
||||
QTextCursor cursor(m_textEdit->document());
|
||||
m_textEdit->setTextCursor(cursor);
|
||||
|
||||
const bool found = searchAndSelect(text, {}, true);
|
||||
m_searchEdit->setStyleSheet(found ? QString() : "background: #5c2222;");
|
||||
}
|
||||
|
||||
void RawView::findNext()
|
||||
{
|
||||
const QString text = m_searchEdit->text();
|
||||
if (text.isEmpty())
|
||||
return;
|
||||
const bool found = searchAndSelect(text, {}, true);
|
||||
m_searchEdit->setStyleSheet(found ? QString() : "background: #5c2222;");
|
||||
}
|
||||
|
||||
void RawView::findPrevious()
|
||||
{
|
||||
const QString text = m_searchEdit->text();
|
||||
if (text.isEmpty())
|
||||
return;
|
||||
const bool found = searchAndSelect(text, QTextDocument::FindBackward, true);
|
||||
m_searchEdit->setStyleSheet(found ? QString() : "background: #5c2222;");
|
||||
}
|
||||
|
||||
void RawView::onScrollValueChanged(int value)
|
||||
{
|
||||
const int max = m_textEdit->verticalScrollBar()->maximum();
|
||||
// If user scrolled away from bottom, disable auto-scroll
|
||||
if (value < max - 5) {
|
||||
if (value < m_textEdit->verticalScrollBar()->maximum() - 5) {
|
||||
m_autoScroll = false;
|
||||
m_autoScrollCb->setChecked(false);
|
||||
}
|
||||
|
||||
@@ -5,13 +5,23 @@
|
||||
SerialWorker::SerialWorker(QObject *parent)
|
||||
: QObject(parent)
|
||||
, m_port(new QSerialPort(this))
|
||||
, m_socket(new QTcpSocket(this))
|
||||
, m_idleFlushTimer(new QTimer(this))
|
||||
, m_reconnectTimer(new QTimer(this))
|
||||
{
|
||||
m_idleFlushTimer->setSingleShot(true);
|
||||
connect(m_idleFlushTimer, &QTimer::timeout, this, &SerialWorker::flushScanTail);
|
||||
|
||||
m_reconnectTimer->setSingleShot(true);
|
||||
connect(m_reconnectTimer, &QTimer::timeout, this, &SerialWorker::tryReconnect);
|
||||
|
||||
connect(m_port, &QSerialPort::readyRead, this, &SerialWorker::onReadyRead);
|
||||
connect(m_port, &QSerialPort::errorOccurred, this, &SerialWorker::onPortError);
|
||||
connect(m_port, &QSerialPort::readyRead, this, &SerialWorker::onReadyRead);
|
||||
connect(m_port, &QSerialPort::errorOccurred, this, &SerialWorker::onPortError);
|
||||
|
||||
connect(m_socket, &QTcpSocket::readyRead, this, &SerialWorker::onReadyRead);
|
||||
connect(m_socket, &QTcpSocket::connected, this, &SerialWorker::onSocketConnected);
|
||||
connect(m_socket, &QTcpSocket::disconnected, this, &SerialWorker::onSocketDisconnected);
|
||||
connect(m_socket, &QTcpSocket::errorOccurred, this, &SerialWorker::onSocketError);
|
||||
}
|
||||
|
||||
SerialWorker::~SerialWorker()
|
||||
@@ -20,7 +30,7 @@ SerialWorker::~SerialWorker()
|
||||
closePort();
|
||||
}
|
||||
|
||||
// ── Public slots ────────────────────────────────────────────────────────────
|
||||
// ── public slots ──────────────────────────────────────────────────────────────
|
||||
|
||||
void SerialWorker::openPort(const QString &portName, qint32 baudRate,
|
||||
QSerialPort::DataBits dataBits,
|
||||
@@ -28,7 +38,7 @@ void SerialWorker::openPort(const QString &portName, qint32 baudRate,
|
||||
QSerialPort::StopBits stopBits,
|
||||
QSerialPort::FlowControl flowControl)
|
||||
{
|
||||
// Save config for auto-reconnect
|
||||
m_mode = ConnectionMode::Serial;
|
||||
m_portName = portName;
|
||||
m_baudRate = baudRate;
|
||||
m_dataBits = dataBits;
|
||||
@@ -38,6 +48,10 @@ void SerialWorker::openPort(const QString &portName, qint32 baudRate,
|
||||
m_userDisconnected = false;
|
||||
m_reconnectAttempt = 0;
|
||||
|
||||
// Make sure any previous connection (of either transport) is torn down
|
||||
// before switching to serial mode.
|
||||
if (m_socket->state() != QAbstractSocket::UnconnectedState)
|
||||
m_socket->abort();
|
||||
if (m_port->isOpen())
|
||||
m_port->close();
|
||||
|
||||
@@ -54,19 +68,62 @@ void SerialWorker::openPort(const QString &portName, qint32 baudRate,
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
m_device = m_port;
|
||||
m_idleFlushTimer->stop();
|
||||
m_buffer.clear();
|
||||
m_scanTail.clear();
|
||||
m_reconnectAttempt = 0;
|
||||
emit portOpened();
|
||||
}
|
||||
|
||||
void SerialWorker::openNetwork(const QString &host, quint16 port)
|
||||
{
|
||||
m_mode = ConnectionMode::Network;
|
||||
m_networkHost = host;
|
||||
m_networkPort = port;
|
||||
m_userDisconnected = false;
|
||||
m_reconnectAttempt = 0;
|
||||
|
||||
// Make sure any previous connection (of either transport) is torn down
|
||||
// before switching to network mode.
|
||||
if (m_port->isOpen())
|
||||
m_port->close();
|
||||
if (m_socket->state() != QAbstractSocket::UnconnectedState)
|
||||
m_socket->abort();
|
||||
|
||||
m_idleFlushTimer->stop();
|
||||
m_buffer.clear();
|
||||
m_scanTail.clear();
|
||||
|
||||
// connectToHost() is asynchronous - the outcome (success or failure)
|
||||
// arrives later via the connected()/errorOccurred() signals, handled
|
||||
// in onSocketConnected()/onSocketError() below.
|
||||
m_socket->connectToHost(host, port);
|
||||
}
|
||||
|
||||
void SerialWorker::closePort()
|
||||
{
|
||||
m_userDisconnected = true;
|
||||
m_reconnectTimer->stop();
|
||||
m_idleFlushTimer->stop();
|
||||
|
||||
bool wasOpen = false;
|
||||
if (m_port && m_port->isOpen()) {
|
||||
m_port->close();
|
||||
emit portClosed();
|
||||
wasOpen = true;
|
||||
}
|
||||
if (m_socket && m_socket->state() != QAbstractSocket::UnconnectedState) {
|
||||
// abort() tears the connection down immediately (no graceful
|
||||
// shutdown handshake needed for a debug/monitor connection like
|
||||
// this one) and reliably triggers disconnected() right away.
|
||||
m_socket->abort();
|
||||
wasOpen = true;
|
||||
}
|
||||
m_device = nullptr;
|
||||
|
||||
if (wasOpen)
|
||||
emit portClosed();
|
||||
|
||||
stopLogging();
|
||||
}
|
||||
|
||||
@@ -107,24 +164,27 @@ void SerialWorker::stopLogging()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private slots ───────────────────────────────────────────────────────────
|
||||
// ── private slots ───────────────────────────────────────────────────────────
|
||||
|
||||
void SerialWorker::onReadyRead()
|
||||
{
|
||||
processRawData(m_port->readAll());
|
||||
if (m_device)
|
||||
processRawData(m_device->readAll());
|
||||
}
|
||||
|
||||
void SerialWorker::onPortError(QSerialPort::SerialPortError err)
|
||||
{
|
||||
if (m_mode != ConnectionMode::Serial)
|
||||
return;
|
||||
if (err == QSerialPort::NoError)
|
||||
return;
|
||||
|
||||
// ResourceError = device physically disconnected (USB pull, power loss)
|
||||
const bool fatal = (err == QSerialPort::ResourceError ||
|
||||
err == QSerialPort::DeviceNotFoundError);
|
||||
|
||||
if (fatal) {
|
||||
m_port->close();
|
||||
m_device = nullptr;
|
||||
emit portClosed();
|
||||
if (m_autoReconnect && !m_userDisconnected) {
|
||||
scheduleReconnect();
|
||||
@@ -132,8 +192,52 @@ void SerialWorker::onPortError(QSerialPort::SerialPortError err)
|
||||
emit errorOccurred(m_port->errorString());
|
||||
}
|
||||
}
|
||||
// Non-fatal errors (framing, parity, etc.) are silently ignored to avoid
|
||||
// spamming the user during noisy serial sessions.
|
||||
}
|
||||
|
||||
void SerialWorker::onSocketConnected()
|
||||
{
|
||||
if (m_mode != ConnectionMode::Network)
|
||||
return;
|
||||
|
||||
m_device = m_socket;
|
||||
m_idleFlushTimer->stop();
|
||||
m_buffer.clear();
|
||||
m_scanTail.clear();
|
||||
m_reconnectAttempt = 0;
|
||||
emit portOpened();
|
||||
}
|
||||
|
||||
void SerialWorker::onSocketDisconnected()
|
||||
{
|
||||
if (m_mode != ConnectionMode::Network)
|
||||
return;
|
||||
|
||||
m_device = nullptr;
|
||||
|
||||
// If this disconnect was requested by us (closePort()), that function
|
||||
// has already emitted portClosed() and handles all cleanup - nothing
|
||||
// more to do here, and reconnecting would be wrong.
|
||||
if (m_userDisconnected)
|
||||
return;
|
||||
|
||||
emit portClosed();
|
||||
if (m_autoReconnect)
|
||||
scheduleReconnect();
|
||||
}
|
||||
|
||||
void SerialWorker::onSocketError(QAbstractSocket::SocketError)
|
||||
{
|
||||
if (m_mode != ConnectionMode::Network)
|
||||
return;
|
||||
|
||||
const QString msg = m_socket->errorString();
|
||||
m_device = nullptr;
|
||||
|
||||
if (m_autoReconnect && !m_userDisconnected) {
|
||||
scheduleReconnect();
|
||||
} else {
|
||||
emit errorOccurred(msg);
|
||||
}
|
||||
}
|
||||
|
||||
void SerialWorker::tryReconnect()
|
||||
@@ -144,23 +248,34 @@ void SerialWorker::tryReconnect()
|
||||
++m_reconnectAttempt;
|
||||
emit reconnecting(m_reconnectAttempt);
|
||||
|
||||
m_port->setPortName(m_portName);
|
||||
m_port->setBaudRate(m_baudRate);
|
||||
m_port->setDataBits(m_dataBits);
|
||||
m_port->setParity(m_parity);
|
||||
m_port->setStopBits(m_stopBits);
|
||||
m_port->setFlowControl(m_flowControl);
|
||||
if (m_mode == ConnectionMode::Serial) {
|
||||
m_port->setPortName(m_portName);
|
||||
m_port->setBaudRate(m_baudRate);
|
||||
m_port->setDataBits(m_dataBits);
|
||||
m_port->setParity(m_parity);
|
||||
m_port->setStopBits(m_stopBits);
|
||||
m_port->setFlowControl(m_flowControl);
|
||||
|
||||
if (m_port->open(QIODevice::ReadOnly)) {
|
||||
m_buffer.clear();
|
||||
m_reconnectAttempt = 0;
|
||||
emit portOpened();
|
||||
if (m_port->open(QIODevice::ReadOnly)) {
|
||||
m_device = m_port;
|
||||
m_idleFlushTimer->stop();
|
||||
m_buffer.clear();
|
||||
m_scanTail.clear();
|
||||
m_reconnectAttempt = 0;
|
||||
emit portOpened();
|
||||
} else {
|
||||
scheduleReconnect();
|
||||
}
|
||||
} else {
|
||||
scheduleReconnect();
|
||||
// Network: connectToHost() is asynchronous. Success/failure is
|
||||
// reported later via onSocketConnected()/onSocketError(), which
|
||||
// either finish this attempt or schedule the next one.
|
||||
m_socket->abort();
|
||||
m_socket->connectToHost(m_networkHost, m_networkPort);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private helpers ─────────────────────────────────────────────────────────
|
||||
// ── private helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
void SerialWorker::scheduleReconnect()
|
||||
{
|
||||
@@ -170,23 +285,75 @@ void SerialWorker::scheduleReconnect()
|
||||
|
||||
void SerialWorker::processRawData(const QByteArray &data)
|
||||
{
|
||||
// Scan raw bytes for ANSI clear-screen BEFORE UTF-8 conversion so we
|
||||
// never miss a sequence that straddles a read boundary.
|
||||
// We look for ESC[2J (optionally followed by ESC[H or ESC[1;1H)
|
||||
// ESC = 0x1B
|
||||
const QByteArray esc2j("\x1b[2J");
|
||||
if (data.contains(esc2j)) {
|
||||
emit clearScreen();
|
||||
// Strip all ANSI escape sequences from the data before further processing
|
||||
// so they don't clutter the raw view.
|
||||
// ── ANSI clear-screen detection ────────────────────────────────────────
|
||||
// We scan a buffer that includes a small tail from the PREVIOUS chunk so
|
||||
// that a sequence split across two readyRead() calls (e.g. "...\x1b" +
|
||||
// "[2J\x1b[H...") is still detected reliably. The clear sequence itself
|
||||
// is also stripped from what reaches processLine()/the line buffer.
|
||||
QByteArray combined = m_scanTail + data;
|
||||
bool sawClear = false;
|
||||
|
||||
// Look for ESC[2J (the actual screen-clear command). ESC[H / ESC[1;1H
|
||||
// (cursor-home) commonly follows but isn't required for us to clear.
|
||||
const QByteArray clearSeq("\x1b[2J");
|
||||
int clearPos = combined.indexOf(clearSeq);
|
||||
while (clearPos != -1) {
|
||||
sawClear = true;
|
||||
// Remove the matched sequence so it doesn't leak into the text stream
|
||||
combined.remove(clearPos, clearSeq.size());
|
||||
clearPos = combined.indexOf(clearSeq, clearPos);
|
||||
}
|
||||
|
||||
// Strip all ANSI escape sequences for display
|
||||
// Sequence: ESC [ <params> <letter>
|
||||
// Keep the last few bytes as the new tail (in case a sequence is cut off
|
||||
// at the very end of this chunk); only forward the rest.
|
||||
constexpr int kTailLen = 8; // longer than any escape sequence we match
|
||||
QByteArray toProcess;
|
||||
if (combined.size() > kTailLen) {
|
||||
toProcess = combined.left(combined.size() - kTailLen);
|
||||
m_scanTail = combined.right(kTailLen);
|
||||
} else {
|
||||
// Not enough data yet to safely flush – hold everything as tail.
|
||||
m_scanTail = combined;
|
||||
}
|
||||
|
||||
if (sawClear)
|
||||
emit clearScreen();
|
||||
|
||||
// (Re)arm the idle-flush timer whenever bytes are still being withheld
|
||||
// in m_scanTail, so that a burst which ends right at a chunk boundary
|
||||
// doesn't leave its last line(s) stuck there forever. If nothing is
|
||||
// being withheld, make sure any pending flush is cancelled.
|
||||
if (!m_scanTail.isEmpty())
|
||||
m_idleFlushTimer->start(kIdleFlushMs);
|
||||
else
|
||||
m_idleFlushTimer->stop();
|
||||
|
||||
if (toProcess.isEmpty())
|
||||
return;
|
||||
|
||||
appendToLineBuffer(toProcess);
|
||||
}
|
||||
|
||||
void SerialWorker::flushScanTail()
|
||||
{
|
||||
// Nothing new arrived within kIdleFlushMs of the last chunk that left
|
||||
// data in m_scanTail: treat it as final and process it as-is, rather
|
||||
// than waiting indefinitely for more bytes that may never come.
|
||||
if (m_scanTail.isEmpty())
|
||||
return;
|
||||
|
||||
QByteArray toProcess = m_scanTail;
|
||||
m_scanTail.clear();
|
||||
appendToLineBuffer(toProcess);
|
||||
}
|
||||
|
||||
void SerialWorker::appendToLineBuffer(const QByteArray &toProcess)
|
||||
{
|
||||
// Strip remaining (non-clear) ANSI escape sequences for clean display.
|
||||
static const QRegularExpression ansiRe(
|
||||
"\x1b(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])");
|
||||
|
||||
QString text = QString::fromUtf8(data);
|
||||
QString text = QString::fromUtf8(toProcess);
|
||||
text.remove(ansiRe);
|
||||
|
||||
m_buffer += text;
|
||||
@@ -212,8 +379,14 @@ void SerialWorker::processLine(const QString &line)
|
||||
m_logStream->flush();
|
||||
}
|
||||
|
||||
// Tag names may contain letters, digits, underscore AND hyphen (e.g.
|
||||
// [I2C-BUS]). Keep this in sync with RawView::s_tagRe, which is used
|
||||
// for cyan highlighting and re-checking suppressed tags client-side;
|
||||
// if the two regexes disagree, a hyphenated tag can be detected here
|
||||
// (and emitted/filterable) while RawView fails to recognise it as
|
||||
// tagged, or vice versa.
|
||||
static const QRegularExpression tagRe(
|
||||
R"(\[([A-Z][A-Z0-9_]*)\](.*))", QRegularExpression::CaseInsensitiveOption);
|
||||
R"(\[([A-Z][A-Z0-9_-]*)\](.*))", QRegularExpression::CaseInsensitiveOption);
|
||||
|
||||
const auto match = tagRe.match(line);
|
||||
if (match.hasMatch()) {
|
||||
|
||||
@@ -10,7 +10,6 @@ TableView::TableView(QWidget *parent)
|
||||
mainLayout->setContentsMargins(4, 4, 4, 4);
|
||||
mainLayout->setSpacing(4);
|
||||
|
||||
// ── Toolbar ──────────────────────────────────────────────────────────────
|
||||
auto *toolbar = new QHBoxLayout();
|
||||
|
||||
m_delimCombo = new QComboBox(this);
|
||||
@@ -44,7 +43,6 @@ TableView::TableView(QWidget *parent)
|
||||
toolbar->addWidget(m_clearBtn);
|
||||
mainLayout->addLayout(toolbar);
|
||||
|
||||
// ── Table ─────────────────────────────────────────────────────────────────
|
||||
m_table = new QTableWidget(this);
|
||||
m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
|
||||
@@ -66,7 +64,6 @@ void TableView::onDelimiterChanged(int index)
|
||||
void TableView::onMaxRowsChanged()
|
||||
{
|
||||
m_maxRows = m_maxRowsEdit->text().toInt();
|
||||
// Trim excess rows
|
||||
while (m_rows.size() > m_maxRows)
|
||||
m_rows.removeFirst();
|
||||
rebuildTable();
|
||||
@@ -87,14 +84,13 @@ void TableView::appendLine(const QString &line)
|
||||
if (line.isEmpty())
|
||||
return;
|
||||
|
||||
// Header row starts with '#'
|
||||
if (!m_headersSet && line.startsWith('#')) {
|
||||
parseHeaders(line.mid(1)); // strip leading '#'
|
||||
parseHeaders(line.mid(1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tryAppendRow(line))
|
||||
return; // didn't match expected column count
|
||||
return;
|
||||
|
||||
if (m_autoScroll)
|
||||
m_table->scrollToBottom();
|
||||
@@ -114,7 +110,6 @@ bool TableView::tryAppendRow(const QString &line)
|
||||
{
|
||||
const QStringList cells = line.split(m_delimiter);
|
||||
|
||||
// Auto-detect column count on the first data row if no header was given
|
||||
if (!m_headersSet) {
|
||||
m_headers.clear();
|
||||
for (int i = 0; i < cells.size(); ++i)
|
||||
@@ -125,9 +120,8 @@ bool TableView::tryAppendRow(const QString &line)
|
||||
}
|
||||
|
||||
if (cells.size() != m_headers.size())
|
||||
return false; // column mismatch – skip row
|
||||
return false;
|
||||
|
||||
// Enforce max rows
|
||||
m_rows.append(cells);
|
||||
if (m_rows.size() > m_maxRows)
|
||||
m_rows.removeFirst();
|
||||
@@ -140,7 +134,6 @@ bool TableView::tryAppendRow(const QString &line)
|
||||
m_table->setItem(row, col, item);
|
||||
}
|
||||
|
||||
// Remove oldest visual row if over limit
|
||||
if (m_table->rowCount() > m_maxRows)
|
||||
m_table->removeRow(0);
|
||||
|
||||
|
||||
196
src/tagpanel.cpp
196
src/tagpanel.cpp
@@ -1,48 +1,91 @@
|
||||
#include "tagpanel.h"
|
||||
#include <QHeaderView>
|
||||
#include <QRegularExpression>
|
||||
#include <QApplication>
|
||||
#include <QClipboard>
|
||||
#include <QDateTime>
|
||||
#include <QScrollBar>
|
||||
#include <QFont>
|
||||
#include <QTextCursor>
|
||||
|
||||
TagPanel::TagPanel(const QString &tag, QWidget *parent)
|
||||
: QGroupBox(QStringLiteral("[%1]").arg(tag), parent)
|
||||
, m_tag(tag)
|
||||
{
|
||||
auto *layout = new QVBoxLayout(this);
|
||||
layout->setContentsMargins(6, 12, 6, 6);
|
||||
layout->setContentsMargins(6, 14, 6, 6);
|
||||
layout->setSpacing(4);
|
||||
|
||||
// Timestamp line
|
||||
m_timestampLabel = new QLabel(tr("No data yet"), this);
|
||||
m_timestampLabel->setStyleSheet("color: gray; font-size: 10px;");
|
||||
layout->addWidget(m_timestampLabel);
|
||||
m_tabs = new QTabWidget(this);
|
||||
|
||||
// Table for key=value pairs
|
||||
m_table = new QTableWidget(0, 2, this);
|
||||
// ── "Aktuell" tab: latest value(s), updates in-place ───────────────
|
||||
auto *currentTab = new QWidget(m_tabs);
|
||||
auto *currentLayout = new QVBoxLayout(currentTab);
|
||||
currentLayout->setContentsMargins(0, 4, 0, 0);
|
||||
currentLayout->setSpacing(4);
|
||||
|
||||
m_table = new QTableWidget(0, 2, currentTab);
|
||||
m_table->setHorizontalHeaderLabels({tr("Key"), tr("Value")});
|
||||
m_table->horizontalHeader()->setStretchLastSection(true);
|
||||
m_table->verticalHeader()->hide();
|
||||
m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
|
||||
m_table->setAlternatingRowColors(true);
|
||||
m_table->setMaximumHeight(200);
|
||||
m_table->setMaximumHeight(220);
|
||||
m_table->verticalHeader()->setDefaultSectionSize(22);
|
||||
layout->addWidget(m_table);
|
||||
currentLayout->addWidget(m_table);
|
||||
|
||||
// Fallback label for non-kv data
|
||||
m_rawLabel = new QLabel(this);
|
||||
m_rawLabel = new QLabel(currentTab);
|
||||
m_rawLabel->setWordWrap(true);
|
||||
m_rawLabel->setStyleSheet("font-family: monospace;");
|
||||
m_rawLabel->hide();
|
||||
layout->addWidget(m_rawLabel);
|
||||
currentLayout->addWidget(m_rawLabel);
|
||||
|
||||
m_tabs->addTab(currentTab, tr("Aktuell"));
|
||||
|
||||
// ── "Verlauf" tab: every value ever received, timestamped ──────────
|
||||
auto *historyTab = new QWidget(m_tabs);
|
||||
auto *historyLayout = new QVBoxLayout(historyTab);
|
||||
historyLayout->setContentsMargins(0, 4, 0, 0);
|
||||
historyLayout->setSpacing(4);
|
||||
|
||||
m_historyEdit = new QPlainTextEdit(historyTab);
|
||||
m_historyEdit->setReadOnly(true);
|
||||
m_historyEdit->setMaximumHeight(220);
|
||||
m_historyEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
|
||||
QFont mono("Monospace");
|
||||
mono.setStyleHint(QFont::Monospace);
|
||||
mono.setPointSize(9);
|
||||
m_historyEdit->setFont(mono);
|
||||
historyLayout->addWidget(m_historyEdit);
|
||||
|
||||
auto *historyBtnRow = new QHBoxLayout();
|
||||
auto *clearHistBtn = new QPushButton(tr("Verlauf leeren"), historyTab);
|
||||
clearHistBtn->setToolTip(tr("Nur den Verlauf dieses Tags leeren (Panel bleibt bestehen)"));
|
||||
connect(clearHistBtn, &QPushButton::clicked, this, &TagPanel::clearHistory);
|
||||
historyBtnRow->addStretch();
|
||||
historyBtnRow->addWidget(clearHistBtn);
|
||||
historyLayout->addLayout(historyBtnRow);
|
||||
|
||||
m_tabs->addTab(historyTab, tr("Verlauf"));
|
||||
|
||||
layout->addWidget(m_tabs);
|
||||
|
||||
auto *btnRow = new QHBoxLayout();
|
||||
btnRow->addStretch();
|
||||
auto *copyBtn = new QPushButton(tr("📋 Copy"), this);
|
||||
copyBtn->setToolTip(tr("Copy the active tab's content to clipboard"));
|
||||
copyBtn->setMaximumWidth(90);
|
||||
connect(copyBtn, &QPushButton::clicked, this, &TagPanel::copyToClipboard);
|
||||
btnRow->addWidget(copyBtn);
|
||||
layout->addLayout(btnRow);
|
||||
}
|
||||
|
||||
void TagPanel::update(const QString &value)
|
||||
{
|
||||
m_timestampLabel->setText(
|
||||
QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
|
||||
appendHistory(value);
|
||||
|
||||
// Detect key=value format: word=anything (space separated)
|
||||
static const QRegularExpression kvRe(R"((\w+)=(\S+))");
|
||||
auto it = kvRe.globalMatch(value);
|
||||
if (it.hasNext()) {
|
||||
if (kvRe.match(value).hasMatch()) {
|
||||
parseKeyValue(value);
|
||||
m_rawLabel->hide();
|
||||
m_table->show();
|
||||
@@ -53,19 +96,90 @@ void TagPanel::update(const QString &value)
|
||||
}
|
||||
}
|
||||
|
||||
void TagPanel::appendHistory(const QString &value)
|
||||
{
|
||||
const QString ts = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
|
||||
m_historyEdit->appendPlainText(QStringLiteral("[%1] %2").arg(ts, value));
|
||||
m_historyEdit->verticalScrollBar()->setValue(
|
||||
m_historyEdit->verticalScrollBar()->maximum());
|
||||
|
||||
++m_historyCount;
|
||||
if (m_historyCount > kMaxHistoryEntries) {
|
||||
// Drop the oldest entry (topmost line) to keep memory use bounded
|
||||
// for very chatty or long-running tags.
|
||||
QTextCursor cursor(m_historyEdit->document());
|
||||
cursor.movePosition(QTextCursor::Start);
|
||||
cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor);
|
||||
cursor.removeSelectedText();
|
||||
--m_historyCount;
|
||||
}
|
||||
}
|
||||
|
||||
void TagPanel::clearHistory()
|
||||
{
|
||||
m_historyEdit->clear();
|
||||
m_historyCount = 0;
|
||||
}
|
||||
|
||||
void TagPanel::parseKeyValue(const QString &value)
|
||||
{
|
||||
static const QRegularExpression kvRe(R"((\w+)=(\S+))");
|
||||
auto it = kvRe.globalMatch(value);
|
||||
while (it.hasNext()) {
|
||||
const auto match = it.next();
|
||||
const QString key = match.captured(1);
|
||||
const QString val = match.captured(2);
|
||||
ensureRow(key);
|
||||
const int row = m_keys.indexOf(key);
|
||||
m_table->item(row, 1)->setText(val);
|
||||
// Flash highlight
|
||||
m_table->item(row, 1)->setBackground(QColor(0x2d, 0x5a, 0x2d));
|
||||
const QString key = match.captured(1);
|
||||
const QString raw = match.captured(2);
|
||||
|
||||
// Split on ';' -> list of values. A plain (non-list) value yields
|
||||
// a QStringList with exactly one element, which still goes through
|
||||
// the same code path for consistency.
|
||||
QStringList values = raw.split(';', Qt::SkipEmptyParts);
|
||||
if (values.isEmpty())
|
||||
values << raw; // preserve even an empty/odd value as-is
|
||||
|
||||
setKeyValues(key, values);
|
||||
}
|
||||
}
|
||||
|
||||
void TagPanel::setKeyValues(const QString &key, const QStringList &values)
|
||||
{
|
||||
const int newCount = values.size();
|
||||
|
||||
if (m_keyRanges.contains(key)) {
|
||||
// Key already exists – remove its current rows, then re-insert at
|
||||
// the same starting position with the new row count.
|
||||
const KeyRange old = m_keyRanges[key];
|
||||
for (int i = 0; i < old.count; ++i)
|
||||
m_table->removeRow(old.firstRow);
|
||||
|
||||
// Shift all OTHER key ranges that started after this one
|
||||
for (auto it = m_keyRanges.begin(); it != m_keyRanges.end(); ++it) {
|
||||
if (it.key() != key && it->firstRow > old.firstRow)
|
||||
it->firstRow += (newCount - old.count);
|
||||
}
|
||||
|
||||
int insertAt = old.firstRow;
|
||||
for (int i = 0; i < newCount; ++i) {
|
||||
m_table->insertRow(insertAt + i);
|
||||
auto *keyItem = new QTableWidgetItem(i == 0 ? key : QString());
|
||||
auto *valItem = new QTableWidgetItem(values[i]);
|
||||
valItem->setBackground(QColor(0x2d, 0x5a, 0x2d)); // flash green on update
|
||||
m_table->setItem(insertAt + i, 0, keyItem);
|
||||
m_table->setItem(insertAt + i, 1, valItem);
|
||||
}
|
||||
m_keyRanges[key] = {insertAt, newCount};
|
||||
} else {
|
||||
// New key – append at the bottom
|
||||
const int insertAt = m_table->rowCount();
|
||||
for (int i = 0; i < newCount; ++i) {
|
||||
m_table->insertRow(insertAt + i);
|
||||
auto *keyItem = new QTableWidgetItem(i == 0 ? key : QString());
|
||||
auto *valItem = new QTableWidgetItem(values[i]);
|
||||
valItem->setBackground(QColor(0x2d, 0x5a, 0x2d));
|
||||
m_table->setItem(insertAt + i, 0, keyItem);
|
||||
m_table->setItem(insertAt + i, 1, valItem);
|
||||
}
|
||||
m_keyRanges[key] = {insertAt, newCount};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,13 +188,33 @@ void TagPanel::showRaw(const QString &value)
|
||||
m_rawLabel->setText(value);
|
||||
}
|
||||
|
||||
void TagPanel::ensureRow(const QString &key)
|
||||
void TagPanel::copyToClipboard()
|
||||
{
|
||||
if (m_keys.contains(key))
|
||||
QStringList lines;
|
||||
lines << QStringLiteral("[%1]").arg(m_tag);
|
||||
|
||||
if (m_tabs->currentIndex() == 1) {
|
||||
// "Verlauf" tab active - copy the full timestamped history as-is.
|
||||
QApplication::clipboard()->setText(
|
||||
lines.join('\n') + '\n' + m_historyEdit->toPlainText());
|
||||
return;
|
||||
m_keys.append(key);
|
||||
const int row = m_table->rowCount();
|
||||
m_table->insertRow(row);
|
||||
m_table->setItem(row, 0, new QTableWidgetItem(key));
|
||||
m_table->setItem(row, 1, new QTableWidgetItem(QString()));
|
||||
}
|
||||
|
||||
if (m_table->isVisible()) {
|
||||
QString lastKey;
|
||||
for (int r = 0; r < m_table->rowCount(); ++r) {
|
||||
const QString key = m_table->item(r, 0)->text();
|
||||
const QString val = m_table->item(r, 1)->text();
|
||||
if (!key.isEmpty()) {
|
||||
lines << QStringLiteral(" %1 = %2").arg(key, val);
|
||||
lastKey = key;
|
||||
} else {
|
||||
lines << QStringLiteral(" %1").arg(val); // continuation row
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lines << QStringLiteral(" %1").arg(m_rawLabel->text());
|
||||
}
|
||||
|
||||
QApplication::clipboard()->setText(lines.join('\n'));
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ TagWidget::TagWidget(QWidget *parent)
|
||||
outerLayout->setContentsMargins(4, 4, 4, 4);
|
||||
outerLayout->setSpacing(4);
|
||||
|
||||
// Header row
|
||||
auto *headerLayout = new QHBoxLayout();
|
||||
auto *titleLabel = new QLabel(tr("<b>Tag Monitor</b>"), this);
|
||||
auto *clearBtn = new QPushButton(tr("Clear all"), this);
|
||||
@@ -18,7 +17,6 @@ TagWidget::TagWidget(QWidget *parent)
|
||||
headerLayout->addWidget(clearBtn);
|
||||
outerLayout->addLayout(headerLayout);
|
||||
|
||||
// Scrollable panel area
|
||||
auto *scrollArea = new QScrollArea(this);
|
||||
scrollArea->setWidgetResizable(true);
|
||||
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
|
||||
@@ -26,7 +24,7 @@ TagWidget::TagWidget(QWidget *parent)
|
||||
m_panelLayout = new QVBoxLayout(container);
|
||||
m_panelLayout->setContentsMargins(0, 0, 0, 0);
|
||||
m_panelLayout->setSpacing(6);
|
||||
m_panelLayout->addStretch(); // pushes panels to the top
|
||||
m_panelLayout->addStretch();
|
||||
scrollArea->setWidget(container);
|
||||
outerLayout->addWidget(scrollArea, 1);
|
||||
}
|
||||
@@ -36,7 +34,6 @@ void TagWidget::handleTag(const QString &tag, const QString &value)
|
||||
if (!m_panels.contains(tag)) {
|
||||
auto *panel = new TagPanel(tag, this);
|
||||
m_panels.insert(tag, panel);
|
||||
// Insert before the stretch at the end
|
||||
m_panelLayout->insertWidget(m_panelLayout->count() - 1, panel);
|
||||
}
|
||||
m_panels[tag]->update(value);
|
||||
|
||||
265
src/v4l2worker.cpp
Normal file
265
src/v4l2worker.cpp
Normal file
@@ -0,0 +1,265 @@
|
||||
#include "v4l2worker.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <linux/videodev2.h>
|
||||
|
||||
#include <QBuffer>
|
||||
#include <QImageReader>
|
||||
|
||||
static int xioctl(int fd, unsigned long req, void *arg)
|
||||
{
|
||||
int r;
|
||||
do { r = ::ioctl(fd, req, arg); } while (r == -1 && errno == EINTR);
|
||||
return r;
|
||||
}
|
||||
|
||||
V4l2Worker::V4l2Worker(QObject *parent) : QObject(parent) {}
|
||||
|
||||
V4l2Worker::~V4l2Worker() { stop(); }
|
||||
|
||||
void V4l2Worker::startCapture(const QString &device, int width, int height)
|
||||
{
|
||||
if (m_running.load())
|
||||
stop();
|
||||
|
||||
if (!openDevice(device, width, height))
|
||||
return;
|
||||
|
||||
m_running.store(true);
|
||||
m_captureThread = std::thread([this] { captureLoop(); });
|
||||
}
|
||||
|
||||
void V4l2Worker::stopCapture() { stop(); }
|
||||
|
||||
void V4l2Worker::stop()
|
||||
{
|
||||
m_running.store(false);
|
||||
if (m_captureThread.joinable())
|
||||
m_captureThread.join();
|
||||
closeDevice();
|
||||
}
|
||||
|
||||
void V4l2Worker::captureLoop()
|
||||
{
|
||||
v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
if (xioctl(m_fd, VIDIOC_STREAMON, &type) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_STREAMON failed: %1").arg(strerror(errno)));
|
||||
m_running.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
while (m_running.load()) {
|
||||
fd_set fds;
|
||||
FD_ZERO(&fds);
|
||||
FD_SET(m_fd, &fds);
|
||||
timeval tv{0, 100000};
|
||||
const int r = ::select(m_fd + 1, &fds, nullptr, nullptr, &tv);
|
||||
if (r == 0) continue;
|
||||
if (r == -1) {
|
||||
if (errno == EINTR) continue;
|
||||
emit errorOccurred(tr("select() failed: %1").arg(strerror(errno)));
|
||||
break;
|
||||
}
|
||||
|
||||
v4l2_buffer buf{};
|
||||
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
buf.memory = V4L2_MEMORY_MMAP;
|
||||
if (xioctl(m_fd, VIDIOC_DQBUF, &buf) == -1) {
|
||||
if (errno == EAGAIN) continue;
|
||||
emit errorOccurred(tr("VIDIOC_DQBUF failed: %1").arg(strerror(errno)));
|
||||
break;
|
||||
}
|
||||
|
||||
const QImage img = convertToImage(
|
||||
m_buffers[buf.index].start, buf.bytesused, m_width, m_height);
|
||||
if (!img.isNull())
|
||||
emit newFrame(img);
|
||||
|
||||
if (xioctl(m_fd, VIDIOC_QBUF, &buf) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_QBUF failed: %1").arg(strerror(errno)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
xioctl(m_fd, VIDIOC_STREAMOFF, &type);
|
||||
emit captureStopped();
|
||||
}
|
||||
|
||||
bool V4l2Worker::openDevice(const QString &device, int width, int height)
|
||||
{
|
||||
m_width = width;
|
||||
m_height = height;
|
||||
|
||||
m_fd = ::open(device.toLocal8Bit().constData(), O_RDWR | O_NONBLOCK);
|
||||
if (m_fd == -1) {
|
||||
emit errorOccurred(tr("Cannot open %1: %2").arg(device, strerror(errno)));
|
||||
return false;
|
||||
}
|
||||
|
||||
v4l2_capability cap{};
|
||||
if (xioctl(m_fd, VIDIOC_QUERYCAP, &cap) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_QUERYCAP failed: %1").arg(strerror(errno)));
|
||||
closeDevice();
|
||||
return false;
|
||||
}
|
||||
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
|
||||
emit errorOccurred(tr("%1 is not a video capture device").arg(device));
|
||||
closeDevice();
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint32_t preferred[] = {
|
||||
V4L2_PIX_FMT_MJPEG, V4L2_PIX_FMT_YUYV, V4L2_PIX_FMT_NV12, 0
|
||||
};
|
||||
|
||||
m_pixFmt = 0;
|
||||
for (int i = 0; preferred[i]; ++i) {
|
||||
v4l2_format fmt{};
|
||||
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
fmt.fmt.pix.width = static_cast<uint32_t>(width);
|
||||
fmt.fmt.pix.height = static_cast<uint32_t>(height);
|
||||
fmt.fmt.pix.pixelformat = preferred[i];
|
||||
fmt.fmt.pix.field = V4L2_FIELD_ANY;
|
||||
if (xioctl(m_fd, VIDIOC_S_FMT, &fmt) == 0) {
|
||||
m_pixFmt = fmt.fmt.pix.pixelformat;
|
||||
m_width = static_cast<int>(fmt.fmt.pix.width);
|
||||
m_height = static_cast<int>(fmt.fmt.pix.height);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!m_pixFmt) {
|
||||
emit errorOccurred(tr("No supported pixel format found on %1").arg(device));
|
||||
closeDevice();
|
||||
return false;
|
||||
}
|
||||
|
||||
QString fmtName;
|
||||
switch (m_pixFmt) {
|
||||
case V4L2_PIX_FMT_MJPEG: fmtName = "MJPEG"; break;
|
||||
case V4L2_PIX_FMT_YUYV: fmtName = "YUYV"; break;
|
||||
case V4L2_PIX_FMT_NV12: fmtName = "NV12"; break;
|
||||
default: fmtName = "?"; break;
|
||||
}
|
||||
|
||||
if (!initMmap()) {
|
||||
closeDevice();
|
||||
return false;
|
||||
}
|
||||
|
||||
emit captureStarted(device, m_width, m_height, fmtName);
|
||||
return true;
|
||||
}
|
||||
|
||||
void V4l2Worker::closeDevice()
|
||||
{
|
||||
freeMmap();
|
||||
if (m_fd != -1) {
|
||||
::close(m_fd);
|
||||
m_fd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
bool V4l2Worker::initMmap()
|
||||
{
|
||||
v4l2_requestbuffers req{};
|
||||
req.count = MMAP_BUFFERS;
|
||||
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
req.memory = V4L2_MEMORY_MMAP;
|
||||
if (xioctl(m_fd, VIDIOC_REQBUFS, &req) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_REQBUFS failed: %1").arg(strerror(errno)));
|
||||
return false;
|
||||
}
|
||||
m_nBuffers = static_cast<int>(req.count);
|
||||
|
||||
for (int i = 0; i < m_nBuffers; ++i) {
|
||||
v4l2_buffer buf{};
|
||||
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
|
||||
buf.memory = V4L2_MEMORY_MMAP;
|
||||
buf.index = static_cast<uint32_t>(i);
|
||||
if (xioctl(m_fd, VIDIOC_QUERYBUF, &buf) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_QUERYBUF failed: %1").arg(strerror(errno)));
|
||||
return false;
|
||||
}
|
||||
m_buffers[i].length = buf.length;
|
||||
m_buffers[i].start = ::mmap(nullptr, buf.length,
|
||||
PROT_READ | PROT_WRITE, MAP_SHARED,
|
||||
m_fd, buf.m.offset);
|
||||
if (m_buffers[i].start == MAP_FAILED) {
|
||||
emit errorOccurred(tr("mmap failed: %1").arg(strerror(errno)));
|
||||
return false;
|
||||
}
|
||||
if (xioctl(m_fd, VIDIOC_QBUF, &buf) == -1) {
|
||||
emit errorOccurred(tr("VIDIOC_QBUF failed: %1").arg(strerror(errno)));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void V4l2Worker::freeMmap()
|
||||
{
|
||||
for (int i = 0; i < m_nBuffers; ++i) {
|
||||
if (m_buffers[i].start && m_buffers[i].start != MAP_FAILED) {
|
||||
::munmap(m_buffers[i].start, m_buffers[i].length);
|
||||
m_buffers[i].start = nullptr;
|
||||
}
|
||||
}
|
||||
m_nBuffers = 0;
|
||||
}
|
||||
|
||||
QImage V4l2Worker::convertToImage(const void *data, size_t size, int width, int height)
|
||||
{
|
||||
switch (m_pixFmt) {
|
||||
case V4L2_PIX_FMT_MJPEG: {
|
||||
QByteArray ba(static_cast<const char *>(data), static_cast<int>(size));
|
||||
QBuffer buf(&ba);
|
||||
QImageReader reader(&buf, "JPEG");
|
||||
return reader.read();
|
||||
}
|
||||
case V4L2_PIX_FMT_YUYV:
|
||||
return yuyv2Rgb(static_cast<const uchar *>(data), width, height);
|
||||
case V4L2_PIX_FMT_NV12:
|
||||
return nv122Rgb(static_cast<const uchar *>(data), width, height);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
QImage V4l2Worker::yuyv2Rgb(const uchar *src, int width, int height)
|
||||
{
|
||||
QImage img(width, height, QImage::Format_RGB32);
|
||||
for (int y = 0; y < height; ++y) {
|
||||
const uchar *row = src + y * width * 2;
|
||||
QRgb *dst = reinterpret_cast<QRgb *>(img.scanLine(y));
|
||||
for (int x = 0; x < width; x += 2) {
|
||||
const int Y0 = row[0], U = row[1]-128, Y1 = row[2], V = row[3]-128;
|
||||
row += 4;
|
||||
auto clamp = [](int v) { return static_cast<uchar>(v<0?0:v>255?255:v); };
|
||||
dst[x] = qRgb(clamp(Y0+1.402f*V), clamp(Y0-0.344f*U-0.714f*V), clamp(Y0+1.772f*U));
|
||||
dst[x+1] = qRgb(clamp(Y1+1.402f*V), clamp(Y1-0.344f*U-0.714f*V), clamp(Y1+1.772f*U));
|
||||
}
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
QImage V4l2Worker::nv122Rgb(const uchar *src, int width, int height)
|
||||
{
|
||||
QImage img(width, height, QImage::Format_RGB32);
|
||||
const uchar *uvPlane = src + width * height;
|
||||
auto clamp = [](int v) { return static_cast<uchar>(v<0?0:v>255?255:v); };
|
||||
for (int y = 0; y < height; ++y) {
|
||||
const uchar *yRow = src + y * width;
|
||||
const uchar *uvRow = uvPlane + (y/2) * width;
|
||||
QRgb *dst = reinterpret_cast<QRgb *>(img.scanLine(y));
|
||||
for (int x = 0; x < width; ++x) {
|
||||
const int Y = yRow[x], U = uvRow[x&~1]-128, V = uvRow[(x&~1)+1]-128;
|
||||
dst[x] = qRgb(clamp(Y+1.402f*V), clamp(Y-0.344f*U-0.714f*V), clamp(Y+1.772f*U));
|
||||
}
|
||||
}
|
||||
return img;
|
||||
}
|
||||
393
src/videowidget.cpp
Normal file
393
src/videowidget.cpp
Normal file
@@ -0,0 +1,393 @@
|
||||
#include "videowidget.h"
|
||||
|
||||
#include <QPainter>
|
||||
#include <QFileDialog>
|
||||
#include <QDir>
|
||||
#include <QDateTime>
|
||||
#include <QStandardPaths>
|
||||
#include <QMetaObject>
|
||||
#include <QResizeEvent>
|
||||
#include <QMessageBox>
|
||||
|
||||
static QStringList enumerateVideoDevices()
|
||||
{
|
||||
QStringList devices;
|
||||
const QDir dev("/dev");
|
||||
const auto entries = dev.entryList({"video*"}, QDir::System, QDir::Name);
|
||||
for (const auto &e : entries)
|
||||
devices << "/dev/" + e;
|
||||
return devices;
|
||||
}
|
||||
|
||||
VideoWidget::VideoWidget(QWidget *parent)
|
||||
: QWidget(parent)
|
||||
{
|
||||
setupUi();
|
||||
|
||||
m_thread = new QThread(this);
|
||||
m_worker = new V4l2Worker();
|
||||
m_worker->moveToThread(m_thread);
|
||||
|
||||
connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);
|
||||
|
||||
connect(m_worker, &V4l2Worker::newFrame, this, &VideoWidget::onNewFrame,
|
||||
Qt::QueuedConnection);
|
||||
connect(m_worker, &V4l2Worker::captureStarted, this, [this](const QString &dev, int w, int h, const QString &fmt) {
|
||||
m_infoLabel->setText(tr("%1 %2×%3 %4").arg(dev).arg(w).arg(h).arg(fmt));
|
||||
m_running = true;
|
||||
m_startBtn->setText(tr("■ Stop"));
|
||||
});
|
||||
connect(m_worker, &V4l2Worker::captureStopped, this, [this] {
|
||||
m_running = false;
|
||||
m_startBtn->setText(tr("▶ Start"));
|
||||
m_infoLabel->setText(tr("Stopped"));
|
||||
if (m_recording)
|
||||
stopRecording();
|
||||
update();
|
||||
});
|
||||
connect(m_worker, &V4l2Worker::errorOccurred, this, [this](const QString &msg) {
|
||||
m_infoLabel->setText(tr("Error: %1").arg(msg));
|
||||
m_running = false;
|
||||
m_startBtn->setText(tr("▶ Start"));
|
||||
if (m_recording)
|
||||
stopRecording();
|
||||
});
|
||||
|
||||
m_thread->start();
|
||||
}
|
||||
|
||||
void VideoWidget::shutdown()
|
||||
{
|
||||
if (m_shutdownDone)
|
||||
return;
|
||||
m_shutdownDone = true;
|
||||
|
||||
if (m_recording)
|
||||
stopRecording();
|
||||
|
||||
m_worker->stopCapture();
|
||||
|
||||
if (m_thread && m_thread->isRunning()) {
|
||||
m_thread->quit();
|
||||
m_thread->wait(5000);
|
||||
if (m_thread->isRunning())
|
||||
m_thread->terminate();
|
||||
}
|
||||
}
|
||||
|
||||
VideoWidget::~VideoWidget()
|
||||
{
|
||||
shutdown();
|
||||
}
|
||||
|
||||
void VideoWidget::setupUi()
|
||||
{
|
||||
setMinimumHeight(140);
|
||||
|
||||
auto *layout = new QVBoxLayout(this);
|
||||
layout->setContentsMargins(2, 2, 2, 2);
|
||||
layout->setSpacing(3);
|
||||
|
||||
auto *ctrlRow = new QHBoxLayout();
|
||||
ctrlRow->setSpacing(4);
|
||||
|
||||
m_deviceCombo = new QComboBox(this);
|
||||
m_deviceCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
|
||||
refreshDeviceList();
|
||||
|
||||
auto *refreshBtn = new QPushButton("↻", this);
|
||||
refreshBtn->setMaximumWidth(26);
|
||||
connect(refreshBtn, &QPushButton::clicked, this, &VideoWidget::refreshDeviceList);
|
||||
|
||||
m_startBtn = new QPushButton(tr("▶ Start"), this);
|
||||
m_startBtn->setMaximumWidth(70);
|
||||
connect(m_startBtn, &QPushButton::clicked, this, &VideoWidget::onStartStop);
|
||||
|
||||
m_freezeBtn = new QPushButton(tr("❚❚ Freeze"), this);
|
||||
m_freezeBtn->setCheckable(true);
|
||||
m_freezeBtn->setMaximumWidth(80);
|
||||
connect(m_freezeBtn, &QPushButton::toggled, this, &VideoWidget::onFreeze);
|
||||
|
||||
m_screenshotBtn = new QPushButton(tr("📷"), this);
|
||||
m_screenshotBtn->setMaximumWidth(32);
|
||||
connect(m_screenshotBtn, &QPushButton::clicked, this, &VideoWidget::onScreenshot);
|
||||
|
||||
m_recordBtn = new QPushButton(tr("⏺ Record"), this);
|
||||
m_recordBtn->setCheckable(true);
|
||||
m_recordBtn->setMaximumWidth(80);
|
||||
m_recordBtn->setToolTip(tr("Record the live preview to an MP4 file (requires ffmpeg)"));
|
||||
connect(m_recordBtn, &QPushButton::toggled, this, &VideoWidget::onRecordToggled);
|
||||
|
||||
ctrlRow->addWidget(m_deviceCombo, 1);
|
||||
ctrlRow->addWidget(refreshBtn);
|
||||
ctrlRow->addWidget(m_startBtn);
|
||||
ctrlRow->addWidget(m_freezeBtn);
|
||||
ctrlRow->addWidget(m_screenshotBtn);
|
||||
ctrlRow->addWidget(m_recordBtn);
|
||||
layout->addLayout(ctrlRow);
|
||||
|
||||
m_infoLabel = new QLabel(tr("No device started"), this);
|
||||
m_infoLabel->setStyleSheet("color: gray; font-size: 9px;");
|
||||
layout->addWidget(m_infoLabel);
|
||||
|
||||
layout->addStretch(1);
|
||||
}
|
||||
|
||||
void VideoWidget::onStartStop()
|
||||
{
|
||||
if (m_running) stopCapture();
|
||||
else startCapture();
|
||||
}
|
||||
|
||||
void VideoWidget::onFreeze(bool frozen)
|
||||
{
|
||||
m_frozen = frozen;
|
||||
m_freezeBtn->setText(frozen ? tr("▶ Live") : tr("❚❚ Freeze"));
|
||||
}
|
||||
|
||||
void VideoWidget::onScreenshot()
|
||||
{
|
||||
if (m_frame.isNull())
|
||||
return;
|
||||
|
||||
const QString defaultName =
|
||||
QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)
|
||||
+ "/uartscope_"
|
||||
+ QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")
|
||||
+ ".png";
|
||||
|
||||
const QString path = QFileDialog::getSaveFileName(
|
||||
this, tr("Save screenshot"), defaultName,
|
||||
tr("PNG Image (*.png);;JPEG Image (*.jpg *.jpeg)"));
|
||||
|
||||
if (!path.isEmpty())
|
||||
m_frame.save(path);
|
||||
}
|
||||
|
||||
void VideoWidget::onNewFrame(const QImage &frame)
|
||||
{
|
||||
// Feed the recorder regardless of freeze state, so pausing the preview
|
||||
// doesn't also pause/corrupt the recording - recording tracks the real
|
||||
// incoming stream, not what's currently shown on screen.
|
||||
if (m_recording && m_recordProcess &&
|
||||
m_recordProcess->state() == QProcess::Running) {
|
||||
writeRecordingFrame(frame);
|
||||
}
|
||||
|
||||
if (m_frozen)
|
||||
return;
|
||||
m_frame = frame;
|
||||
updateScaled();
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoWidget::clearFrame()
|
||||
{
|
||||
m_frame = QImage();
|
||||
m_scaled = QImage();
|
||||
update();
|
||||
}
|
||||
|
||||
void VideoWidget::refreshDeviceList()
|
||||
{
|
||||
const QString current = m_deviceCombo->currentText();
|
||||
m_deviceCombo->clear();
|
||||
const auto devices = enumerateVideoDevices();
|
||||
for (const auto &d : devices)
|
||||
m_deviceCombo->addItem(d);
|
||||
const int idx = m_deviceCombo->findText(current);
|
||||
if (idx >= 0)
|
||||
m_deviceCombo->setCurrentIndex(idx);
|
||||
}
|
||||
|
||||
void VideoWidget::startCapture()
|
||||
{
|
||||
const QString dev = m_deviceCombo->currentText();
|
||||
if (dev.isEmpty())
|
||||
return;
|
||||
m_frame = QImage();
|
||||
m_scaled = QImage();
|
||||
QMetaObject::invokeMethod(m_worker, "startCapture",
|
||||
Qt::QueuedConnection,
|
||||
Q_ARG(QString, dev),
|
||||
Q_ARG(int, 1920),
|
||||
Q_ARG(int, 1080));
|
||||
}
|
||||
|
||||
void VideoWidget::stopCapture()
|
||||
{
|
||||
QMetaObject::invokeMethod(m_worker, "stopCapture", Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void VideoWidget::updateScaled()
|
||||
{
|
||||
const QRect videoRect(0, 55, width(), height() - 55);
|
||||
if (videoRect.width() < 10 || videoRect.height() < 10 || m_frame.isNull())
|
||||
return;
|
||||
|
||||
m_scaled = m_frame.scaled(videoRect.size(), Qt::KeepAspectRatio,
|
||||
Qt::SmoothTransformation);
|
||||
}
|
||||
|
||||
void VideoWidget::paintEvent(QPaintEvent *)
|
||||
{
|
||||
QPainter p(this);
|
||||
p.fillRect(rect(), QColor(0x10, 0x10, 0x10));
|
||||
|
||||
if (m_scaled.isNull()) {
|
||||
p.setPen(QColor(0x44, 0x44, 0x44));
|
||||
p.drawText(rect(), Qt::AlignCenter,
|
||||
m_running ? tr("Waiting for frames…") : tr("No signal"));
|
||||
return;
|
||||
}
|
||||
|
||||
const QRect videoRect(0, 55, width(), height() - 55);
|
||||
const QPoint origin(
|
||||
videoRect.left() + (videoRect.width() - m_scaled.width()) / 2,
|
||||
videoRect.top() + (videoRect.height() - m_scaled.height()) / 2);
|
||||
p.drawImage(origin, m_scaled);
|
||||
|
||||
if (m_frozen) {
|
||||
p.setPen(QColor(0xff, 0xcc, 0x00));
|
||||
p.setFont(QFont("Sans", 9, QFont::Bold));
|
||||
p.drawText(videoRect.adjusted(4, 4, -4, -4),
|
||||
Qt::AlignTop | Qt::AlignRight, tr("FREEZE"));
|
||||
}
|
||||
}
|
||||
|
||||
void VideoWidget::resizeEvent(QResizeEvent *event)
|
||||
{
|
||||
QWidget::resizeEvent(event);
|
||||
updateScaled();
|
||||
}
|
||||
|
||||
// ── Recording (raw frames piped into ffmpeg, encoded to MP4) ──────────────
|
||||
|
||||
void VideoWidget::onRecordToggled(bool checked)
|
||||
{
|
||||
if (checked)
|
||||
startRecording();
|
||||
else
|
||||
stopRecording();
|
||||
}
|
||||
|
||||
void VideoWidget::startRecording()
|
||||
{
|
||||
if (m_frame.isNull()) {
|
||||
QMessageBox::warning(this, tr("No signal"),
|
||||
tr("Start the video capture first before recording."));
|
||||
m_recordBtn->setChecked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const QString defaultName =
|
||||
QStandardPaths::writableLocation(QStandardPaths::MoviesLocation)
|
||||
+ "/uartscope_"
|
||||
+ QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")
|
||||
+ ".mp4";
|
||||
|
||||
const QString path = QFileDialog::getSaveFileName(
|
||||
this, tr("Save recording as"), defaultName,
|
||||
tr("MP4 Video (*.mp4)"));
|
||||
if (path.isEmpty()) {
|
||||
m_recordBtn->setChecked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Frames are piped in as raw BGRA (matching QImage::Format_RGB32's
|
||||
// in-memory byte layout on little-endian systems) at whatever
|
||||
// resolution capture is currently running at; a resolution change
|
||||
// mid-recording would corrupt ffmpeg's raw input stream, so
|
||||
// writeRecordingFrame() watches for that and stops the recording if
|
||||
// it happens (see there).
|
||||
m_recordSize = m_frame.size();
|
||||
|
||||
m_recordProcess = new QProcess(this);
|
||||
|
||||
connect(m_recordProcess, &QProcess::errorOccurred, this, [this](QProcess::ProcessError) {
|
||||
m_infoLabel->setText(tr("Recording error: %1").arg(m_recordProcess->errorString()));
|
||||
stopRecording();
|
||||
});
|
||||
connect(m_recordProcess,
|
||||
QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
|
||||
this, [this](int exitCode, QProcess::ExitStatus) {
|
||||
if (exitCode != 0 && m_recordProcess)
|
||||
m_infoLabel->setText(tr("ffmpeg exited with code %1").arg(exitCode));
|
||||
if (m_recordProcess) {
|
||||
m_recordProcess->deleteLater();
|
||||
m_recordProcess = nullptr;
|
||||
}
|
||||
});
|
||||
|
||||
// -use_wallclock_as_timestamps: frames don't arrive at a strictly
|
||||
// constant rate (V4L2 delivers whatever the device/driver produces),
|
||||
// so we let ffmpeg timestamp each frame using the system clock at the
|
||||
// moment it's read from the pipe rather than assuming a fixed
|
||||
// framerate. That keeps the resulting MP4's real-time duration
|
||||
// correct even if the capture rate varies or briefly stalls.
|
||||
const QStringList args = {
|
||||
"-y",
|
||||
"-f", "rawvideo",
|
||||
"-pixel_format", "bgra",
|
||||
"-video_size", QStringLiteral("%1x%2").arg(m_recordSize.width()).arg(m_recordSize.height()),
|
||||
"-use_wallclock_as_timestamps", "1",
|
||||
"-i", "-",
|
||||
"-c:v", "libx264",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-preset", "veryfast",
|
||||
"-movflags", "+faststart",
|
||||
path
|
||||
};
|
||||
|
||||
m_recordProcess->start("ffmpeg", args);
|
||||
if (!m_recordProcess->waitForStarted(3000)) {
|
||||
QMessageBox::critical(this, tr("Recording failed"),
|
||||
tr("Could not start ffmpeg. Is it installed and available on PATH?"));
|
||||
m_recordProcess->deleteLater();
|
||||
m_recordProcess = nullptr;
|
||||
m_recordBtn->setChecked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
m_recording = true;
|
||||
m_recordBtn->setText(tr("⏹ Stop"));
|
||||
m_infoLabel->setText(tr("Recording to %1").arg(path));
|
||||
}
|
||||
|
||||
void VideoWidget::stopRecording()
|
||||
{
|
||||
m_recording = false;
|
||||
m_recordBtn->setChecked(false);
|
||||
m_recordBtn->setText(tr("⏺ Record"));
|
||||
|
||||
if (m_recordProcess) {
|
||||
// Closing stdin signals ffmpeg there's no more input; it then
|
||||
// finishes encoding/muxing and exits on its own. The finished()
|
||||
// handler connected in startRecording() cleans the QProcess up
|
||||
// once that happens.
|
||||
m_recordProcess->closeWriteChannel();
|
||||
if (!m_recordProcess->waitForFinished(3000))
|
||||
m_recordProcess->terminate();
|
||||
}
|
||||
}
|
||||
|
||||
void VideoWidget::writeRecordingFrame(const QImage &frame)
|
||||
{
|
||||
if (frame.size() != m_recordSize) {
|
||||
// The capture device changed resolution mid-recording (shouldn't
|
||||
// normally happen, but e.g. a device re-negotiating format could
|
||||
// trigger it). Feeding ffmpeg mismatched frame sizes on a raw pipe
|
||||
// would desync/corrupt the output, so stop cleanly instead.
|
||||
stopRecording();
|
||||
m_infoLabel->setText(tr("Recording stopped: frame size changed"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Format_RGB32 stores each pixel as 0xffRRGGBB in host byte order,
|
||||
// which on little-endian systems (the overwhelming majority of
|
||||
// desktop/embedded targets) is byte-for-byte BGRA - matching the
|
||||
// "-pixel_format bgra" we told ffmpeg to expect above.
|
||||
const QImage bgra = frame.convertToFormat(QImage::Format_RGB32);
|
||||
m_recordProcess->write(reinterpret_cast<const char *>(bgra.constBits()),
|
||||
static_cast<qint64>(bgra.sizeInBytes()));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: diabolus <your@email.com>
|
||||
pkgname=uartscope
|
||||
pkgver=1.0.0
|
||||
pkgver=1.0.0.r6.ga942f83
|
||||
pkgrel=1
|
||||
pkgdesc="Qt6-based UART serial monitor with tag monitoring, table view and auto-reconnect"
|
||||
arch=('x86_64' 'aarch64')
|
||||
|
||||
3051
uartscope-git/pkg/uartscope/.BUILDINFO
Normal file
3051
uartscope-git/pkg/uartscope/.BUILDINFO
Normal file
File diff suppressed because it is too large
Load Diff
BIN
uartscope-git/pkg/uartscope/.MTREE
Normal file
BIN
uartscope-git/pkg/uartscope/.MTREE
Normal file
Binary file not shown.
19
uartscope-git/pkg/uartscope/.PKGINFO
Normal file
19
uartscope-git/pkg/uartscope/.PKGINFO
Normal file
@@ -0,0 +1,19 @@
|
||||
# Generated by makepkg 7.1.0
|
||||
# using fakeroot version 1.37.2
|
||||
pkgname = uartscope
|
||||
pkgbase = uartscope
|
||||
xdata = pkgtype=pkg
|
||||
pkgver = 1.0.0.r6.ga942f83-1
|
||||
pkgdesc = Qt6-based UART serial monitor with tag monitoring, table view and auto-reconnect
|
||||
url = https://git.projekt-hirnfrei.de/diabolus/uartscope
|
||||
builddate = 1787005573
|
||||
packager = Unknown Packager
|
||||
size = 406129
|
||||
arch = x86_64
|
||||
license = MIT
|
||||
conflict = uartscope
|
||||
provides = uartscope
|
||||
depend = qt6-base
|
||||
depend = qt6-serialport
|
||||
makedepend = cmake
|
||||
makedepend = git
|
||||
BIN
uartscope-git/pkg/uartscope/usr/bin/uartscope
Executable file
BIN
uartscope-git/pkg/uartscope/usr/bin/uartscope
Executable file
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
[Desktop Entry]
|
||||
Name=UARTScope
|
||||
Comment=UART Serial Monitor
|
||||
Exec=uartscope
|
||||
Icon=uartscope
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Categories=Development;Utility;
|
||||
1
uartscope-git/src/uartscope
Submodule
1
uartscope-git/src/uartscope
Submodule
Submodule uartscope-git/src/uartscope added at a942f8385b
BIN
uartscope-git/uartscope-1.0.0.r0.gcc102c9-1-x86_64.pkg.tar.zst
Normal file
BIN
uartscope-git/uartscope-1.0.0.r0.gcc102c9-1-x86_64.pkg.tar.zst
Normal file
Binary file not shown.
2
uartscope-git/uartscope/FETCH_HEAD
Normal file
2
uartscope-git/uartscope/FETCH_HEAD
Normal file
@@ -0,0 +1,2 @@
|
||||
a942f8385b8b05f5ec9a097ebbb3ba61ad0690f6 not-for-merge branch 'main' of https://git.projekt-hirnfrei.de/diabolus/uartscope
|
||||
cc102c93eb17f7b910d8e74c3505f198bed77f10 not-for-merge tag 'v1.0.0' of https://git.projekt-hirnfrei.de/diabolus/uartscope
|
||||
1
uartscope-git/uartscope/HEAD
Normal file
1
uartscope-git/uartscope/HEAD
Normal file
@@ -0,0 +1 @@
|
||||
ref: refs/heads/main
|
||||
9
uartscope-git/uartscope/config
Normal file
9
uartscope-git/uartscope/config
Normal file
@@ -0,0 +1,9 @@
|
||||
[core]
|
||||
repositoryformatversion = 0
|
||||
filemode = true
|
||||
bare = true
|
||||
[remote "origin"]
|
||||
url = https://git.projekt-hirnfrei.de/diabolus/uartscope.git
|
||||
tagOpt = --no-tags
|
||||
fetch = +refs/*:refs/*
|
||||
mirror = true
|
||||
1
uartscope-git/uartscope/description
Normal file
1
uartscope-git/uartscope/description
Normal file
@@ -0,0 +1 @@
|
||||
Unnamed repository; edit this file 'description' to name the repository.
|
||||
15
uartscope-git/uartscope/hooks/applypatch-msg.sample
Executable file
15
uartscope-git/uartscope/hooks/applypatch-msg.sample
Executable file
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to check the commit log message taken by
|
||||
# applypatch from an e-mail message.
|
||||
#
|
||||
# The hook should exit with non-zero status after issuing an
|
||||
# appropriate message if it wants to stop the commit. The hook is
|
||||
# allowed to edit the commit message file.
|
||||
#
|
||||
# To enable this hook, rename this file to "applypatch-msg".
|
||||
|
||||
. git-sh-setup
|
||||
commitmsg="$(git rev-parse --git-path hooks/commit-msg)"
|
||||
test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"}
|
||||
:
|
||||
74
uartscope-git/uartscope/hooks/commit-msg.sample
Executable file
74
uartscope-git/uartscope/hooks/commit-msg.sample
Executable file
@@ -0,0 +1,74 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to check the commit log message.
|
||||
# Called by "git commit" with one argument, the name of the file
|
||||
# that has the commit message. The hook should exit with non-zero
|
||||
# status after issuing an appropriate message if it wants to stop the
|
||||
# commit. The hook is allowed to edit the commit message file.
|
||||
#
|
||||
# To enable this hook, rename this file to "commit-msg".
|
||||
|
||||
# Uncomment the below to add a Signed-off-by line to the message.
|
||||
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
|
||||
# hook is more suited to it.
|
||||
#
|
||||
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
|
||||
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
|
||||
|
||||
# This example catches duplicate Signed-off-by lines and messages that
|
||||
# would confuse 'git am'.
|
||||
|
||||
ret=0
|
||||
|
||||
test "" = "$(grep '^Signed-off-by: ' "$1" |
|
||||
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
|
||||
echo >&2 Duplicate Signed-off-by lines.
|
||||
ret=1
|
||||
}
|
||||
|
||||
comment_re="$(
|
||||
{
|
||||
git config --get-regexp "^core\.comment(char|string)\$" ||
|
||||
echo '#'
|
||||
} | sed -n -e '
|
||||
${
|
||||
s/^[^ ]* //
|
||||
s|[][*./\]|\\&|g
|
||||
s/^auto$/[#;@!$%^&|:]/
|
||||
p
|
||||
}'
|
||||
)"
|
||||
scissors_line="^${comment_re} -\{8,\} >8 -\{8,\}\$"
|
||||
comment_line="^${comment_re}.*"
|
||||
blank_line='^[ ]*$'
|
||||
# Disallow lines starting with "diff -" or "Index: " in the body of the
|
||||
# message. Stop looking if we see a scissors line.
|
||||
line="$(sed -n -e "
|
||||
# Skip comments and blank lines at the start of the file.
|
||||
/${scissors_line}/q
|
||||
/${comment_line}/d
|
||||
/${blank_line}/d
|
||||
# The first paragraph will become the subject header so
|
||||
# does not need to be checked.
|
||||
: subject
|
||||
n
|
||||
/${scissors_line}/q
|
||||
/${blank_line}/!b subject
|
||||
# Check the body of the message for problematic
|
||||
# prefixes.
|
||||
: body
|
||||
n
|
||||
/${scissors_line}/q
|
||||
/${comment_line}/b body
|
||||
/^diff -/{p;q;}
|
||||
/^Index: /{p;q;}
|
||||
b body
|
||||
" "$1")"
|
||||
if test -n "$line"
|
||||
then
|
||||
echo >&2 "Message contains a diff that will confuse 'git am'."
|
||||
echo >&2 "To fix this indent the diff."
|
||||
ret=1
|
||||
fi
|
||||
|
||||
exit $ret
|
||||
168
uartscope-git/uartscope/hooks/fsmonitor-watchman.sample
Executable file
168
uartscope-git/uartscope/hooks/fsmonitor-watchman.sample
Executable file
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/perl
|
||||
|
||||
use strict;
|
||||
use warnings;
|
||||
use IPC::Open2;
|
||||
|
||||
# An example hook script to integrate Watchman
|
||||
# (https://facebook.github.io/watchman/) with git to speed up detecting
|
||||
# new and modified files.
|
||||
#
|
||||
# The hook is passed a version (currently 2) and last update token
|
||||
# formatted as a string and outputs to stdout a new update token and
|
||||
# all files that have been modified since the update token. Paths must
|
||||
# be relative to the root of the working tree and separated by a single NUL.
|
||||
#
|
||||
# To enable this hook, rename this file to "query-watchman" and set
|
||||
# 'git config core.fsmonitor .git/hooks/query-watchman'
|
||||
#
|
||||
my ($version, $last_update_token) = @ARGV;
|
||||
|
||||
# Uncomment for debugging
|
||||
# print STDERR "$0 $version $last_update_token\n";
|
||||
|
||||
# Check the hook interface version
|
||||
if ($version ne 2) {
|
||||
die "Unsupported query-fsmonitor hook version '$version'.\n" .
|
||||
"Falling back to scanning...\n";
|
||||
}
|
||||
|
||||
my $git_work_tree = get_working_dir();
|
||||
|
||||
my $json_pkg;
|
||||
eval {
|
||||
require JSON::XS;
|
||||
$json_pkg = "JSON::XS";
|
||||
1;
|
||||
} or do {
|
||||
require JSON::PP;
|
||||
$json_pkg = "JSON::PP";
|
||||
};
|
||||
|
||||
launch_watchman();
|
||||
|
||||
sub launch_watchman {
|
||||
my $o = watchman_query();
|
||||
if (is_work_tree_watched($o)) {
|
||||
output_result($o->{clock}, @{$o->{files}});
|
||||
}
|
||||
}
|
||||
|
||||
sub output_result {
|
||||
my ($clockid, @files) = @_;
|
||||
|
||||
# Uncomment for debugging watchman output
|
||||
# open (my $fh, ">", ".git/watchman-output.out");
|
||||
# binmode $fh, ":utf8";
|
||||
# print $fh "$clockid\n@files\n";
|
||||
# close $fh;
|
||||
|
||||
binmode STDOUT, ":utf8";
|
||||
print $clockid;
|
||||
print "\0";
|
||||
local $, = "\0";
|
||||
print @files;
|
||||
}
|
||||
|
||||
sub watchman_clock {
|
||||
my $response = qx/watchman clock "$git_work_tree"/;
|
||||
die "Failed to get clock id on '$git_work_tree'.\n" .
|
||||
"Falling back to scanning...\n" if $? != 0;
|
||||
|
||||
return $json_pkg->new->utf8->decode($response);
|
||||
}
|
||||
|
||||
sub watchman_query {
|
||||
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
|
||||
or die "open2() failed: $!\n" .
|
||||
"Falling back to scanning...\n";
|
||||
|
||||
# In the query expression below we're asking for names of files that
|
||||
# changed since $last_update_token but not from the .git folder.
|
||||
#
|
||||
# To accomplish this, we're using the "since" generator to use the
|
||||
# recency index to select candidate nodes and "fields" to limit the
|
||||
# output to file names only. Then we're using the "expression" term to
|
||||
# further constrain the results.
|
||||
my $last_update_line = "";
|
||||
if (substr($last_update_token, 0, 1) eq "c") {
|
||||
$last_update_token = "\"$last_update_token\"";
|
||||
$last_update_line = qq[\n"since": $last_update_token,];
|
||||
}
|
||||
my $query = <<" END";
|
||||
["query", "$git_work_tree", {$last_update_line
|
||||
"fields": ["name"],
|
||||
"expression": ["not", ["dirname", ".git"]]
|
||||
}]
|
||||
END
|
||||
|
||||
# Uncomment for debugging the watchman query
|
||||
# open (my $fh, ">", ".git/watchman-query.json");
|
||||
# print $fh $query;
|
||||
# close $fh;
|
||||
|
||||
print CHLD_IN $query;
|
||||
close CHLD_IN;
|
||||
my $response = do {local $/; <CHLD_OUT>};
|
||||
|
||||
# Uncomment for debugging the watch response
|
||||
# open ($fh, ">", ".git/watchman-response.json");
|
||||
# print $fh $response;
|
||||
# close $fh;
|
||||
|
||||
die "Watchman: command returned no output.\n" .
|
||||
"Falling back to scanning...\n" if $response eq "";
|
||||
die "Watchman: command returned invalid output: $response\n" .
|
||||
"Falling back to scanning...\n" unless $response =~ /^\{/;
|
||||
|
||||
return $json_pkg->new->utf8->decode($response);
|
||||
}
|
||||
|
||||
sub is_work_tree_watched {
|
||||
my ($output) = @_;
|
||||
my $error = $output->{error};
|
||||
if ($error and $error =~ m/unable to resolve root .* directory (.*) is not watched/) {
|
||||
my $response = qx/watchman watch "$git_work_tree"/;
|
||||
die "Failed to make watchman watch '$git_work_tree'.\n" .
|
||||
"Falling back to scanning...\n" if $? != 0;
|
||||
$output = $json_pkg->new->utf8->decode($response);
|
||||
$error = $output->{error};
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
# Uncomment for debugging watchman output
|
||||
# open (my $fh, ">", ".git/watchman-output.out");
|
||||
# close $fh;
|
||||
|
||||
# Watchman will always return all files on the first query so
|
||||
# return the fast "everything is dirty" flag to git and do the
|
||||
# Watchman query just to get it over with now so we won't pay
|
||||
# the cost in git to look up each individual file.
|
||||
my $o = watchman_clock();
|
||||
$error = $o->{error};
|
||||
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
output_result($o->{clock}, ("/"));
|
||||
return 0;
|
||||
}
|
||||
|
||||
die "Watchman: $error.\n" .
|
||||
"Falling back to scanning...\n" if $error;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
sub get_working_dir {
|
||||
my $working_dir;
|
||||
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
|
||||
$working_dir = Win32::GetCwd();
|
||||
$working_dir =~ tr/\\/\//;
|
||||
} else {
|
||||
require Cwd;
|
||||
$working_dir = Cwd::cwd();
|
||||
}
|
||||
|
||||
return $working_dir;
|
||||
}
|
||||
8
uartscope-git/uartscope/hooks/post-update.sample
Executable file
8
uartscope-git/uartscope/hooks/post-update.sample
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to prepare a packed repository for use over
|
||||
# dumb transports.
|
||||
#
|
||||
# To enable this hook, rename this file to "post-update".
|
||||
|
||||
exec git update-server-info
|
||||
14
uartscope-git/uartscope/hooks/pre-applypatch.sample
Executable file
14
uartscope-git/uartscope/hooks/pre-applypatch.sample
Executable file
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to verify what is about to be committed
|
||||
# by applypatch from an e-mail message.
|
||||
#
|
||||
# The hook should exit with non-zero status after issuing an
|
||||
# appropriate message if it wants to stop the commit.
|
||||
#
|
||||
# To enable this hook, rename this file to "pre-applypatch".
|
||||
|
||||
. git-sh-setup
|
||||
precommit="$(git rev-parse --git-path hooks/pre-commit)"
|
||||
test -x "$precommit" && exec "$precommit" ${1+"$@"}
|
||||
:
|
||||
49
uartscope-git/uartscope/hooks/pre-commit.sample
Executable file
49
uartscope-git/uartscope/hooks/pre-commit.sample
Executable file
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to verify what is about to be committed.
|
||||
# Called by "git commit" with no arguments. The hook should
|
||||
# exit with non-zero status after issuing an appropriate message if
|
||||
# it wants to stop the commit.
|
||||
#
|
||||
# To enable this hook, rename this file to "pre-commit".
|
||||
|
||||
if git rev-parse --verify HEAD >/dev/null 2>&1
|
||||
then
|
||||
against=HEAD
|
||||
else
|
||||
# Initial commit: diff against an empty tree object
|
||||
against=$(git hash-object -t tree /dev/null)
|
||||
fi
|
||||
|
||||
# If you want to allow non-ASCII filenames set this variable to true.
|
||||
allownonascii=$(git config --type=bool hooks.allownonascii)
|
||||
|
||||
# Redirect output to stderr.
|
||||
exec 1>&2
|
||||
|
||||
# Cross platform projects tend to avoid non-ASCII filenames; prevent
|
||||
# them from being added to the repository. We exploit the fact that the
|
||||
# printable range starts at the space character and ends with tilde.
|
||||
if [ "$allownonascii" != "true" ] &&
|
||||
# Note that the use of brackets around a tr range is ok here, (it's
|
||||
# even required, for portability to Solaris 10's /usr/bin/tr), since
|
||||
# the square bracket bytes happen to fall in the designated range.
|
||||
test $(git diff-index --cached --name-only --diff-filter=A -z $against |
|
||||
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
|
||||
then
|
||||
cat <<\EOF
|
||||
Error: Attempt to add a non-ASCII file name.
|
||||
|
||||
This can cause problems if you want to work with people on other platforms.
|
||||
|
||||
To be portable it is advisable to rename the file.
|
||||
|
||||
If you know what you are doing you can disable this check using:
|
||||
|
||||
git config hooks.allownonascii true
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# If there are whitespace errors, print the offending file names and fail.
|
||||
exec git diff-index --check --cached $against --
|
||||
13
uartscope-git/uartscope/hooks/pre-merge-commit.sample
Executable file
13
uartscope-git/uartscope/hooks/pre-merge-commit.sample
Executable file
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to verify what is about to be committed.
|
||||
# Called by "git merge" with no arguments. The hook should
|
||||
# exit with non-zero status after issuing an appropriate message to
|
||||
# stderr if it wants to stop the merge commit.
|
||||
#
|
||||
# To enable this hook, rename this file to "pre-merge-commit".
|
||||
|
||||
. git-sh-setup
|
||||
test -x "$GIT_DIR/hooks/pre-commit" &&
|
||||
exec "$GIT_DIR/hooks/pre-commit"
|
||||
:
|
||||
53
uartscope-git/uartscope/hooks/pre-push.sample
Executable file
53
uartscope-git/uartscope/hooks/pre-push.sample
Executable file
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
|
||||
# An example hook script to verify what is about to be pushed. Called by "git
|
||||
# push" after it has checked the remote status, but before anything has been
|
||||
# pushed. If this script exits with a non-zero status nothing will be pushed.
|
||||
#
|
||||
# This hook is called with the following parameters:
|
||||
#
|
||||
# $1 -- Name of the remote to which the push is being done
|
||||
# $2 -- URL to which the push is being done
|
||||
#
|
||||
# If pushing without using a named remote those arguments will be equal.
|
||||
#
|
||||
# Information about the commits which are being pushed is supplied as lines to
|
||||
# the standard input in the form:
|
||||
#
|
||||
# <local ref> <local oid> <remote ref> <remote oid>
|
||||
#
|
||||
# This sample shows how to prevent push of commits where the log message starts
|
||||
# with "WIP" (work in progress).
|
||||
|
||||
remote="$1"
|
||||
url="$2"
|
||||
|
||||
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
|
||||
|
||||
while read local_ref local_oid remote_ref remote_oid
|
||||
do
|
||||
if test "$local_oid" = "$zero"
|
||||
then
|
||||
# Handle delete
|
||||
:
|
||||
else
|
||||
if test "$remote_oid" = "$zero"
|
||||
then
|
||||
# New branch, examine all commits
|
||||
range="$local_oid"
|
||||
else
|
||||
# Update to existing branch, examine new commits
|
||||
range="$remote_oid..$local_oid"
|
||||
fi
|
||||
|
||||
# Check for WIP commit
|
||||
commit=$(git rev-list -n 1 --grep '^WIP' "$range")
|
||||
if test -n "$commit"
|
||||
then
|
||||
echo >&2 "Found WIP commit in $local_ref, not pushing"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
exit 0
|
||||
169
uartscope-git/uartscope/hooks/pre-rebase.sample
Executable file
169
uartscope-git/uartscope/hooks/pre-rebase.sample
Executable file
@@ -0,0 +1,169 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# Copyright (c) 2006, 2008 Junio C Hamano
|
||||
#
|
||||
# The "pre-rebase" hook is run just before "git rebase" starts doing
|
||||
# its job, and can prevent the command from running by exiting with
|
||||
# non-zero status.
|
||||
#
|
||||
# The hook is called with the following parameters:
|
||||
#
|
||||
# $1 -- the upstream the series was forked from.
|
||||
# $2 -- the branch being rebased (or empty when rebasing the current branch).
|
||||
#
|
||||
# This sample shows how to prevent topic branches that are already
|
||||
# merged to 'next' branch from getting rebased, because allowing it
|
||||
# would result in rebasing already published history.
|
||||
|
||||
publish=next
|
||||
basebranch="$1"
|
||||
if test "$#" = 2
|
||||
then
|
||||
topic="refs/heads/$2"
|
||||
else
|
||||
topic=`git symbolic-ref HEAD` ||
|
||||
exit 0 ;# we do not interrupt rebasing detached HEAD
|
||||
fi
|
||||
|
||||
case "$topic" in
|
||||
refs/heads/??/*)
|
||||
;;
|
||||
*)
|
||||
exit 0 ;# we do not interrupt others.
|
||||
;;
|
||||
esac
|
||||
|
||||
# Now we are dealing with a topic branch being rebased
|
||||
# on top of master. Is it OK to rebase it?
|
||||
|
||||
# Does the topic really exist?
|
||||
git show-ref -q "$topic" || {
|
||||
echo >&2 "No such branch $topic"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Is topic fully merged to master?
|
||||
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
|
||||
if test -z "$not_in_master"
|
||||
then
|
||||
echo >&2 "$topic is fully merged to master; better remove it."
|
||||
exit 1 ;# we could allow it, but there is no point.
|
||||
fi
|
||||
|
||||
# Is topic ever merged to next? If so you should not be rebasing it.
|
||||
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
|
||||
only_next_2=`git rev-list ^master ${publish} | sort`
|
||||
if test "$only_next_1" = "$only_next_2"
|
||||
then
|
||||
not_in_topic=`git rev-list "^$topic" master`
|
||||
if test -z "$not_in_topic"
|
||||
then
|
||||
echo >&2 "$topic is already up to date with master"
|
||||
exit 1 ;# we could allow it, but there is no point.
|
||||
else
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
|
||||
/usr/bin/perl -e '
|
||||
my $topic = $ARGV[0];
|
||||
my $msg = "* $topic has commits already merged to public branch:\n";
|
||||
my (%not_in_next) = map {
|
||||
/^([0-9a-f]+) /;
|
||||
($1 => 1);
|
||||
} split(/\n/, $ARGV[1]);
|
||||
for my $elem (map {
|
||||
/^([0-9a-f]+) (.*)$/;
|
||||
[$1 => $2];
|
||||
} split(/\n/, $ARGV[2])) {
|
||||
if (!exists $not_in_next{$elem->[0]}) {
|
||||
if ($msg) {
|
||||
print STDERR $msg;
|
||||
undef $msg;
|
||||
}
|
||||
print STDERR " $elem->[1]\n";
|
||||
}
|
||||
}
|
||||
' "$topic" "$not_in_next" "$not_in_master"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
<<\DOC_END
|
||||
|
||||
This sample hook safeguards topic branches that have been
|
||||
published from being rewound.
|
||||
|
||||
The workflow assumed here is:
|
||||
|
||||
* Once a topic branch forks from "master", "master" is never
|
||||
merged into it again (either directly or indirectly).
|
||||
|
||||
* Once a topic branch is fully cooked and merged into "master",
|
||||
it is deleted. If you need to build on top of it to correct
|
||||
earlier mistakes, a new topic branch is created by forking at
|
||||
the tip of the "master". This is not strictly necessary, but
|
||||
it makes it easier to keep your history simple.
|
||||
|
||||
* Whenever you need to test or publish your changes to topic
|
||||
branches, merge them into "next" branch.
|
||||
|
||||
The script, being an example, hardcodes the publish branch name
|
||||
to be "next", but it is trivial to make it configurable via
|
||||
$GIT_DIR/config mechanism.
|
||||
|
||||
With this workflow, you would want to know:
|
||||
|
||||
(1) ... if a topic branch has ever been merged to "next". Young
|
||||
topic branches can have stupid mistakes you would rather
|
||||
clean up before publishing, and things that have not been
|
||||
merged into other branches can be easily rebased without
|
||||
affecting other people. But once it is published, you would
|
||||
not want to rewind it.
|
||||
|
||||
(2) ... if a topic branch has been fully merged to "master".
|
||||
Then you can delete it. More importantly, you should not
|
||||
build on top of it -- other people may already want to
|
||||
change things related to the topic as patches against your
|
||||
"master", so if you need further changes, it is better to
|
||||
fork the topic (perhaps with the same name) afresh from the
|
||||
tip of "master".
|
||||
|
||||
Let's look at this example:
|
||||
|
||||
o---o---o---o---o---o---o---o---o---o "next"
|
||||
/ / / /
|
||||
/ a---a---b A / /
|
||||
/ / / /
|
||||
/ / c---c---c---c B /
|
||||
/ / / \ /
|
||||
/ / / b---b C \ /
|
||||
/ / / / \ /
|
||||
---o---o---o---o---o---o---o---o---o---o---o "master"
|
||||
|
||||
|
||||
A, B and C are topic branches.
|
||||
|
||||
* A has one fix since it was merged up to "next".
|
||||
|
||||
* B has finished. It has been fully merged up to "master" and "next",
|
||||
and is ready to be deleted.
|
||||
|
||||
* C has not merged to "next" at all.
|
||||
|
||||
We would want to allow C to be rebased, refuse A, and encourage
|
||||
B to be deleted.
|
||||
|
||||
To compute (1):
|
||||
|
||||
git rev-list ^master ^topic next
|
||||
git rev-list ^master next
|
||||
|
||||
if these match, topic has not merged in next at all.
|
||||
|
||||
To compute (2):
|
||||
|
||||
git rev-list master..topic
|
||||
|
||||
if this is empty, it is fully merged to "master".
|
||||
|
||||
DOC_END
|
||||
24
uartscope-git/uartscope/hooks/pre-receive.sample
Executable file
24
uartscope-git/uartscope/hooks/pre-receive.sample
Executable file
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to make use of push options.
|
||||
# The example simply echoes all push options that start with 'echoback='
|
||||
# and rejects all pushes when the "reject" push option is used.
|
||||
#
|
||||
# To enable this hook, rename this file to "pre-receive".
|
||||
|
||||
if test -n "$GIT_PUSH_OPTION_COUNT"
|
||||
then
|
||||
i=0
|
||||
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
|
||||
do
|
||||
eval "value=\$GIT_PUSH_OPTION_$i"
|
||||
case "$value" in
|
||||
echoback=*)
|
||||
echo "echo from the pre-receive-hook: ${value#*=}" >&2
|
||||
;;
|
||||
reject)
|
||||
exit 1
|
||||
esac
|
||||
i=$((i + 1))
|
||||
done
|
||||
fi
|
||||
42
uartscope-git/uartscope/hooks/prepare-commit-msg.sample
Executable file
42
uartscope-git/uartscope/hooks/prepare-commit-msg.sample
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to prepare the commit log message.
|
||||
# Called by "git commit" with the name of the file that has the
|
||||
# commit message, followed by the description of the commit
|
||||
# message's source. The hook's purpose is to edit the commit
|
||||
# message file. If the hook fails with a non-zero status,
|
||||
# the commit is aborted.
|
||||
#
|
||||
# To enable this hook, rename this file to "prepare-commit-msg".
|
||||
|
||||
# This hook includes three examples. The first one removes the
|
||||
# "# Please enter the commit message..." help message.
|
||||
#
|
||||
# The second includes the output of "git diff --name-status -r"
|
||||
# into the message, just before the "git status" output. It is
|
||||
# commented because it doesn't cope with --amend or with squashed
|
||||
# commits.
|
||||
#
|
||||
# The third example adds a Signed-off-by line to the message, that can
|
||||
# still be edited. This is rarely a good idea.
|
||||
|
||||
COMMIT_MSG_FILE=$1
|
||||
COMMIT_SOURCE=$2
|
||||
SHA1=$3
|
||||
|
||||
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
|
||||
|
||||
# case "$COMMIT_SOURCE,$SHA1" in
|
||||
# ,|template,)
|
||||
# /usr/bin/perl -i.bak -pe '
|
||||
# print "\n" . `git diff --cached --name-status -r`
|
||||
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
|
||||
# *) ;;
|
||||
# esac
|
||||
|
||||
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
|
||||
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
|
||||
# if test -z "$COMMIT_SOURCE"
|
||||
# then
|
||||
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
|
||||
# fi
|
||||
78
uartscope-git/uartscope/hooks/push-to-checkout.sample
Executable file
78
uartscope-git/uartscope/hooks/push-to-checkout.sample
Executable file
@@ -0,0 +1,78 @@
|
||||
#!/bin/sh
|
||||
|
||||
# An example hook script to update a checked-out tree on a git push.
|
||||
#
|
||||
# This hook is invoked by git-receive-pack(1) when it reacts to git
|
||||
# push and updates reference(s) in its repository, and when the push
|
||||
# tries to update the branch that is currently checked out and the
|
||||
# receive.denyCurrentBranch configuration variable is set to
|
||||
# updateInstead.
|
||||
#
|
||||
# By default, such a push is refused if the working tree and the index
|
||||
# of the remote repository has any difference from the currently
|
||||
# checked out commit; when both the working tree and the index match
|
||||
# the current commit, they are updated to match the newly pushed tip
|
||||
# of the branch. This hook is to be used to override the default
|
||||
# behaviour; however the code below reimplements the default behaviour
|
||||
# as a starting point for convenient modification.
|
||||
#
|
||||
# The hook receives the commit with which the tip of the current
|
||||
# branch is going to be updated:
|
||||
commit=$1
|
||||
|
||||
# It can exit with a non-zero status to refuse the push (when it does
|
||||
# so, it must not modify the index or the working tree).
|
||||
die () {
|
||||
echo >&2 "$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Or it can make any necessary changes to the working tree and to the
|
||||
# index to bring them to the desired state when the tip of the current
|
||||
# branch is updated to the new commit, and exit with a zero status.
|
||||
#
|
||||
# For example, the hook can simply run git read-tree -u -m HEAD "$1"
|
||||
# in order to emulate git fetch that is run in the reverse direction
|
||||
# with git push, as the two-tree form of git read-tree -u -m is
|
||||
# essentially the same as git switch or git checkout that switches
|
||||
# branches while keeping the local changes in the working tree that do
|
||||
# not interfere with the difference between the branches.
|
||||
|
||||
# The below is a more-or-less exact translation to shell of the C code
|
||||
# for the default behaviour for git's push-to-checkout hook defined in
|
||||
# the push_to_deploy() function in builtin/receive-pack.c.
|
||||
#
|
||||
# Note that the hook will be executed from the repository directory,
|
||||
# not from the working tree, so if you want to perform operations on
|
||||
# the working tree, you will have to adapt your code accordingly, e.g.
|
||||
# by adding "cd .." or using relative paths.
|
||||
|
||||
if ! git update-index -q --ignore-submodules --refresh
|
||||
then
|
||||
die "Up-to-date check failed"
|
||||
fi
|
||||
|
||||
if ! git diff-files --quiet --ignore-submodules --
|
||||
then
|
||||
die "Working directory has unstaged changes"
|
||||
fi
|
||||
|
||||
# This is a rough translation of:
|
||||
#
|
||||
# head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX
|
||||
if git cat-file -e HEAD 2>/dev/null
|
||||
then
|
||||
head=HEAD
|
||||
else
|
||||
head=$(git hash-object -t tree --stdin </dev/null)
|
||||
fi
|
||||
|
||||
if ! git diff-index --quiet --cached --ignore-submodules $head --
|
||||
then
|
||||
die "Working directory has staged changes"
|
||||
fi
|
||||
|
||||
if ! git read-tree -u -m "$commit"
|
||||
then
|
||||
die "Could not update working tree to new HEAD"
|
||||
fi
|
||||
77
uartscope-git/uartscope/hooks/sendemail-validate.sample
Executable file
77
uartscope-git/uartscope/hooks/sendemail-validate.sample
Executable file
@@ -0,0 +1,77 @@
|
||||
#!/bin/sh
|
||||
|
||||
# An example hook script to validate a patch (and/or patch series) before
|
||||
# sending it via email.
|
||||
#
|
||||
# The hook should exit with non-zero status after issuing an appropriate
|
||||
# message if it wants to prevent the email(s) from being sent.
|
||||
#
|
||||
# To enable this hook, rename this file to "sendemail-validate".
|
||||
#
|
||||
# By default, it will only check that the patch(es) can be applied on top of
|
||||
# the default upstream branch without conflicts in a secondary worktree. After
|
||||
# validation (successful or not) of the last patch of a series, the worktree
|
||||
# will be deleted.
|
||||
#
|
||||
# The following config variables can be set to change the default remote and
|
||||
# remote ref that are used to apply the patches against:
|
||||
#
|
||||
# sendemail.validateRemote (default: origin)
|
||||
# sendemail.validateRemoteRef (default: HEAD)
|
||||
#
|
||||
# Replace the TODO placeholders with appropriate checks according to your
|
||||
# needs.
|
||||
|
||||
validate_cover_letter () {
|
||||
file="$1"
|
||||
# TODO: Replace with appropriate checks (e.g. spell checking).
|
||||
true
|
||||
}
|
||||
|
||||
validate_patch () {
|
||||
file="$1"
|
||||
# Ensure that the patch applies without conflicts.
|
||||
git am -3 "$file" || return
|
||||
# TODO: Replace with appropriate checks for this patch
|
||||
# (e.g. checkpatch.pl).
|
||||
true
|
||||
}
|
||||
|
||||
validate_series () {
|
||||
# TODO: Replace with appropriate checks for the whole series
|
||||
# (e.g. quick build, coding style checks, etc.).
|
||||
true
|
||||
}
|
||||
|
||||
# main -------------------------------------------------------------------------
|
||||
|
||||
if test "$GIT_SENDEMAIL_FILE_COUNTER" = 1
|
||||
then
|
||||
remote=$(git config --default origin --get sendemail.validateRemote) &&
|
||||
ref=$(git config --default HEAD --get sendemail.validateRemoteRef) &&
|
||||
worktree=$(mktemp --tmpdir -d sendemail-validate.XXXXXXX) &&
|
||||
git worktree add -fd --checkout "$worktree" "refs/remotes/$remote/$ref" &&
|
||||
git config --replace-all sendemail.validateWorktree "$worktree"
|
||||
else
|
||||
worktree=$(git config --get sendemail.validateWorktree)
|
||||
fi || {
|
||||
echo "sendemail-validate: error: failed to prepare worktree" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
unset GIT_DIR GIT_WORK_TREE
|
||||
cd "$worktree" &&
|
||||
|
||||
if grep -q "^diff --git " "$1"
|
||||
then
|
||||
validate_patch "$1"
|
||||
else
|
||||
validate_cover_letter "$1"
|
||||
fi &&
|
||||
|
||||
if test "$GIT_SENDEMAIL_FILE_COUNTER" = "$GIT_SENDEMAIL_FILE_TOTAL"
|
||||
then
|
||||
git config --unset-all sendemail.validateWorktree &&
|
||||
trap 'git worktree remove -ff "$worktree"' EXIT &&
|
||||
validate_series
|
||||
fi
|
||||
128
uartscope-git/uartscope/hooks/update.sample
Executable file
128
uartscope-git/uartscope/hooks/update.sample
Executable file
@@ -0,0 +1,128 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# An example hook script to block unannotated tags from entering.
|
||||
# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
|
||||
#
|
||||
# To enable this hook, rename this file to "update".
|
||||
#
|
||||
# Config
|
||||
# ------
|
||||
# hooks.allowunannotated
|
||||
# This boolean sets whether unannotated tags will be allowed into the
|
||||
# repository. By default they won't be.
|
||||
# hooks.allowdeletetag
|
||||
# This boolean sets whether deleting tags will be allowed in the
|
||||
# repository. By default they won't be.
|
||||
# hooks.allowmodifytag
|
||||
# This boolean sets whether a tag may be modified after creation. By default
|
||||
# it won't be.
|
||||
# hooks.allowdeletebranch
|
||||
# This boolean sets whether deleting branches will be allowed in the
|
||||
# repository. By default they won't be.
|
||||
# hooks.denycreatebranch
|
||||
# This boolean sets whether remotely creating branches will be denied
|
||||
# in the repository. By default this is allowed.
|
||||
#
|
||||
|
||||
# --- Command line
|
||||
refname="$1"
|
||||
oldrev="$2"
|
||||
newrev="$3"
|
||||
|
||||
# --- Safety check
|
||||
if [ -z "$GIT_DIR" ]; then
|
||||
echo "Don't run this script from the command line." >&2
|
||||
echo " (if you want, you could supply GIT_DIR then run" >&2
|
||||
echo " $0 <ref> <oldrev> <newrev>)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
|
||||
echo "usage: $0 <ref> <oldrev> <newrev>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Config
|
||||
allowunannotated=$(git config --type=bool hooks.allowunannotated)
|
||||
allowdeletebranch=$(git config --type=bool hooks.allowdeletebranch)
|
||||
denycreatebranch=$(git config --type=bool hooks.denycreatebranch)
|
||||
allowdeletetag=$(git config --type=bool hooks.allowdeletetag)
|
||||
allowmodifytag=$(git config --type=bool hooks.allowmodifytag)
|
||||
|
||||
# check for no description
|
||||
projectdesc=$(sed -e '1q' "$GIT_DIR/description")
|
||||
case "$projectdesc" in
|
||||
"Unnamed repository"* | "")
|
||||
echo "*** Project description file hasn't been set" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# --- Check types
|
||||
# if $newrev is 0000...0000, it's a commit to delete a ref.
|
||||
zero=$(git hash-object --stdin </dev/null | tr '[0-9a-f]' '0')
|
||||
if [ "$newrev" = "$zero" ]; then
|
||||
newrev_type=delete
|
||||
else
|
||||
newrev_type=$(git cat-file -t $newrev)
|
||||
fi
|
||||
|
||||
case "$refname","$newrev_type" in
|
||||
refs/tags/*,commit)
|
||||
# un-annotated tag
|
||||
short_refname=${refname##refs/tags/}
|
||||
if [ "$allowunannotated" != "true" ]; then
|
||||
echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
|
||||
echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
refs/tags/*,delete)
|
||||
# delete tag
|
||||
if [ "$allowdeletetag" != "true" ]; then
|
||||
echo "*** Deleting a tag is not allowed in this repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
refs/tags/*,tag)
|
||||
# annotated tag
|
||||
if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
|
||||
then
|
||||
echo "*** Tag '$refname' already exists." >&2
|
||||
echo "*** Modifying a tag is not allowed in this repository." >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
refs/heads/*,commit)
|
||||
# branch
|
||||
if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
|
||||
echo "*** Creating a branch is not allowed in this repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
refs/heads/*,delete)
|
||||
# delete branch
|
||||
if [ "$allowdeletebranch" != "true" ]; then
|
||||
echo "*** Deleting a branch is not allowed in this repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
refs/remotes/*,commit)
|
||||
# tracking branch
|
||||
;;
|
||||
refs/remotes/*,delete)
|
||||
# delete tracking branch
|
||||
if [ "$allowdeletebranch" != "true" ]; then
|
||||
echo "*** Deleting a tracking branch is not allowed in this repository" >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
# Anything else (is there anything else?)
|
||||
echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# --- Finished
|
||||
exit 0
|
||||
1
uartscope-git/uartscope/info/attributes
Normal file
1
uartscope-git/uartscope/info/attributes
Normal file
@@ -0,0 +1 @@
|
||||
* -export-subst -export-ignore
|
||||
6
uartscope-git/uartscope/info/exclude
Normal file
6
uartscope-git/uartscope/info/exclude
Normal file
@@ -0,0 +1,6 @@
|
||||
# git ls-files --others --exclude-from=.git/info/exclude
|
||||
# Lines that start with '#' are comments.
|
||||
# For a project mostly in C, the following would be a good set of
|
||||
# exclude patterns (uncomment them if you want to use them):
|
||||
# *.[oa]
|
||||
# *~
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
2
uartscope-git/uartscope/packed-refs
Normal file
2
uartscope-git/uartscope/packed-refs
Normal file
@@ -0,0 +1,2 @@
|
||||
# pack-refs with: peeled fully-peeled sorted
|
||||
cc102c93eb17f7b910d8e74c3505f198bed77f10 refs/heads/main
|
||||
1
uartscope-git/uartscope/refs/tags/v1.0.0
Normal file
1
uartscope-git/uartscope/refs/tags/v1.0.0
Normal file
@@ -0,0 +1 @@
|
||||
cc102c93eb17f7b910d8e74c3505f198bed77f10
|
||||
@@ -2,7 +2,7 @@
|
||||
Name=UARTScope
|
||||
Comment=UART Serial Monitor
|
||||
Exec=uartscope
|
||||
Icon=utilities-terminal
|
||||
Icon=uartscope
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Categories=Development;Utility;
|
||||
|
||||
Reference in New Issue
Block a user