Repository: hacknus/serial-monitor-rust
Branch: main
Commit: b204f6cafbeb
Files: 24
Total size: 222.8 KB
Directory structure:
gitextract_vwrm_txo/
├── .cargo/
│ └── config.toml
├── .github/
│ └── workflows/
│ ├── changelog.yml
│ ├── deployment.yml
│ └── rust.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
├── icons/
│ └── icon.xd
├── ios-cargo
├── src/
│ ├── color_picker.rs
│ ├── custom_highlighter.rs
│ ├── data.rs
│ ├── gui.rs
│ ├── io.rs
│ ├── main.rs
│ ├── serial.rs
│ ├── settings_window.rs
│ ├── toggle.rs
│ └── update.rs
└── wix/
├── License.rtf
└── main.wxs
================================================
FILE CONTENTS
================================================
================================================
FILE: .cargo/config.toml
================================================
[target.x86_64-apple-darwin]
rustflags = ["-C", "link-arg=-mmacosx-version-min=10.8"]
[env]
MACOSX_DEPLOYMENT_TARGET = "10.12"
================================================
FILE: .github/workflows/changelog.yml
================================================
name: Check Changelog
on:
pull_request:
types: [ assigned, opened, synchronize, reopened, labeled, unlabeled ]
branches:
- main
jobs:
Check-Changelog:
name: Check Changelog Action
runs-on: ubuntu-latest
steps:
- uses: tarides/changelog-check-action@v2
with:
changelog: CHANGELOG.md
================================================
FILE: .github/workflows/deployment.yml
================================================
name: Deployment
on:
release:
types:
- created
env:
CARGO_TERM_COLOR: always
jobs:
build:
permissions: write-all
strategy:
matrix:
include:
- os: ubuntu-22.04
target: x86_64-unknown-linux-gnu
- os: ubuntu-22.04
target: aarch64-unknown-linux-gnu
- os: macos-15-intel
target: x86_64-apple-darwin
- os: macos-14
target: aarch64-apple-darwin
- os: windows-2022
target: x86_64-pc-windows-msvc
- os: windows-2022
target: aarch64-pc-windows-msvc
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Dependencies (Linux)
if: contains(matrix.os, 'ubuntu')
run: sudo apt-get update && sudo apt-get install -y libclang-dev libgtk-3-dev libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev libxkbcommon-dev libssl-dev libudev-dev && cargo install cargo-bundle
- name: Install Dependencies (macOS)
if: contains(matrix.os, 'macos')
run: cargo install cargo-bundle
- name: Install Dependencies (Windows)
if: contains(matrix.os, 'windows')
run: cargo install --force cargo-wix
- name: Set CARGO_FEATURES environment variable (Windows)
if: contains(matrix.os, 'windows')
run: |
echo "CARGO_FEATURES=self_update" >> $env:GITHUB_ENV
- name: Build
run: cargo build --features self_update --release
- name: Build .deb Package (Linux)
if: contains(matrix.os, 'ubuntu')
run: cargo bundle --features self_update --release
- name: Build .app Package (macOS)
if: contains(matrix.os, 'macos')
run: cargo bundle --features self_update --release
- name: Build .msi Package (Windows)
if: contains(matrix.os, 'windows')
run: cargo wix
# Compress for Linux Binary
- name: Compress Output (Linux Binary)
if: contains(matrix.os, 'ubuntu')
run: |
cd target/release
zip -r serial-monitor-${{ matrix.target }}.zip serial-monitor-rust
mv serial-monitor-${{ matrix.target }}.zip $GITHUB_WORKSPACE/
# Compress for Linux .deb Package
- name: Compress Output (Linux .deb)
if: contains(matrix.os, 'ubuntu')
run: |
cd target/release/bundle/deb
zip serial-monitor-${{ matrix.target }}.deb.zip *.deb
mv serial-monitor-${{ matrix.target }}.deb.zip $GITHUB_WORKSPACE/
# Compress for macOS (.app Bundle)
- name: Compress Output (macOS)
if: contains(matrix.os, 'macos')
run: |
cd target/release/bundle/osx
zip -r serial-monitor-${{ matrix.target }}.app.zip Serial\ Monitor.app
mv serial-monitor-${{ matrix.target }}.app.zip $GITHUB_WORKSPACE/
# Compress for Windows (.exe)
- name: Compress Output (Windows .exe)
if: contains(matrix.os, 'windows')
run: |
Compress-Archive -Path target/release/serial-monitor-rust.exe -DestinationPath serial-monitor-${{ matrix.target }}.exe.zip
Move-Item -Path serial-monitor-${{ matrix.target }}.exe.zip -Destination $env:GITHUB_WORKSPACE
# Compress for Windows (.msi)
- name: Compress Output (Windows .msi)
if: contains(matrix.os, 'windows')
run: |
cd target/wix
Compress-Archive -Path *.msi -DestinationPath serial-monitor-${{ matrix.target }}.msi.zip
Move-Item -Path serial-monitor-${{ matrix.target }}.msi.zip -Destination $env:GITHUB_WORKSPACE
- name: Upload .deb and executable for Linux (Ubuntu)
if: contains(matrix.os, 'ubuntu')
uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: serial-monitor-${{ matrix.target }}.deb.zip
asset_name: serial-monitor-${{ matrix.target }}.deb.zip
asset_content_type: application/zip
- name: Upload .zip for Linux (Ubuntu executable)
if: contains(matrix.os, 'ubuntu')
uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: serial-monitor-${{ matrix.target }}.zip
asset_name: serial-monitor-${{ matrix.target }}.zip
asset_content_type: application/zip
- name: Upload .exe for Windows
if: contains(matrix.os, 'windows')
uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: serial-monitor-${{ matrix.target }}.exe.zip
asset_name: serial-monitor-${{ matrix.target }}.exe.zip
asset_content_type: application/zip
- name: Upload .msi for Windows
if: contains(matrix.os, 'windows')
uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: serial-monitor-${{ matrix.target }}.msi.zip
asset_name: serial-monitor-${{ matrix.target }}.msi.zip
asset_content_type: application/zip
- name: Upload .zip for macOS
if: contains(matrix.os, 'macos')
uses: actions/upload-release-asset@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ github.event.release.upload_url }}
asset_path: serial-monitor-${{ matrix.target }}.app.zip
asset_name: serial-monitor-${{ matrix.target }}.app.zip
asset_content_type: application/zip
================================================
FILE: .github/workflows/rust.yml
================================================
name: Rust
on:
push:
branches: [ "main" ]
paths:
- "**/*.rs"
- "**/Cargo.toml"
pull_request:
branches: [ "main" ]
paths:
- "**/*.rs"
- "**/Cargo.toml"
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install libraries
run: sudo apt-get update && sudo apt-get install -y libclang-dev libgtk-3-dev libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev libxkbcommon-dev libssl-dev && sudo apt-get install libudev-dev && cargo install cargo-bundle
- name: Build
run: cargo build --all --all-features
- name: Cargo check
run: cargo check --all --all-features
- name: Rustfmt
run: cargo fmt --all -- --check
- name: Clippy
run: cargo clippy --all --all-targets --all-features
- name: Test
run: cargo test --all --all-features
================================================
FILE: .gitignore
================================================
/target
================================================
FILE: CHANGELOG.md
================================================
# Serial Monitor changelog
All notable changes to the `Serial Monitor` crate will be documented in this file.
## Unreleased 0.4.x
* ...
## 0.4.0 - 3.4.2026
* update to `egui 0.34`
## 0.3.7 - 28.11.2025
* update to `egui 0.33`
## 0.3.6 - 29.9.2025
* Switched to `crossbeam-channel` for more efficient channel routing
* removed many `.clone()` calls to reduce CPU load
* Fixed sample rate / disconnect issue
* Releases are now linked to libssl 3.4.1 on linux (built on Ubuntu 22.04)
* allow to plot only every n-th point (max points is 5000, if dataset is larger, it will reduce it by showing only every
2nd point. if it is larger than 10000 only every 3rd point etc...)
* Fixed the theme preference setting not being properly restored after restarting the application (
thanks [@Rahix](https://github.com/Rahix))
* Fixed bug where you couldn't change the color and label of columns (thanks [@Rahix](https://github.com/Rahix))
* Fixed bug where for a single column of data the graph would never show (thanks [@Rahix](https://github.com/Rahix))
* Added a commandline interface for selecting the serial port and its settings. (
thanks [@Rahix](https://github.com/Rahix))
## 0.3.4
* implement option to self-update the application
## 0.3.3
### Added:
* implement `egui-file-dialog` and the feature to open `.csv` files.
## 0.3.2
### Added:
* fixed display of only one dataset bug
## 0.3.1 - 8.12.2024
### Added:
* removed the custom implementation of `Print` and `ScrollArea` and implemented the `log` crate and `egui_logger`
* Up to 4 Sentences highlightings using regex (thanks [@simon0356](https://github.com/simon0356))
* Groups settings in the side bar by category into collapsing menu. (thanks [@simon0356](https://github.com/simon0356))
## 0.3.0 - 14.10.2024 - Automatic Reconnection
### Added:
* Color-picker for curves
* Automatically reconnect when device becomes available again (only after unplugging)
* minor bug fixes
## 0.2.0 - 09.03.2024 - New Design, Improved Performance
### Added:
* [egui-phosphor](https://github.com/amPerl/egui-phosphor) icons for certain buttons
* multiple plots support (thanks [@oeb25](https://github.com/oeb25))
* implemented keyboard shortcuts
* improved serial transfer speed (thanks [@L-Trump](https://github.com/L-Trump))
* Bug fixes (thanks [@zimward](https://github.com/zimward))
## Earlier:
* code clean up (thanks [@lonesometraveler](https://github.com/lonesometraveler))
================================================
FILE: Cargo.toml
================================================
[package]
name = "serial-monitor-rust"
version = "0.4.0"
edition = "2021"
authors = ["Linus Leo Stöckli"]
description = "Serial Monitor and Plotter written in rust."
license = "GPL-3.0"
homepage = "https://github.com/hacknus/serial-monitor-rust"
[dependencies]
csv = "1.4"
egui_plot = "0.35"
egui_extras = { version = "0.34", features = ["all_loaders"] }
egui-phosphor = { version = "0.12" }
egui-theme-switch = "0.7"
egui_logger = "0.10"
egui-file-dialog = { git = "https://github.com/hacknus/egui-file-dialog", branch = "sort_by_metadata", features = ["information_view"] }
image = { version = "0.25", default-features = false, features = ["png"] }
preferences = { version = "2.0.0" }
regex = "1"
serde = { version = "1.0", features = ["derive"] }
serialport = { version = "4.8", features = ["serde"] }
log = "0.4"
self_update = { git = "https://github.com/hacknus/self_update", features = ["archive-zip", "compression-zip-deflate"], optional = true }
tempfile = { version = "3.23", optional = true }
reqwest = { version = "0.13", default-features = false, features = ["blocking", "json", "http2"], optional = true }
semver = { version = "1.0.27", optional = true }
crossbeam-channel = "0.5.15"
gumdrop = "0.8.1"
[target.'cfg(not(target_os = "ios"))'.dependencies]
eframe = { version = "0.34", features = ["persistence", "wayland", "x11"] }
keepawake = { version = "0.6" }
# ios:
[target.'cfg(target_os = "ios")'.dependencies]
eframe = { version = "0.34", default-features = false, features = [
"accesskit",
"default_fonts",
"wgpu", # Use the wgpu rendering backend on iOS.
"persistence",
] }
[features]
self_update = ["dep:self_update", "tempfile", "reqwest", "semver"]
[build-dependencies]
regex = "1.12"
[package.metadata.bundle]
name = "Serial Monitor"
identifier = "ch.hacknus.serial_monitor"
icon = ["./icons/install.png"]
copyright = "Copyright (c) hacknus 2025. All rights reserved."
category = "Developer Tool"
short_description = "Serial Monitor and Plotter written in rust."
long_description = "Serial Monitor and Plotter written in rust. Interface with serial devices with the ability to log to a file and plot the data."
osx_minimum_system_version = "10.12"
osx_url_schemes = ["ch.hacknus.serial_monitor"]
deb_depends = ["libclang-dev", "libgtk-3-dev", "libxcb-render0-dev", "libxcb-shape0-dev", "libxcb-xfixes0-dev", "libxkbcommon-dev", "libssl-dev"]
[package.metadata.wix]
dbg-build = false
dbg-name = false
name = "Serial Monitor"
no-build = false
output = "target/wix/SerialMonitorInstaller.msi"
[profile.release]
debug = true
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# Serial Monitor
A cross-platform serial monitor and plotter written entirely in rust, the GUI is written
using [egui](https://github.com/emilk/egui).
Inspired by the serial monitor/plotter from the Arduino IDE, but both plotting and reading the traffic can be done
simultaneously.
## Installation:
### Download pre-built executables
[Binary bundles](https://github.com/hacknus/serial-monitor-rust/releases) are available for Linux, macOS and Windows.
Running the apple silicon binary (serial-monitor-aarch64-apple-darwin.app) may result to the message "Serial Monitor is
damaged and cannot be opened.", to get
around this you first need to run:
`xattr -rd com.apple.quarantine Serial\ Monitor.app`
On Linux first install the following:
```sh
sudo apt-get install libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev libxkbcommon-dev libssl-dev
```
### Compile from source
The source code can be run using `cargo run` or bundled to a platform-executable using cargo bundle.
Currently [cargo bundle](https://github.com/burtonageo/cargo-bundle) only supports linux and macOS
bundles [see github issue](https://github.com/burtonageo/cargo-bundle/issues/77).
As a work-around we can use [cargo wix](https://github.com/volks73/cargo-wix) to create a windows installer.
#### Debian & Ubuntu
```sh
sudo apt-get install libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev libxkbcommon-dev libssl-dev libudev-dev
cargo install cargo-bundle
cargo bundle
```
### Fedora Rawhide
```sh
dnf install clang clang-devel clang-tools-extra libxkbcommon-devel pkg-config openssl-devel libxcb-devel gtk3-devel atk fontconfig-devel libusbx-devel
```
#### macOS
```sh
cargo install cargo-bundle
cargo bundle
```
#### iOS
But this is probably not useful since iOS devices do not let you access serial devices because of sandboxing.
```sh
sudo xcodebuild -license
rustup target add aarch64-apple-ios
cargo install cargo-bundle
./ios-cargo ipa --ipad --release
```
#### Windows
```sh
cargo install cargo-wix
cargo wix
```
## Commandline Arguments
You can start the app with commandline arguments to automatically select a serial port and its settings:
```text
Usage: serial-monitor-rust [OPTIONS]
Positional arguments:
device Serial port device to open on startup
Optional arguments:
-b, --baudrate BAUDRATE Baudrate (default=9600)
-d, --databits DATABITS Data bits (5, 6, 7, default=8)
-f, --flow FLOW Flow conrol (hard, soft, default=none)
-s, --stopbits STOPBITS Stop bits (default=1, 2)
-p, --parity PARITY Parity (odd, even, default=none)
-F, --file FILE Load data from a file instead of a serial port
--column COLUMN-LABELS Column labels, can be specified multiple times for more columns
--color COLUMN-COLORS Column colors (hex color without #), can be specified multiple times for more columns
-h, --help
```
Example usage:
```sh
serial-monitor-rust /dev/ttyACM0 --baudrate 115200
```
You can also preconfigure the column settings. The following example configures the name and color for two columns in the incoming data:
```sh
serial-monitor-rust --column Raw --color '808080' --column Temperature --color 'ff8000' /dev/ttyACM0
```
## Features:
- [X] Plotting and printing of data simultaneously
- [X] Smart data parser, works with ", " or "," or ":" or ": "
- [X] History of the past sent commands
- [X] Low CPU Usage, lightweight
- [X] Clear history options
- [X] Data Window width (number of displayed datapoints in plot) is adjustable
- [X] Cross-platform, fully written in Rust
- [X] Ability to save text to file
- [X] Ability to save the plot
- [X] Allow to put in labels for the different data columns (instead of column 1, 2, ...)
- [X] Allow to choose Data-bits, Flow-Control, Parity and Stop-Bits for Serial Connection
- [X] Saves the configuration for the serial port after closing and reloads them automatically upon selection
- [X] Option to save raw data to file
- [X] Use keyboard shortcuts (ctrl-S to save data, ctrl-shift-S to save plot, ctrl-X to clear plot)
- [X] Automatic reconnect after device has been unplugged
- [X] Color-picker for curves
- [X] Open a CSV file and display data in plot
- [ ] Allow to select (and copy) more than just the displayed raw traffic (also implement ctrl + A)
- [ ] Smarter data parser
- [ ] make serial print selectable and show corresponding datapoint in plot
- [ ] COM-Port names on Windows (display manufacturer, name, pid or vid of device?)
- [ ] current command entered is lost when navigating through the history
- [ ] command history is currently unlimited (needs an upper limit to prevent huge memory usage)
- [ ] data history is currently unlimited (needs an upper limit to prevent huge memory usage)
- [ ] ...

Tested on:
- macOS 12 Monterey x86
- macOS 13 Ventura x86
- macOS 13 Ventura ARM
- macOS 14 Sonoma ARM
- Debian 12 (Testing) x86
- Windows 10 x86
- ...
One might have to delete the `Cargo.lock` file before compiling.
================================================
FILE: build.rs
================================================
fn main() {
println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=10.12");
}
================================================
FILE: ios-cargo
================================================
#!/usr/bin/env python3
import argparse
import subprocess
import tomllib
import os
import shutil
import zipfile
import tempfile
import json
def parse_cargo_toml():
with open('Cargo.toml', 'rb') as f:
cargo_toml = tomllib.load(f)
app_name = cargo_toml['package']['metadata']['bundle']['name']
app_id = cargo_toml['package']['metadata']['bundle']['identifier']
return app_name, app_id
def ipa(args):
print("Releasing the build...")
args.release = True
build(args)
app_name, _ = parse_cargo_toml()
build_type = 'release'
target = get_target(args)
cargo_target_dir = os.getenv('CARGO_TARGET_DIR')
if cargo_target_dir:
base_target_dir = cargo_target_dir
else:
base_target_dir = 'target'
app_path = os.path.join(base_target_dir, target, build_type, 'bundle', 'ios', f'{app_name}.app')
temp_dir = tempfile.mkdtemp()
payload_dir = os.path.join(temp_dir, "Payload")
os.makedirs(payload_dir)
shutil.copytree(app_path, os.path.join(payload_dir, f'{app_name}.app'))
ipa_path = f'{app_name}.ipa'
with zipfile.ZipFile(ipa_path, 'w', zipfile.ZIP_DEFLATED) as ipa_file:
for root, dirs, files in os.walk(payload_dir):
for file in files:
file_path = os.path.join(root, file)
ipa_file.write(file_path, os.path.relpath(file_path, os.path.dirname(payload_dir)))
shutil.rmtree(payload_dir)
print(f"Created {ipa_path}")
def post_process_info_plist(plist_path, ipad):
try:
with open('insert.plist', 'r') as insert_file:
insert_content = insert_file.read()
except:
insert_content = ""
with open(plist_path, 'r') as plist_file:
plist_content = plist_file.read()
if ipad:
ipad_content = """
UIDeviceFamily
1
2
UISupportedInterfaceOrientations
UIInterfaceOrientationPortrait
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UISupportedInterfaceOrientations~ipad
UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
"""
insert_content += ipad_content
modified_content = plist_content.replace('', f'{insert_content}\n')
with open(plist_path, 'w') as plist_file:
plist_file.write(modified_content)
def get_target(args):
target = 'aarch64-apple-ios'
if args.x86:
target = 'x86_64-apple-ios'
elif args.sim:
target = 'aarch64-apple-ios-sim'
if args.target:
target = args.target
return target
def build(args):
target = get_target(args)
command = ['cargo', 'bundle', '--target', target]
if args.release:
command.append('--release')
print(f"Running command: {' '.join(command)}")
subprocess.run(command, check=True)
app_name, _ = parse_cargo_toml()
build_type = 'release' if args.release else 'debug'
cargo_target_dir = os.getenv('CARGO_TARGET_DIR')
if cargo_target_dir:
base_target_dir = cargo_target_dir
else:
base_target_dir = 'target'
plist_path = os.path.join(base_target_dir, target, build_type, 'bundle', 'ios', f'{app_name}.app', 'Info.plist')
post_process_info_plist(plist_path, args.ipad)
def get_booted_device():
result = subprocess.run(['xcrun', 'simctl', 'list', 'devices', '--json'], capture_output=True, text=True, check=True)
devices = json.loads(result.stdout)
for runtime in devices['devices']:
for dev in devices['devices'][runtime]:
if dev['state'] == 'Booted':
return dev['udid']
return None
def boot_device(device):
print(f"Booting device {device}...")
subprocess.run(['xcrun', 'simctl', 'boot', device], check=True)
print(f"Device {device} booted.")
def get_newest_iphone_udid():
result = subprocess.run(['xcrun', 'simctl', 'list', 'devices', '--json'], capture_output=True, text=True, check=True)
devices = json.loads(result.stdout)
for runtime in devices['devices']:
for dev in devices['devices'][runtime]:
if 'iPhone' in dev['name'] and dev['isAvailable'] and 'SE' not in dev['name']:
return dev['udid']
raise Exception("No available iPhone simulators found")
def run_build(args):
app_name, app_id = parse_cargo_toml()
build_type = 'release' if args.release else 'debug'
target = get_target(args)
cargo_target_dir = os.getenv('CARGO_TARGET_DIR')
if cargo_target_dir:
base_target_dir = cargo_target_dir
else:
base_target_dir = 'target'
app_path = os.path.join(base_target_dir, target, build_type, 'bundle', 'ios', f'{app_name}.app')
if args.device == "booted":
if not get_booted_device():
specific_device_udid = get_newest_iphone_udid()
boot_device(specific_device_udid)
args.device = specific_device_udid
install_command = [
'xcrun', 'simctl', 'install', args.device, app_path
]
launch_command = ['xcrun', 'simctl', 'launch', '--console', args.device, app_id]
print(f"Running command: {' '.join(install_command)}")
subprocess.run(install_command, check=True)
print(f"Running command: {' '.join(launch_command)}")
subprocess.run(launch_command, check=True)
def run(args):
print("Running the build process...")
build(args)
print("Running the build...")
run_build(args)
def main():
parser = argparse.ArgumentParser(description='A script with build, run, run-build, and release subcommands.')
subparsers = parser.add_subparsers(dest='command', required=True)
build_parser = subparsers.add_parser('build', help='Build the project')
build_parser.add_argument('--x86', action='store_true', help='Use x86 target')
build_parser.add_argument('--sim', action='store_true', help='Use simulator target')
build_parser.add_argument('--target', type=str, help='Specify custom target')
build_parser.add_argument('--release', '-r', action='store_true', help='Build for release')
build_parser.add_argument('--ipad', action='store_true', help='Include iPad-specific Info.plist entries')
build_parser.set_defaults(func=build)
run_parser = subparsers.add_parser('run', help='Build and run the project')
run_parser.add_argument('--x86', action='store_true', help='Use x86 target')
run_parser.add_argument('--sim', action='store_true', help='Use simulator target')
run_parser.add_argument('--target', type=str, help='Specify custom target')
run_parser.add_argument('--release', '-r', action='store_true', help='Build for release')
run_parser.add_argument('--ipad', action='store_true', help='Include iPad-specific Info.plist entries')
run_parser.add_argument('--device', type=str, default='booted', help='Specify the target device')
run_parser.set_defaults(func=run)
run_build_parser = subparsers.add_parser('run-build', help='Runs already built project')
run_build_parser.add_argument('--x86', action='store_true', help='Use x86 target')
run_build_parser.add_argument('--sim', action='store_true', help='Use simulator target')
run_build_parser.add_argument('--target', type=str, help='Specify custom target')
run_build_parser.add_argument('--release', '-r', action='store_true', help='Build for release')
run_build_parser.add_argument('--device', type=str, default='booted', help='Specify the target device')
run_build_parser.add_argument('--ipad', action='store_true', help='Include iPad-specific Info.plist entries')
run_build_parser.set_defaults(func=run_build)
release_parser = subparsers.add_parser('ipa', help='Creates a ipa')
release_parser.add_argument('--x86', action='store_true', help='Use x86 target')
release_parser.add_argument('--sim', action='store_true', help='Use simulator target')
release_parser.add_argument('--target', type=str, help='Specify custom target')
release_parser.add_argument('--release', '-r', action='store_true', help='Build for release')
release_parser.add_argument('--ipad', action='store_true', help='Include iPad-specific Info.plist entries')
release_parser.set_defaults(func=ipa)
args = parser.parse_args()
args.func(args)
if __name__ == '__main__':
main()
================================================
FILE: src/color_picker.rs
================================================
use eframe::egui::{
self, lerp, pos2, remap_clamp, vec2, Align2, Color32, Mesh, Response, Sense, Shape, Stroke, Ui,
Vec2,
};
use eframe::epaint::StrokeKind;
// Ten colors that are distinguishable and suitable for colorblind people
pub const COLORS: [Color32; 10] = [
Color32::WHITE, // White
Color32::from_rgb(230, 159, 0), // Orange
Color32::from_rgb(86, 180, 233), // Sky Blue
Color32::from_rgb(0, 158, 115), // Bluish Green
Color32::from_rgb(240, 228, 66), // Yellow
Color32::from_rgb(0, 114, 178), // Blue
Color32::from_rgb(213, 94, 0), // Vermilion (Red-Orange)
Color32::from_rgb(204, 121, 167), // Reddish Purple
Color32::from_rgb(121, 94, 56), // Brown
Color32::from_rgb(0, 204, 204), // Cyan
];
fn contrast_color(color: Color32) -> Color32 {
let intensity = (color.r() as f32 + color.g() as f32 + color.b() as f32) / 3.0 / 255.0;
if intensity < 0.5 {
Color32::WHITE
} else {
Color32::BLACK
}
}
pub fn color_picker_widget(
ui: &mut Ui,
label: &str,
color: &mut [Color32],
index: usize,
) -> Response {
// Draw the square
ui.horizontal(|ui| {
// Define the desired square size (same as checkbox size)
let square_size = ui.spacing().interact_size.y * 0.8;
// Allocate a square of the same size as the checkbox
let (rect, response) =
ui.allocate_exact_size(egui::vec2(square_size, square_size), Sense::click());
// Highlight stroke when hovered
let stroke = if response.hovered() {
Stroke::new(2.0, Color32::WHITE) // White stroke when hovered
} else {
Stroke::NONE // No stroke otherwise
};
// Draw the color square with possible hover outline
ui.painter()
.rect(rect, 2.0, color[index], stroke, StrokeKind::Middle);
ui.label(label);
response
})
.inner
}
pub fn color_picker_window(ctx: &egui::Context, color: &mut Color32, value: &mut f32) -> bool {
let mut save_button = false;
let _window_response = egui::Window::new("Color Menu")
// .fixed_pos(Pos2 { x: 800.0, y: 450.0 })
.fixed_size(Vec2 { x: 100.0, y: 100.0 })
.anchor(Align2::CENTER_CENTER, Vec2 { x: 0.0, y: 0.0 })
.collapsible(false)
.show(ctx, |ui| {
// We will create two horizontal rows with five squares each
let square_size = ui.spacing().interact_size.y * 0.8;
ui.vertical(|ui| {
// First row (5 squares)
ui.horizontal(|ui| {
for color_option in &COLORS[0..5] {
let (rect, response) = ui.allocate_exact_size(
egui::vec2(square_size, square_size),
Sense::click(),
);
// Handle click to set selected color
if response.clicked() {
*color = *color_option;
}
// Stroke highlighting for hover
let stroke = if response.hovered() {
Stroke::new(2.0, Color32::WHITE)
} else {
Stroke::NONE
};
// Draw the color square
ui.painter()
.rect(rect, 2.0, *color_option, stroke, StrokeKind::Middle);
}
});
// Second row (5 squares)
ui.horizontal(|ui| {
for color_option in &COLORS[5..10] {
let (rect, response) = ui.allocate_exact_size(
egui::vec2(square_size, square_size),
Sense::click(),
);
// Handle click to set selected color
if response.clicked() {
*color = *color_option;
}
// Stroke highlighting for hover
let stroke = if response.hovered() {
Stroke::new(2.0, Color32::WHITE)
} else {
Stroke::NONE
};
// Draw the color square
ui.painter()
.rect(rect, 2.0, *color_option, stroke, StrokeKind::Middle);
}
});
// Now, create the 1D color bar slider below the grid
ui.separator(); // Optional visual separator between grid and color bar
// Add a 1D color slider below the color grid
let response = color_slider_1d(ui, value, |t| {
// Generate hue-based colors
let hue = t * 360.0; // Convert t from [0.0, 1.0] to [0.0, 360.0]
hsv_to_rgb(hue, 1.0, 1.0) // Full saturation and value
});
if response.clicked() || response.changed() || response.dragged() {
// Update the selected color based on the slider position
*color = hsv_to_rgb(*value * 360.0, 1.0, 1.0); // Update color
}
ui.add_space(5.0);
ui.centered_and_justified(|ui| {
if ui.button("Exit").clicked() {
save_button = true;
}
});
});
});
save_button
}
// Function to create a 1D color slider
fn color_slider_1d(ui: &mut Ui, value: &mut f32, color_at: impl Fn(f32) -> Color32) -> Response {
const N: usize = 100; // Number of segments
let desired_size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y);
let (rect, response) = ui.allocate_at_least(desired_size, Sense::click_and_drag());
if let Some(mpos) = response.interact_pointer_pos() {
*value = remap_clamp(mpos.x, rect.left()..=rect.right(), 0.0..=1.0);
}
if ui.is_rect_visible(rect) {
let visuals = ui.style().interact(&response);
// Fill the color gradient
let mut mesh = Mesh::default();
for i in 0..=N {
let t = i as f32 / (N as f32);
let color = color_at(t);
let x = lerp(rect.left()..=rect.right(), t);
mesh.colored_vertex(pos2(x, rect.top()), color);
mesh.colored_vertex(pos2(x, rect.bottom()), color);
if i < N {
mesh.add_triangle((2 * i) as u32, (2 * i + 1) as u32, (2 * i + 2) as u32);
mesh.add_triangle((2 * i + 1) as u32, (2 * i + 2) as u32, (2 * i + 3) as u32);
}
}
ui.painter().add(Shape::mesh(mesh));
ui.painter()
.rect_stroke(rect, 0.0, visuals.bg_stroke, StrokeKind::Middle); // outline
// Show where the slider is at:
let x = lerp(rect.left()..=rect.right(), *value);
let r = rect.height() / 4.0;
let picked_color = color_at(*value);
ui.painter().add(Shape::convex_polygon(
vec![
pos2(x, rect.center().y), // tip
pos2(x + r, rect.bottom()), // right bottom
pos2(x - r, rect.bottom()), // left bottom
],
picked_color,
Stroke::new(visuals.fg_stroke.width, contrast_color(picked_color)),
));
}
response
}
// Convert HSV color to RGB
fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> Color32 {
let c = value * saturation;
let x = c * (1.0 - ((hue / 60.0) % 2.0 - 1.0).abs());
let m = value - c;
let (r, g, b) = if hue < 60.0 {
(c, x, 0.0)
} else if hue < 120.0 {
(x, c, 0.0)
} else if hue < 180.0 {
(0.0, c, x)
} else if hue < 240.0 {
(0.0, x, c)
} else if hue < 300.0 {
(x, 0.0, c)
} else {
(c, 0.0, x)
};
Color32::from_rgb(
((r + m) * 255.0) as u8,
((g + m) * 255.0) as u8,
((b + m) * 255.0) as u8,
)
}
================================================
FILE: src/custom_highlighter.rs
================================================
extern crate regex;
use eframe::egui::{self, text::LayoutJob, Color32, TextFormat};
use eframe::egui::{FontFamily, FontId};
use regex::Regex;
use regex::RegexSet;
const DEFAULT_FONT_ID: FontId = FontId::new(14.0, FontFamily::Monospace);
#[derive(Debug, Clone, Copy)]
pub struct HighLightElement {
pos_start: usize,
pos_end: usize,
token_idx: usize,
}
impl HighLightElement {
pub fn new(pos_start: usize, pos_end: usize, token_idx: usize) -> Self {
Self {
pos_start,
pos_end,
token_idx,
}
}
}
pub fn highlight_impl(
_ctx: &egui::Context,
text: &str,
tokens: Vec,
default_color: Color32,
) -> Option {
// Extremely simple syntax highlighter for when we compile without syntect
let mut my_tokens = tokens.clone();
for token in my_tokens.clone() {
if token.is_empty() {
let index = my_tokens.iter().position(|x| *x == token).unwrap();
my_tokens.remove(index);
}
}
let content_string = String::from(text);
// let _ = file.read_to_string(&mut isi);
let mut regexs: Vec = Vec::new();
for sentence in my_tokens.clone() {
match Regex::new(&sentence) {
Ok(re) => {
regexs.push(re);
}
Err(_err) => {}
};
}
let mut highlight_list: Vec = Vec::::new();
match RegexSet::new(my_tokens.clone()) {
Ok(set) => {
for idx in set.matches(&content_string).into_iter() {
for caps in regexs[idx].captures_iter(&content_string) {
highlight_list.push(HighLightElement::new(
caps.get(0).unwrap().start(),
caps.get(0).unwrap().end(),
idx,
));
}
}
}
Err(_err) => {}
};
highlight_list.sort_by_key(|item| (item.pos_start, item.pos_end));
let mut job = LayoutJob::default();
let mut previous = HighLightElement::new(0, 0, 0);
for matches in highlight_list {
if previous.pos_end >= matches.pos_start {
continue;
}
job.append(
&text[previous.pos_end..(matches.pos_start)],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, default_color),
);
if matches.token_idx == 0 {
job.append(
&text[matches.pos_start..matches.pos_end],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, Color32::from_rgb(255, 100, 100)),
);
} else if matches.token_idx == 1 {
job.append(
&text[matches.pos_start..matches.pos_end],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, Color32::from_rgb(225, 159, 0)),
);
} else if matches.token_idx == 2 {
job.append(
&text[matches.pos_start..matches.pos_end],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, Color32::from_rgb(87, 165, 171)),
);
} else if matches.token_idx == 3 {
job.append(
&text[matches.pos_start..matches.pos_end],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, Color32::from_rgb(109, 147, 226)),
);
}
previous = matches;
}
job.append(
&text[previous.pos_end..],
0.0,
TextFormat::simple(DEFAULT_FONT_ID, default_color),
);
Some(job)
}
================================================
FILE: src/data.rs
================================================
use egui_plot::PlotPoint;
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Clone, Debug, PartialEq)]
pub enum SerialDirection {
Send,
Receive,
}
impl fmt::Display for SerialDirection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SerialDirection::Send => write!(f, "SEND"),
SerialDirection::Receive => write!(f, "RECV"),
}
}
}
pub fn get_epoch_ms() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis()
}
#[derive(Clone, Debug)]
pub struct Packet {
pub relative_time: f64,
pub absolute_time: f64,
pub direction: SerialDirection,
pub payload: String,
}
impl Default for Packet {
fn default() -> Packet {
Packet {
relative_time: 0.0,
absolute_time: get_epoch_ms() as f64,
direction: SerialDirection::Send,
payload: "".to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct DataContainer {
pub time: Vec,
pub absolute_time: Vec,
pub dataset: Vec>,
pub raw_traffic: Vec,
pub loaded_from_file: bool,
}
impl Default for DataContainer {
fn default() -> DataContainer {
DataContainer {
time: vec![],
absolute_time: vec![],
dataset: vec![],
raw_traffic: vec![],
loaded_from_file: false,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct GuiOutputDataContainer {
pub prints: Vec,
pub plots: Vec<(String, Vec)>,
}
================================================
FILE: src/gui.rs
================================================
use core::f32;
use crossbeam_channel::{Receiver, Sender};
use std::cmp::max;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use crate::color_picker::{color_picker_widget, color_picker_window, COLORS};
use crate::custom_highlighter::highlight_impl;
use crate::data::GuiOutputDataContainer;
use crate::serial::{clear_serial_settings, save_serial_settings, Device, SerialDevices};
use crate::settings_window::settings_window;
use crate::toggle::toggle;
#[cfg(feature = "self_update")]
use crate::update::check_update;
use crate::FileOptions;
use crate::{APP_INFO, PREFERENCES_KEY};
use eframe::egui::scroll_area::ScrollSource;
use eframe::egui::{
Align2, CollapsingHeader, Color32, FontFamily, FontId, KeyboardShortcut, Pos2, Sense, Ui, Vec2,
};
use eframe::{egui, Storage};
use egui::ThemePreference;
use egui_file_dialog::information_panel::InformationPanel;
use egui_file_dialog::{FileDialog, Filter};
use egui_plot::{log_grid_spacer, GridMark, Legend, Line, Plot, PlotPoints};
use preferences::Preferences;
#[cfg(feature = "self_update")]
use self_update::update::Release;
use serde::{Deserialize, Serialize};
use serialport::{DataBits, FlowControl, Parity, StopBits};
const DEFAULT_FONT_ID: FontId = FontId::new(14.0, FontFamily::Monospace);
pub const RIGHT_PANEL_WIDTH: f32 = 350.0;
const BAUD_RATES: &[u32] = &[
300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 74880, 115200, 230400, 128000, 460800,
576000, 921600,
];
const SAVE_FILE_SHORTCUT: KeyboardShortcut =
KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::S);
// bitOr is not const, so we use plus
const SAVE_PLOT_SHORTCUT: KeyboardShortcut = KeyboardShortcut::new(
egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT),
egui::Key::S,
);
const CLEAR_PLOT_SHORTCUT: KeyboardShortcut =
KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::X);
#[derive(Clone)]
pub enum FileDialogState {
Open,
Save,
SavePlot,
None,
}
#[derive(PartialEq)]
pub enum WindowFeedback {
None,
Waiting,
Clear,
Cancel,
}
#[derive(Clone)]
pub enum GuiCommand {
Clear,
ShowTimestamps(bool),
ShowSentTraffic(bool),
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct GuiSettingsContainer {
pub device: String,
pub baud: u32,
pub debug: bool,
pub x: f32,
pub y: f32,
pub save_absolute_time: bool,
pub dark_mode: bool,
pub theme_preference: ThemePreference,
}
impl Default for GuiSettingsContainer {
fn default() -> Self {
Self {
device: "".to_string(),
baud: 115_200,
debug: true,
x: 1600.0,
y: 900.0,
save_absolute_time: false,
dark_mode: true,
theme_preference: ThemePreference::System,
}
}
}
pub fn load_gui_settings() -> GuiSettingsContainer {
GuiSettingsContainer::load(&APP_INFO, PREFERENCES_KEY).unwrap_or_else(|_| {
let gui_settings = GuiSettingsContainer::default();
// save default settings
if gui_settings.save(&APP_INFO, PREFERENCES_KEY).is_err() {
log::error!("failed to save gui_settings");
}
gui_settings
})
}
pub enum ColorWindow {
NoShow,
ColorIndex(usize),
}
pub struct MyApp {
connected_to_device: bool,
command: String,
device: String,
old_device: String,
device_idx: usize,
serial_devices: SerialDevices,
plotting_range: usize,
max_points: usize,
plot_serial_display_ratio: f32,
picked_path: PathBuf,
plot_location: Option,
data: GuiOutputDataContainer,
file_dialog_state: FileDialogState,
file_dialog: FileDialog,
information_panel: InformationPanel,
file_opened: bool,
settings_window_open: bool,
update_text: String,
gui_conf: GuiSettingsContainer,
device_lock: Arc>,
devices_lock: Arc>>,
connected_lock: Arc>,
data_lock: Arc>,
save_tx: Sender,
load_tx: Sender,
load_names_rx: Receiver>,
send_tx: Sender,
gui_cmd_tx: Sender,
history: Vec,
index: usize,
eol: String,
colors: Vec,
color_vals: Vec,
labels: Vec,
show_color_window: ColorWindow,
show_sent_cmds: bool,
show_timestamps: bool,
save_raw: bool,
show_warning_window: WindowFeedback,
do_not_show_clear_warning: bool,
init: bool,
cli_column_colors: Vec,
#[cfg(feature = "self_update")]
new_release: Option,
}
#[allow(clippy::too_many_arguments)]
impl MyApp {
pub fn new(
cc: &eframe::CreationContext,
data_lock: Arc>,
device_lock: Arc>,
devices_lock: Arc>>,
devices: SerialDevices,
connected_lock: Arc>,
gui_conf: GuiSettingsContainer,
save_tx: Sender,
load_tx: Sender,
load_names_rx: Receiver>,
send_tx: Sender,
gui_cmd_tx: Sender,
cli_column_colors: Vec,
) -> Self {
let mut file_dialog = FileDialog::default()
//.initial_directory(PathBuf::from("/path/to/app"))
.default_file_name("measurement.csv")
.default_size([600.0, 400.0])
// .add_quick_access("Project", |s| {
// s.add_path("☆ Examples", "examples");
// s.add_path("📷 Media", "media");
// s.add_path("📂 Source", "src");
// })
.set_file_icon(
"🖹",
Filter::new(|path: &Path| {
path.extension()
.unwrap_or_default()
.eq_ignore_ascii_case("md")
}),
)
.set_file_icon(
"",
Filter::new(|path: &Path| {
path.file_name()
.unwrap_or_default()
.eq_ignore_ascii_case(".gitignore")
}),
)
.add_file_filter(
"CSV files",
Filter::new(|p: &Path| {
p.extension()
.unwrap_or_default()
.eq_ignore_ascii_case("csv")
}),
);
// Load the persistent data of the file dialog.
// Alternatively, you can also use the `FileDialog::storage` builder method.
if let Some(storage) = cc.storage {
*file_dialog.storage_mut() =
eframe::get_value(storage, "file_dialog_storage").unwrap_or_default()
}
Self {
connected_to_device: false,
picked_path: PathBuf::new(),
device: "".to_string(),
old_device: "".to_string(),
data: GuiOutputDataContainer::default(),
file_dialog_state: FileDialogState::None,
file_dialog,
information_panel: InformationPanel::default().add_file_preview("csv", |ui, item| {
ui.label("CSV preview:");
if let Some(mut content) = item.content() {
egui::ScrollArea::vertical()
.max_height(ui.available_height())
.show(ui, |ui| {
ui.add(egui::TextEdit::multiline(&mut content).code_editor());
});
}
}),
connected_lock,
device_lock,
devices_lock,
device_idx: 0,
serial_devices: devices,
gui_conf,
data_lock,
save_tx,
load_tx,
load_names_rx,
send_tx,
gui_cmd_tx,
plotting_range: usize::MAX,
max_points: 5000,
plot_serial_display_ratio: 0.45,
command: "".to_string(),
show_sent_cmds: true,
show_timestamps: true,
save_raw: false,
eol: "\\r\\n".to_string(),
colors: vec![COLORS[0]],
color_vals: vec![0.0],
labels: vec!["Column 0".to_string()],
history: vec![],
index: 0,
plot_location: None,
do_not_show_clear_warning: false,
show_warning_window: WindowFeedback::None,
init: false,
show_color_window: ColorWindow::NoShow,
file_opened: false,
cli_column_colors,
#[cfg(feature = "self_update")]
new_release: None,
settings_window_open: false,
update_text: "".to_string(),
}
}
pub fn clear_warning_window(&mut self, ui: &mut egui::Ui) -> WindowFeedback {
let mut window_feedback = WindowFeedback::Waiting;
egui::Window::new("Attention!")
.fixed_pos(Pos2 { x: 800.0, y: 450.0 })
.fixed_size(Vec2 { x: 400.0, y: 200.0 })
.anchor(Align2::CENTER_CENTER, Vec2 { x: 0.0, y: 0.0 })
.collapsible(false)
.show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.add_space(20.0);
ui.label("Changing devices will clear all data.");
ui.label("How do you want to proceed?");
ui.add_space(20.0);
ui.checkbox(&mut self.do_not_show_clear_warning, "Remember my decision.");
ui.add_space(20.0);
ui.horizontal(|ui| {
ui.add_space(130.0);
if ui.button("Continue & Clear").clicked() {
window_feedback = WindowFeedback::Clear;
}
if ui.button("Cancel").clicked() {
window_feedback = WindowFeedback::Cancel;
}
});
ui.add_space(5.0);
});
});
window_feedback
}
fn draw_central_panel(&mut self, ui: &mut egui::Ui) {
egui::CentralPanel::default().show_inside(ui, |ui| {
let left_border = 10.0;
// Width
let width = ui.available_size().x - 2.0 * left_border;
// Height
let top_spacing = 5.0;
let panel_height = ui.available_size().y;
let mut plot_height: f32 = 0.0;
if self.serial_devices.number_of_plots[self.device_idx] > 0 {
let height = ui.available_size().y * self.plot_serial_display_ratio;
plot_height = height;
// need to subtract 12.0, this seems to be the height of the separator of two adjacent plots
plot_height = plot_height
/ (self.serial_devices.number_of_plots[self.device_idx] as f32)
- 12.0;
}
let mut plot_ui_heigh: f32 = 0.0;
ui.add_space(top_spacing);
ui.horizontal(|ui| {
ui.add_space(left_border);
ui.vertical(|ui| {
if let Ok(gui_data) = self.data_lock.read() {
self.data = gui_data.clone();
if self.data.plots.len() != self.labels.len() {
self.labels = gui_data.plots.iter().map(|d| d.0.clone()).collect();
}
if self.colors.len() != self.labels.len() {
self.colors = (0..max(self.labels.len(), 1))
.map(|i| {
self.cli_column_colors
.get(i)
.copied()
.unwrap_or(COLORS[i % COLORS.len()])
})
.collect();
self.color_vals =
(0..max(self.data.plots.len(), 1)).map(|_| 0.0).collect();
}
}
// TODO what about self.data.loaded_from_file
if self.file_opened {
if let Ok(labels) = self.load_names_rx.try_recv() {
self.labels = labels;
self.colors = (0..max(self.labels.len(), 1))
.map(|i| COLORS[i % COLORS.len()])
.collect();
self.color_vals = (0..max(self.labels.len(), 1)).map(|_| 0.0).collect();
}
}
if self.serial_devices.number_of_plots[self.device_idx] > 0 {
if self.data.plots.len() != self.labels.len() && !self.file_opened {
// self.labels = (0..max(self.data.dataset.len(), 1))
// .map(|i| format!("Column {i}"))
// .collect();
self.colors = (0..max(self.data.plots.len(), 1))
.map(|i| COLORS[i % COLORS.len()])
.collect();
self.color_vals =
(0..max(self.data.plots.len(), 1)).map(|_| 0.0).collect();
}
// offloaded to main thread
// let mut graphs: Vec> = vec![vec![]; self.data.dataset.len()];
// let window = self.data.dataset[0]
// .len()
// .saturating_sub(self.plotting_range);
//
// for (i, time) in self.data.time[window..].iter().enumerate() {
// let x = *time / 1000.0;
// for (graph, data) in graphs.iter_mut().zip(&self.data.dataset) {
// if self.data.time.len() == data.len() {
// if let Some(y) = data.get(i + window) {
// graph.push(PlotPoint { x, y: *y as f64 });
// }
// }
// }
// }
let window = if let Some(first_entry) = self.data.plots.first() {
first_entry.1.len().saturating_sub(self.plotting_range)
} else {
0
};
let t_fmt = |x: GridMark, _range: &RangeInclusive| {
format!("{:4.2} s", x.value)
};
let plots_ui = ui.vertical(|ui| {
for graph_idx in 0..self.serial_devices.number_of_plots[self.device_idx]
{
if graph_idx != 0 {
ui.separator();
}
let signal_plot = Plot::new(format!("data-{graph_idx}"))
.height(plot_height)
.width(width)
.legend(Legend::default())
.x_grid_spacer(log_grid_spacer(10))
.y_grid_spacer(log_grid_spacer(10))
.x_axis_formatter(t_fmt);
let n = (self.data.prints.len() / self.max_points).max(1);
let plot_inner = signal_plot.show(ui, |signal_plot_ui| {
for (i, (_label, graph)) in self.data.plots.iter().enumerate() {
// this check needs to be here for when we change devices (not very elegant)
if i < self.labels.len() {
signal_plot_ui.line(
Line::new(
self.labels[i].to_string(),
PlotPoints::Owned(
graph
.iter()
.skip(window)
.step_by(n)
.cloned()
.collect(),
),
)
.color(self.colors[i]),
);
}
}
});
self.plot_location = Some(plot_inner.response.rect);
}
let separator_response = ui.separator();
let separator = ui
.interact(
separator_response.rect,
separator_response.id,
Sense::click_and_drag(),
)
.on_hover_cursor(egui::CursorIcon::ResizeVertical);
let resize_y = separator.drag_delta().y;
if separator.double_clicked() {
self.plot_serial_display_ratio = 0.45;
}
self.plot_serial_display_ratio = (self.plot_serial_display_ratio
+ resize_y / panel_height)
.clamp(0.1, 0.9);
ui.add_space(top_spacing);
});
plot_ui_heigh = plots_ui.response.rect.height();
} else {
plot_ui_heigh = 0.0;
}
let serial_height =
panel_height - plot_ui_heigh - left_border * 2.0 - top_spacing;
let num_rows = self.data.prints.len();
let row_height = ui.text_style_height(&egui::TextStyle::Body);
let color = if self.gui_conf.dark_mode {
Color32::WHITE
} else {
Color32::BLACK
};
egui::ScrollArea::vertical()
.id_salt("serial_output")
.auto_shrink([false; 2])
.stick_to_bottom(true)
.scroll_source(ScrollSource::ALL)
.max_height(serial_height - top_spacing)
.min_scrolled_height(serial_height - top_spacing)
.max_width(width)
.show_rows(ui, row_height, num_rows, |ui, row_range| {
let content: String = row_range
.into_iter()
.flat_map(|i| {
if self.data.prints.is_empty() {
None
} else {
Some(self.data.prints[i].clone())
}
})
.collect();
let mut layouter =
|ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap_width: f32| {
let string = text.as_str();
let mut layout_job = highlight_impl(
ui.ctx(),
string,
self.serial_devices.highlight_labels[self.device_idx]
.clone(),
Color32::from_rgb(155, 164, 167),
)
.unwrap();
layout_job.wrap.max_width = wrap_width;
ui.fonts_mut(|f| f.layout_job(layout_job))
};
ui.add(
egui::TextEdit::multiline(&mut content.as_str())
.font(DEFAULT_FONT_ID) // for cursor height
.lock_focus(true)
.text_color(color)
.desired_width(width)
.layouter(&mut layouter),
);
});
ui.horizontal(|ui| {
let cmd_line = ui.add(
egui::TextEdit::singleline(&mut self.command)
.desired_width(width - 50.0)
.lock_focus(true)
.code_editor(),
);
let cmd_has_lost_focus = cmd_line.lost_focus();
let key_pressed = ui.input(|i| i.key_pressed(egui::Key::Enter));
if (key_pressed && cmd_has_lost_focus) || ui.button("Send").clicked() {
// send command
self.history.push(self.command.clone());
self.index = self.history.len() - 1;
let eol = self.eol.replace("\\r", "\r").replace("\\n", "\n");
if let Err(err) = self.send_tx.send(self.command.clone() + &eol) {
log::error!("send_tx thread send failed: {:?}", err);
}
// stay in focus!
cmd_line.request_focus();
}
});
if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) {
self.index = self.index.saturating_sub(1);
if !self.history.is_empty() {
self.command = self.history[self.index].clone();
}
}
if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
self.index = std::cmp::min(self.index + 1, self.history.len() - 1);
if !self.history.is_empty() {
self.command = self.history[self.index].clone();
}
}
});
ui.add_space(left_border);
});
});
}
fn draw_serial_settings(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
ui.heading("Serial Monitor");
self.paint_connection_indicator(ui);
});
let devices: Vec = if let Ok(read_guard) = self.devices_lock.read() {
read_guard.clone()
} else {
vec![]
};
if !devices.contains(&self.device) {
self.device.clear();
}
if let Ok(dev) = self.device_lock.read() {
if !dev.name.is_empty() {
self.device = dev.name.clone();
}
}
ui.add_space(10.0);
ui.horizontal(|ui| {
ui.label("Device");
ui.add_space(130.0);
ui.label("Baud");
});
let old_name = self.device.clone();
ui.horizontal(|ui| {
if self.file_opened {
ui.disable();
}
let dev_text = self.device.replace("/dev/tty.", "");
ui.horizontal(|ui| {
if self.connected_to_device {
ui.disable();
}
let _response = egui::ComboBox::from_id_salt("Device")
.selected_text(dev_text)
.width(RIGHT_PANEL_WIDTH * 0.92 - 155.0)
.show_ui(ui, |ui| {
devices
.into_iter()
// on macOS each device appears as /dev/tty.* and /dev/cu.*
// we only display the /dev/tty.* here
.filter(|dev| !dev.contains("/dev/cu."))
.for_each(|dev| {
// this makes the names shorter in the UI on UNIX and UNIX-like platforms
let dev_text = dev.replace("/dev/tty.", "");
ui.selectable_value(&mut self.device, dev, dev_text);
});
})
.response;
// let selected_new_device = response.changed(); //somehow this does not work
// if selected_new_device {
if old_name != self.device {
if !self.data.prints.is_empty() {
self.show_warning_window = WindowFeedback::Waiting;
self.old_device = old_name;
} else {
self.show_warning_window = WindowFeedback::Clear;
}
}
});
match self.show_warning_window {
WindowFeedback::None => {}
WindowFeedback::Waiting => {
self.show_warning_window = self.clear_warning_window(ui);
}
WindowFeedback::Clear => {
// new device selected, check in previously used devices
let mut device_is_already_saved = false;
for (idx, dev) in self.serial_devices.devices.iter().enumerate() {
if dev.name == self.device {
// this is the device!
self.device = dev.name.clone();
self.device_idx = idx;
self.init = true;
device_is_already_saved = true;
}
}
if !device_is_already_saved {
// create new device in the archive
let mut device = Device::default();
device.name = self.device.clone();
self.serial_devices.devices.push(device);
self.serial_devices.number_of_plots.push(1);
self.serial_devices.number_of_highlights.push(1);
self.serial_devices
.highlight_labels
.push(vec!["".to_string()]);
self.serial_devices
.labels
.push(vec!["Column 0".to_string()]);
self.device_idx = self.serial_devices.devices.len() - 1;
save_serial_settings(&self.serial_devices);
}
self.gui_cmd_tx
.send(GuiCommand::Clear)
.expect("failed to send clear after choosing new device");
// need to clear the data here such that we don't get errors in the gui (plot)
self.data = GuiOutputDataContainer::default();
self.show_warning_window = WindowFeedback::None;
}
WindowFeedback::Cancel => {
self.device = self.old_device.clone();
self.show_warning_window = WindowFeedback::None;
}
}
egui::ComboBox::from_id_salt("Baud Rate")
.selected_text(format!(
"{}",
self.serial_devices.devices[self.device_idx].baud_rate
))
.width(80.0)
.show_ui(ui, |ui| {
if self.connected_to_device {
ui.disable();
}
BAUD_RATES.iter().for_each(|baud_rate| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].baud_rate,
*baud_rate,
baud_rate.to_string(),
);
});
});
let connect_text = if self.connected_to_device {
"Disconnect"
} else {
"Connect"
};
if ui.button(connect_text).clicked() {
if let Ok(mut device) = self.device_lock.write() {
if self.connected_to_device {
device.name.clear();
} else {
device.name = self.serial_devices.devices[self.device_idx].name.clone();
device.baud_rate = self.serial_devices.devices[self.device_idx].baud_rate;
}
}
}
});
ui.add_space(5.0);
ui.horizontal(|ui| {
ui.label("Data Bits");
ui.add_space(5.0);
ui.label("Parity");
ui.add_space(20.0);
ui.label("Stop Bits");
ui.label("Flow Control");
ui.label("Timeout");
});
ui.horizontal(|ui| {
if self.connected_to_device {
ui.disable();
}
egui::ComboBox::from_id_salt("Data Bits")
.selected_text(
self.serial_devices.devices[self.device_idx]
.data_bits
.to_string(),
)
.width(30.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].data_bits,
DataBits::Eight,
DataBits::Eight.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].data_bits,
DataBits::Seven,
DataBits::Seven.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].data_bits,
DataBits::Six,
DataBits::Six.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].data_bits,
DataBits::Five,
DataBits::Five.to_string(),
);
});
egui::ComboBox::from_id_salt("Parity")
.selected_text(
self.serial_devices.devices[self.device_idx]
.parity
.to_string(),
)
.width(30.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].parity,
Parity::None,
Parity::None.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].parity,
Parity::Odd,
Parity::Odd.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].parity,
Parity::Even,
Parity::Even.to_string(),
);
});
egui::ComboBox::from_id_salt("Stop Bits")
.selected_text(
self.serial_devices.devices[self.device_idx]
.stop_bits
.to_string(),
)
.width(30.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].stop_bits,
StopBits::One,
StopBits::One.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].stop_bits,
StopBits::Two,
StopBits::Two.to_string(),
);
});
egui::ComboBox::from_id_salt("Flow Control")
.selected_text(
self.serial_devices.devices[self.device_idx]
.flow_control
.to_string(),
)
.width(75.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].flow_control,
FlowControl::None,
FlowControl::None.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].flow_control,
FlowControl::Hardware,
FlowControl::Hardware.to_string(),
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].flow_control,
FlowControl::Software,
FlowControl::Software.to_string(),
);
});
egui::ComboBox::from_id_salt("Timeout")
.selected_text(
self.serial_devices.devices[self.device_idx]
.timeout
.as_millis()
.to_string(),
)
.width(55.0)
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].timeout,
Duration::from_millis(0),
"0",
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].timeout,
Duration::from_millis(10),
"10",
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].timeout,
Duration::from_millis(100),
"100",
);
ui.selectable_value(
&mut self.serial_devices.devices[self.device_idx].timeout,
Duration::from_millis(1000),
"1000",
);
});
});
ui.add_space(5.0);
ui.horizontal(|ui| {
if self.connected_to_device {
ui.disable();
}
if ui
.button(egui::RichText::new(format!(
"{} Open file",
egui_phosphor::regular::FOLDER_OPEN
)))
.on_hover_text("Load data from .csv")
.clicked()
{
self.file_dialog_state = FileDialogState::Open;
self.file_dialog.pick_file();
}
if self.file_opened
&& ui
.button(egui::RichText::new(
egui_phosphor::regular::X_SQUARE.to_string(),
))
.on_hover_text("Close file.")
.clicked()
{
self.file_opened = false;
let _ = self.load_tx.send(PathBuf::new());
self.file_dialog_state = FileDialogState::None;
}
});
}
fn draw_export_settings(&mut self, ui: &mut Ui) {
egui::Grid::new("export_settings")
.num_columns(2)
.spacing(Vec2 { x: 10.0, y: 10.0 })
.striped(true)
.show(ui, |ui| {
if ui
.button(egui::RichText::new(format!(
"{} Save CSV",
egui_phosphor::regular::FLOPPY_DISK
)))
.on_hover_text("Save Plot Data to CSV.")
.clicked()
|| ui.input_mut(|i| i.consume_shortcut(&SAVE_FILE_SHORTCUT))
{
self.file_dialog_state = FileDialogState::Save;
self.file_dialog.save_file();
}
if ui
.button(egui::RichText::new(format!(
"{} Save Plot",
egui_phosphor::regular::FLOPPY_DISK
)))
.on_hover_text("Save an image of the Plot.")
.clicked()
|| ui.input_mut(|i| i.consume_shortcut(&SAVE_PLOT_SHORTCUT))
{
self.file_dialog_state = FileDialogState::SavePlot;
self.file_dialog.save_file();
}
ui.end_row();
ui.label("Save Raw Traffic");
ui.add(toggle(&mut self.save_raw))
.on_hover_text("Save second CSV containing raw traffic.")
.changed();
ui.end_row();
ui.label("Save Absolute Time");
ui.add(toggle(&mut self.gui_conf.save_absolute_time))
.on_hover_text("Save absolute time in CSV.");
ui.end_row();
});
}
fn draw_global_settings(&mut self, ui: &mut Ui) {
ui.add_space(20.0);
if ui
.button(format!("{} Settings", egui_phosphor::regular::GEAR_FINE))
.clicked()
{
#[cfg(feature = "self_update")]
{
self.new_release = check_update();
}
self.settings_window_open = true;
}
if self.settings_window_open {
settings_window(
ui,
&mut self.gui_conf,
#[cfg(feature = "self_update")]
&mut self.new_release,
&mut self.settings_window_open,
&mut self.update_text,
);
}
ui.add_space(20.0);
if ui
.button(egui::RichText::new(format!(
"{} Clear Data",
egui_phosphor::regular::X
)))
.on_hover_text("Clear Data from Plot.")
.clicked()
|| ui.input_mut(|i| i.consume_shortcut(&CLEAR_PLOT_SHORTCUT))
{
log::info!("Cleared recorded Data");
if let Err(err) = self.gui_cmd_tx.send(GuiCommand::Clear) {
log::error!("clear_tx thread send failed: {:?}", err);
}
// need to clear the data here in order to prevent errors in the gui (plot)
self.data = GuiOutputDataContainer::default();
// self.names_tx.send(self.serial_devices.labels[self.device_idx].clone()).expect("Failed to send names");
}
ui.add_space(5.0);
ui.horizontal(|ui| {
if ui.button("Clear Device History").clicked() {
self.serial_devices = SerialDevices::default();
self.device.clear();
self.device_idx = 0;
clear_serial_settings();
}
if ui.button("Reset Labels").clicked() {
// self.serial_devices.labels[self.device_idx] = self.serial_devices.labels.clone();
}
});
ui.add_space(5.0);
ui.horizontal(|ui| {
if ui
.add(toggle(&mut self.show_sent_cmds))
.on_hover_text("Show sent commands in console.")
.changed()
{
if let Err(err) = self
.gui_cmd_tx
.send(GuiCommand::ShowSentTraffic(self.show_sent_cmds))
{
log::error!("clear_tx thread send failed: {:?}", err);
}
}
ui.label("Show Sent Commands");
});
ui.add_space(5.0);
ui.horizontal(|ui| {
if ui
.add(toggle(&mut self.show_timestamps))
.on_hover_text("Show timestamp in console.")
.changed()
{
if let Err(err) = self
.gui_cmd_tx
.send(GuiCommand::ShowTimestamps(self.show_sent_cmds))
{
log::error!("clear_tx thread send failed: {:?}", err);
}
}
ui.label("Show Timestamp");
});
ui.add_space(5.0);
ui.horizontal(|ui| {
ui.label("EOL character");
ui.add(
egui::TextEdit::singleline(&mut self.eol).desired_width(ui.available_width() * 0.9),
)
.on_hover_text("Configure your EOL character for sent commands..");
});
}
fn draw_plot_settings(&mut self, ui: &mut Ui) {
egui::Grid::new("plot_settings")
.num_columns(2)
.spacing(Vec2 { x: 10.0, y: 10.0 })
.striped(true)
.show(ui, |ui| {
ui.label("Plotting range [#]: ");
let window_fmt = |val: f64, _range: RangeInclusive| {
if val != usize::MAX as f64 {
val.to_string()
} else {
"∞".to_string()
}
};
ui.horizontal(|ui| {
ui.add(
egui::DragValue::new(&mut self.plotting_range).custom_formatter(window_fmt),
)
.on_hover_text(
"Select a window of the last datapoints to be displayed in the plot.",
);
if ui
.button("Full Dataset")
.on_hover_text("Show the full dataset.")
.clicked()
{
self.plotting_range = usize::MAX;
}
});
ui.end_row();
ui.label("Max Points [#]: ");
ui.horizontal(|ui| {
ui.add(
egui::DragValue::new(&mut self.max_points).custom_formatter(window_fmt),
)
.on_hover_text(
"Select the maximum number of points to be displayed in the plot. The actual displayed points will be less than this value (only every 2nd, 3rd, etc. point will be displayed).",
);
if ui
.button("Full Dataset")
.on_hover_text("Show the full dataset.")
.clicked()
{
self.max_points = usize::MAX;
}
});
ui.end_row();
ui.label("Number of plots [#]: ");
ui.horizontal(|ui| {
if ui
.button(egui::RichText::new(
egui_phosphor::regular::ARROW_FAT_LEFT.to_string(),
))
.clicked()
{
if self.serial_devices.number_of_plots[self.device_idx] == 0 {
return;
}
self.serial_devices.number_of_plots[self.device_idx] =
(self.serial_devices.number_of_plots[self.device_idx] - 1).clamp(0, 10);
}
ui.add(
egui::DragValue::new(
&mut self.serial_devices.number_of_plots[self.device_idx],
)
.range(0..=10),
)
.on_hover_text("Select the number of plots to be shown.");
if ui
.button(egui::RichText::new(
egui_phosphor::regular::ARROW_FAT_RIGHT.to_string(),
))
.clicked()
{
if self.serial_devices.number_of_plots[self.device_idx] == 10 {
return;
}
self.serial_devices.number_of_plots[self.device_idx] =
(self.serial_devices.number_of_plots[self.device_idx] + 1).clamp(0, 10);
}
});
ui.end_row();
});
ui.add_space(25.0);
if self.labels.len() == 1 {
ui.label("Detected 1 Dataset:");
} else {
ui.label(format!("Detected {} Datasets:", self.labels.len()));
}
ui.add_space(5.0);
for i in 0..self.labels.len().min(10) {
// if init, set names to what has been stored in the device last time
if self.init {
// self.names_tx.send(self.labels.clone()).expect("Failed to send names");
self.init = false;
}
if self.labels.len() <= i {
break;
}
ui.horizontal(|ui| {
let response = color_picker_widget(ui, "", &mut self.colors, i);
// Check if the square was clicked and toggle color picker window
if response.clicked() {
self.show_color_window = ColorWindow::ColorIndex(i);
};
if ui
.add(
egui::TextEdit::singleline(&mut self.labels[i])
.desired_width(0.95 * RIGHT_PANEL_WIDTH),
)
.on_hover_text("Use custom names for your Datasets.")
.changed()
{
// self.names_tx.send(self.labels.clone()).expect("Failed to send names");
};
});
}
match self.show_color_window {
ColorWindow::NoShow => {}
ColorWindow::ColorIndex(index) => {
if color_picker_window(
ui.ctx(),
&mut self.colors[index],
&mut self.color_vals[index],
) {
self.show_color_window = ColorWindow::NoShow;
}
}
}
if self.labels.len() > 10 {
ui.label("Only renaming up to 10 Datasets is currently supported.");
}
}
fn draw_highlight_settings(&mut self, ui: &mut Ui) {
egui::Grid::new("highlight_settings")
.num_columns(2)
.spacing(Vec2 { x: 10.0, y: 10.0 })
.striped(true)
.show(ui, |ui| {
ui.label("Number of sentence [#]: ");
ui.horizontal(|ui| {
if ui
.button(egui::RichText::new(
egui_phosphor::regular::ARROW_FAT_LEFT.to_string(),
))
.clicked()
{
self.serial_devices.number_of_highlights[self.device_idx] =
(self.serial_devices.number_of_highlights[self.device_idx] - 1)
.clamp(1, 4);
while self.serial_devices.number_of_highlights[self.device_idx]
< self.serial_devices.highlight_labels[self.device_idx].len()
{
self.serial_devices.highlight_labels[self.device_idx].truncate(
self.serial_devices.number_of_highlights[self.device_idx],
);
}
}
ui.add(
egui::DragValue::new(
&mut self.serial_devices.number_of_highlights[self.device_idx],
)
.range(1..=4),
)
.on_hover_text("Select the number of sentence to be highlighted.");
if ui
.button(egui::RichText::new(
egui_phosphor::regular::ARROW_FAT_RIGHT.to_string(),
))
.clicked()
{
self.serial_devices.number_of_highlights[self.device_idx] =
(self.serial_devices.number_of_highlights[self.device_idx] + 1)
.clamp(1, 4);
}
while self.serial_devices.number_of_highlights[self.device_idx]
> self.serial_devices.highlight_labels[self.device_idx].len()
{
self.serial_devices.highlight_labels[self.device_idx].push("".to_string());
}
});
});
ui.label(format!(
"Detected {} highlight:",
self.serial_devices.number_of_highlights[self.device_idx]
));
ui.add_space(5.0);
for i in 0..(self.serial_devices.number_of_highlights[self.device_idx]) {
ui.add(
egui::TextEdit::singleline(
&mut self.serial_devices.highlight_labels[self.device_idx][i],
)
.desired_width(0.95 * RIGHT_PANEL_WIDTH),
)
.on_hover_text("Sentence to highlight");
/*
// Todo implement the color picker for each sentence
let mut theme =
egui_extras::syntax_highlighting::CodeTheme::from_memory(ui.ctx(), ui.style());
ui.collapsing(self.serial_devices.highlight_labels[self.device_idx][i].clone(), |ui| {
theme.ui(ui);
theme.store_in_memory(ui.ctx());
});
*/
}
}
fn draw_side_panel(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
egui::Panel::right("settings panel")
.min_size(RIGHT_PANEL_WIDTH)
.max_size(RIGHT_PANEL_WIDTH)
.resizable(false)
//.default_width(right_panel_width)
.show_inside(ui, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
ui.add_enabled_ui(true, |ui| {
self.draw_serial_settings(ui);
self.draw_global_settings(ui);
ui.add_space(10.0);
CollapsingHeader::new("Plot Settings")
.default_open(true)
.show(ui, |ui| {
self.draw_plot_settings(ui);
});
CollapsingHeader::new("Text Highlight Settings")
.default_open(true)
.show(ui, |ui| {
self.draw_highlight_settings(ui);
});
CollapsingHeader::new("Export Settings")
.default_open(true)
.show(ui, |ui| {
self.draw_export_settings(ui);
});
});
ui.add_space(20.0);
ui.separator();
ui.collapsing("Debug logs:", |ui| {
egui_logger::logger_ui().show(ui);
});
ui.ctx().input(|i| {
// Check if files were dropped
if let Some(dropped_file) = i.raw.dropped_files.last() {
let path = dropped_file.clone().path.unwrap();
self.picked_path = path.to_path_buf();
self.file_opened = true;
if let Err(e) = self.load_tx.send(self.picked_path.clone()) {
log::error!("load_tx thread send failed: {:?}", e);
}
}
});
match self.file_dialog_state {
FileDialogState::Open => {
if let Some(path) = self
.file_dialog
.update_with_right_panel_ui(ui.ctx(), &mut |ui, dia| {
self.information_panel.ui(ui, dia);
})
.picked()
{
self.picked_path = path.to_path_buf();
self.file_opened = true;
self.file_dialog_state = FileDialogState::None;
if let Err(e) = self.load_tx.send(self.picked_path.clone()) {
log::error!("load_tx thread send failed: {:?}", e);
}
}
}
FileDialogState::SavePlot => {
if let Some(path) = self.file_dialog.update(ui.ctx()).picked() {
self.picked_path = path.to_path_buf();
self.file_dialog_state = FileDialogState::None;
self.picked_path.set_extension("png");
ui.ctx()
.send_viewport_cmd(egui::ViewportCommand::Screenshot(
Default::default(),
));
}
}
FileDialogState::Save => {
if let Some(path) = self.file_dialog.update(ui.ctx()).picked() {
self.picked_path = path.to_path_buf();
self.file_dialog_state = FileDialogState::None;
self.picked_path.set_extension("csv");
if let Err(e) = self.save_tx.send(FileOptions {
file_path: self.picked_path.clone(),
save_absolute_time: self.gui_conf.save_absolute_time,
save_raw_traffic: self.save_raw,
names: self.labels.clone(),
}) {
log::error!("save_tx thread send failed: {:?}", e);
}
}
}
FileDialogState::None => {}
}
});
});
}
fn paint_connection_indicator(&self, ui: &mut egui::Ui) {
let (color, color_stroke) = if !self.connected_to_device {
ui.add(egui::Spinner::new());
(Color32::DARK_RED, Color32::RED)
} else {
(Color32::DARK_GREEN, Color32::GREEN)
};
let radius = ui.spacing().interact_size.y * 0.375;
let center = egui::pos2(
ui.next_widget_position().x + ui.spacing().interact_size.x * 0.5,
ui.next_widget_position().y,
);
ui.painter()
.circle(center, radius, color, egui::Stroke::new(1.0, color_stroke));
}
}
impl eframe::App for MyApp {
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
if let Ok(read_guard) = self.connected_lock.read() {
self.connected_to_device = *read_guard;
}
self.draw_side_panel(ui, frame);
self.draw_central_panel(ui);
self.gui_conf.x = ui.globally_used_rect().width();
self.gui_conf.y = ui.globally_used_rect().height();
// Check for returned screenshot:
let screenshot = ui.ctx().input(|i| {
for event in &i.raw.events {
if let egui::Event::Screenshot { image, .. } = event {
return Some(image.clone());
}
}
None
});
if let (Some(screenshot), Some(plot_location)) = (screenshot, self.plot_location) {
// for a full size application, we should put this in a different thread,
// so that the GUI doesn't lag during saving
let pixels_per_point = ui.ctx().pixels_per_point();
let plot = screenshot.region(&plot_location, Some(pixels_per_point));
// save the plot to png
image::save_buffer(
&self.picked_path,
plot.as_raw(),
plot.width() as u32,
plot.height() as u32,
image::ColorType::Rgba8,
)
.unwrap();
log::info!("Image saved to {:?}.", self.picked_path);
}
}
fn save(&mut self, _storage: &mut dyn Storage) {
save_serial_settings(&self.serial_devices);
if let Err(err) = self.gui_conf.save(&APP_INFO, PREFERENCES_KEY) {
log::error!("gui settings save failed: {:?}", err);
}
}
}
================================================
FILE: src/io.rs
================================================
use std::error::Error;
use std::path::PathBuf;
use csv::{ReaderBuilder, WriterBuilder};
use crate::DataContainer;
/// A set of options for saving data to a CSV file.
#[derive(Debug)]
pub struct FileOptions {
pub file_path: PathBuf,
pub save_absolute_time: bool,
pub save_raw_traffic: bool,
pub names: Vec,
}
pub fn open_from_csv(
data: &mut DataContainer,
csv_options: &mut FileOptions,
) -> Result, Box> {
let mut rdr = ReaderBuilder::new()
.has_headers(true)
.from_path(&csv_options.file_path)?;
csv_options.names = rdr
.headers()
.unwrap()
.into_iter()
.skip(1)
.map(|s| s.to_string())
.collect::>();
// Clear any existing data in the DataContainer
data.absolute_time.clear();
data.time.clear();
data.dataset = vec![vec![]; csv_options.names.len()];
let mut raw_data = vec![];
// Read and parse each record in the CSV
for result in rdr.records() {
let record = result?;
// Ensure the record has the correct number of fields
if record.len() != csv_options.names.len() + 1 {
return Err("CSV record does not match the expected number of columns".into());
}
// Parse the time field (first column)
let time_value = record.get(0).unwrap();
if csv_options.save_absolute_time {
data.absolute_time.push(time_value.parse()?);
} else {
data.time.push(time_value.parse()?);
}
// Parse the remaining columns and populate the dataset
for (i, value) in record.iter().skip(1).enumerate() {
if let Some(dataset_column) = data.dataset.get_mut(i) {
dataset_column.push(value.trim().parse().unwrap_or(0.0));
} else {
return Err("Unexpected number of data columns in the CSV".into());
}
}
// Join the row into a single string with ", " as delimiter and push to raw_data
let row = record.iter().collect::>().join(", ");
raw_data.push(row + "\n");
}
data.loaded_from_file = true;
Ok(raw_data)
}
pub fn save_to_csv(data: &DataContainer, csv_options: &FileOptions) -> Result<(), Box> {
let mut wtr = WriterBuilder::new()
.has_headers(false)
.from_path(&csv_options.file_path)?;
// serialize does not work, so we do it with a loop..
let mut header = vec!["Time [ms]".to_string()];
header.extend_from_slice(&csv_options.names);
wtr.write_record(header)?;
for j in 0..data.dataset[0].len() {
let time = if csv_options.save_absolute_time {
data.absolute_time[j].to_string()
} else {
data.time[j].to_string()
};
let mut data_to_write = vec![time];
for value in data.dataset.iter() {
data_to_write.push(value[j].to_string());
}
wtr.write_record(&data_to_write)?;
}
wtr.flush()?;
if csv_options.save_raw_traffic {
let mut path = csv_options.file_path.clone();
let mut file_name = path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string()
.replace(".csv", "");
file_name += "raw.csv";
path.set_file_name(file_name);
save_raw(data, &path)?
}
Ok(())
}
pub fn save_raw(data: &DataContainer, path: &PathBuf) -> Result<(), Box> {
let mut wtr = WriterBuilder::new().has_headers(false).from_path(path)?;
let header = vec![
"Time [ms]".to_string(),
"Abs Time [ms]".to_string(),
"Raw Traffic".to_string(),
];
wtr.write_record(header)?;
for j in 0..data.dataset[0].len() {
let mut data_to_write = vec![data.time[j].to_string(), data.absolute_time[j].to_string()];
data_to_write.push(data.raw_traffic[j].payload.clone());
wtr.write_record(&data_to_write)?;
}
wtr.flush()?;
Ok(())
}
================================================
FILE: src/main.rs
================================================
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
// hide console window on Windows in release
extern crate core;
extern crate csv;
extern crate preferences;
extern crate serde;
use crate::data::{DataContainer, GuiOutputDataContainer, Packet, SerialDirection};
use crate::gui::{load_gui_settings, GuiCommand, MyApp, RIGHT_PANEL_WIDTH};
use crate::io::{open_from_csv, save_to_csv, FileOptions};
use crate::serial::{load_serial_settings, serial_devices_thread, serial_thread, Device};
use crossbeam_channel::{select, Receiver, Sender};
use eframe::egui::{vec2, ViewportBuilder};
use eframe::{egui, icon_data};
use egui_plot::PlotPoint;
pub use gumdrop::Options;
use preferences::AppInfo;
use std::cmp::max;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;
mod color_picker;
mod custom_highlighter;
mod data;
mod gui;
mod io;
mod serial;
mod settings_window;
mod toggle;
mod update;
const APP_INFO: AppInfo = AppInfo {
name: "Serial Monitor",
author: "Linus Leo Stöckli",
};
const PREFERENCES_KEY: &str = "config/gui";
const PREFERENCES_KEY_SERIAL: &str = "config/serial_devices";
fn split(payload: &str) -> Vec {
let mut split_data: Vec<&str> = vec![];
for s in payload.split(':') {
split_data.extend(s.split(','));
}
split_data
.iter()
.map(|x| x.trim())
.flat_map(|x| x.parse::())
.collect()
}
fn console_text(show_timestamps: bool, show_sent_cmds: bool, packet: &Packet) -> Option {
match (show_sent_cmds, show_timestamps, &packet.direction) {
(true, true, _) => Some(format!(
"[{}] t + {:.3}s: {}\n",
packet.direction,
packet.relative_time as f32 / 1000.0,
packet.payload
)),
(true, false, _) => Some(format!("[{}]: {}\n", packet.direction, packet.payload)),
(false, true, SerialDirection::Receive) => Some(format!(
"t + {:.3}s: {}\n",
packet.relative_time as f32 / 1000.0,
packet.payload
)),
(false, false, SerialDirection::Receive) => Some(packet.payload.clone() + "\n"),
(_, _, _) => None,
}
}
fn main_thread(
sync_tx: Sender,
data_lock: Arc>,
raw_data_rx: Receiver,
save_rx: Receiver,
load_rx: Receiver,
load_names_tx: Sender>,
gui_cmd_rx: Receiver,
cli_column_labels: Vec,
) {
// reads data from mutex, samples and saves if needed
let mut data = DataContainer::default();
let mut failed_format_counter = 0;
let mut show_timestamps = true;
let mut show_sent_cmds = true;
let mut file_opened = false;
loop {
select! {
recv(raw_data_rx) -> packet => {
if let Ok(packet) = packet {
if !file_opened {
data.loaded_from_file = false;
if !packet.payload.is_empty() {
sync_tx.send(true).expect("unable to send sync tx");
data.raw_traffic.push(packet.clone());
if let Some(text) = console_text(show_timestamps, show_sent_cmds, &packet) {
// append prints
if let Ok(mut gui_data) = data_lock.write() {
gui_data.prints.push(text);
}
}
let split_data = split(&packet.payload);
if data.dataset.is_empty() || failed_format_counter > 10 {
// resetting dataset
data.time = vec![];
data.dataset = vec![vec![]; max(split_data.len(), 1)];
if let Ok(mut gui_data) = data_lock.write() {
gui_data.plots = (0..max(split_data.len(), 1))
.map(|i| (cli_column_labels.get(i).cloned().unwrap_or_else(|| format!("Column {i}")), vec![]))
.collect();
}
failed_format_counter = 0;
// log::error!("resetting dataset. split length = {}, length data.dataset = {}", split_data.len(), data.dataset.len());
} else if split_data.len() == data.dataset.len() {
// appending data
for (i, set) in data.dataset.iter_mut().enumerate() {
set.push(split_data[i]);
failed_format_counter = 0;
}
data.time.push(packet.relative_time);
data.absolute_time.push(packet.absolute_time);
// appending data for GUI thread
if let Ok(mut gui_data) = data_lock.write() {
// append plot-points
for ((_label, graph), data_i) in
gui_data.plots.iter_mut().zip(&data.dataset)
{
if data.time.len() == data_i.len() {
if let Some(y) = data_i.last() {
graph.push(PlotPoint {
x: packet.relative_time / 1000.0,
y: *y as f64,
});
}
}
}
}
if data.time.len() != data.dataset[0].len() {
// resetting dataset
data.time = vec![];
data.dataset = vec![vec![]; max(split_data.len(), 1)];
if let Ok(mut gui_data) = data_lock.write() {
gui_data.prints = vec!["".to_string(); max(split_data.len(), 1)];
gui_data.plots = (0..max(split_data.len(), 1))
.map(|i| (format!("Column {i}"), vec![]))
.collect();
}
}
} else {
// not same length
failed_format_counter += 1;
// log::error!("not same length in main! length split_data = {}, length data.dataset = {}", split_data.len(), data.dataset.len())
}
}
}
}
}
recv(gui_cmd_rx) -> msg => {
if let Ok(cmd) = msg {
match cmd {
GuiCommand::Clear => {
data = DataContainer::default();
failed_format_counter = 0;
if let Ok(mut gui_data) = data_lock.write() {
*gui_data = GuiOutputDataContainer::default();
}
}
GuiCommand::ShowTimestamps(val) => {
show_timestamps = val;
}
GuiCommand::ShowSentTraffic(val) => {
show_sent_cmds = val;
}
}
}
}
recv(load_rx) -> msg => {
if let Ok(fp) = msg {
// load logic
if let Some(file_ending) = fp.extension() {
match file_ending.to_str().unwrap() {
"csv" => {
file_opened = true;
let mut file_options = FileOptions {
file_path: fp.clone(),
save_absolute_time: false,
save_raw_traffic: false,
names: vec![],
};
match open_from_csv(&mut data, &mut file_options) {
Ok(raw_data) => {
log::info!("opened {:?}", fp);
if let Ok(mut gui_data) = data_lock.write() {
gui_data.prints = raw_data;
gui_data.plots = (0..data.dataset.len())
.map(|i| (file_options.names[i].to_string(), vec![]))
.collect();
// append plot-points
for ((_label, graph), data_i) in
gui_data.plots.iter_mut().zip(&data.dataset)
{
for (y,t) in data_i.iter().zip(data.time.iter()) {
graph.push(PlotPoint {
x: *t / 1000.0,
y: *y as f64 ,
});
}
}
}
load_names_tx
.send(file_options.names)
.expect("unable to send names on channel after loading");
}
Err(err) => {
file_opened = false;
log::error!("failed opening {:?}: {:?}", fp, err);
}
};
}
_ => {
file_opened = false;
log::error!("file not supported: {:?} \n Close the file to connect to a spectrometer or open another file.", fp);
continue;
}
}
} else {
file_opened = false;
}
} else {
file_opened = false;
}
}
recv(save_rx) -> msg => {
if let Ok(csv_options) = msg {
match save_to_csv(&data, &csv_options) {
Ok(_) => {
log::info!("saved data file to {:?} ", csv_options.file_path);
}
Err(e) => {
log::error!(
"failed to save file to {:?}: {:?}",
csv_options.file_path,
e
);
}
}
}
}
default(Duration::from_millis(10)) => {
// occasionally push data to GUI
}
}
}
}
fn parse_databits(s: &str) -> Result {
let d: u8 = s
.parse()
.map_err(|_e| format!("databits not a number: {s}"))?;
Ok(serialport::DataBits::try_from(d).map_err(|_e| format!("invalid databits: {s}"))?)
}
fn parse_flow(s: &str) -> Result {
match s {
"none" => Ok(serialport::FlowControl::None),
"soft" => Ok(serialport::FlowControl::Software),
"hard" => Ok(serialport::FlowControl::Hardware),
_ => Err(format!("invalid flow-control: {s}")),
}
}
fn parse_stopbits(s: &str) -> Result {
let d: u8 = s
.parse()
.map_err(|_e| format!("stopbits not a number: {s}"))?;
Ok(serialport::StopBits::try_from(d).map_err(|_e| format!("invalid stopbits: {s}"))?)
}
fn parse_parity(s: &str) -> Result {
match s {
"none" => Ok(serialport::Parity::None),
"odd" => Ok(serialport::Parity::Odd),
"even" => Ok(serialport::Parity::Even),
_ => Err(format!("invalid parity setting: {s}")),
}
}
fn parse_color(s: &str) -> Result {
Ok(egui::ecolor::HexColor::from_str_without_hash(s)
.map_err(|e| format!("invalid color {s:?}: {e:?}"))?
.color())
}
#[derive(Debug, Options)]
struct CliOptions {
/// Serial port device to open on startup
#[options(free)]
device: Option,
/// Baudrate (default=9600)
#[options(short = "b")]
baudrate: Option,
/// Data bits (5, 6, 7, default=8)
#[options(short = "d", parse(try_from_str = "parse_databits"))]
databits: Option,
/// Flow conrol (hard, soft, default=none)
#[options(short = "f", parse(try_from_str = "parse_flow"))]
flow: Option,
/// Stop bits (default=1, 2)
#[options(short = "s", parse(try_from_str = "parse_stopbits"))]
stopbits: Option,
/// Parity (odd, even, default=none)
#[options(short = "p", parse(try_from_str = "parse_parity"))]
parity: Option,
/// Load data from a file instead of a serial port
#[options(short = "F")]
file: Option,
/// Column labels, can be specified multiple times for more columns
#[options(no_short, long = "column")]
column_labels: Vec,
/// Column colors (hex color without #), can be specified multiple times for more columns
#[options(no_short, long = "color", parse(try_from_str = "parse_color"))]
column_colors: Vec,
help: bool,
}
fn main() {
egui_logger::builder().init().unwrap();
let args = CliOptions::parse_args_default_or_exit();
let gui_settings = load_gui_settings();
let saved_serial_device_configs = load_serial_settings();
let mut device = Device::default();
if let Some(name) = args.device {
device.name = name;
}
if let Some(baudrate) = args.baudrate {
device.baud_rate = baudrate;
}
if let Some(databits) = args.databits {
device.data_bits = databits;
}
if let Some(flow) = args.flow {
device.flow_control = flow;
}
if let Some(stopbits) = args.stopbits {
device.stop_bits = stopbits;
}
if let Some(parity) = args.parity {
device.parity = parity;
}
let device_lock = Arc::new(RwLock::new(device));
let devices_lock = Arc::new(RwLock::new(vec![gui_settings.device.clone()]));
let data_lock = Arc::new(RwLock::new(GuiOutputDataContainer::default()));
let connected_lock = Arc::new(RwLock::new(false));
let (save_tx, save_rx): (Sender, Receiver) =
crossbeam_channel::unbounded();
let (load_tx, load_rx): (Sender, Receiver) = crossbeam_channel::unbounded();
let (loaded_names_tx, loaded_names_rx): (Sender>, Receiver>) =
crossbeam_channel::unbounded();
let (send_tx, send_rx): (Sender, Receiver) = crossbeam_channel::unbounded();
let (gui_cmd_tx, gui_cmd_rx): (Sender, Receiver) =
crossbeam_channel::unbounded();
let (raw_data_tx, raw_data_rx): (Sender, Receiver) =
crossbeam_channel::unbounded();
let (sync_tx, sync_rx): (Sender, Receiver) = crossbeam_channel::unbounded();
let serial_2_devices_lock = devices_lock.clone();
let _serial_devices_thread_handler = thread::spawn(|| {
serial_devices_thread(serial_2_devices_lock);
});
let serial_device_lock = device_lock.clone();
let serial_devices_lock = devices_lock.clone();
let serial_connected_lock = connected_lock.clone();
let _serial_thread_handler = thread::spawn(|| {
serial_thread(
send_rx,
raw_data_tx,
serial_device_lock,
serial_devices_lock,
serial_connected_lock,
);
});
let main_data_lock = data_lock.clone();
let _main_thread_handler = thread::spawn(|| {
main_thread(
sync_tx,
main_data_lock,
raw_data_rx,
save_rx,
load_rx,
loaded_names_tx,
gui_cmd_rx,
args.column_labels,
);
});
if let Some(file) = args.file {
load_tx.send(file).expect("failed to send file");
}
let options = eframe::NativeOptions {
viewport: ViewportBuilder::default()
.with_drag_and_drop(true)
.with_inner_size(vec2(gui_settings.x, gui_settings.y))
.with_min_inner_size(vec2(2.0 * RIGHT_PANEL_WIDTH, 2.0 * RIGHT_PANEL_WIDTH))
.with_icon(
icon_data::from_png_bytes(&include_bytes!("../icons/icon.png")[..]).unwrap(),
),
..Default::default()
};
let gui_data_lock = data_lock;
let gui_device_lock = device_lock;
let gui_devices_lock = devices_lock;
let gui_connected_lock = connected_lock;
if let Err(e) = eframe::run_native(
"Serial Monitor",
options,
Box::new(|ctx| {
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
ctx.egui_ctx.set_fonts(fonts);
ctx.egui_ctx.set_theme(gui_settings.theme_preference);
egui_extras::install_image_loaders(&ctx.egui_ctx);
let repaint_signal = ctx.egui_ctx.clone();
thread::spawn(move || loop {
if sync_rx.recv().is_ok() {
repaint_signal.request_repaint();
}
});
Ok(Box::new(MyApp::new(
ctx,
gui_data_lock,
gui_device_lock,
gui_devices_lock,
saved_serial_device_configs,
gui_connected_lock,
gui_settings,
save_tx,
load_tx,
loaded_names_rx,
send_tx,
gui_cmd_tx,
args.column_colors,
)))
}),
) {
log::error!("{e:?}");
}
}
================================================
FILE: src/serial.rs
================================================
use crossbeam_channel::{Receiver, Sender};
use eframe::egui::Color32;
use preferences::Preferences;
use serde::{Deserialize, Serialize};
use serialport::{DataBits, FlowControl, Parity, SerialPort, StopBits};
use std::io::{BufRead, BufReader};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use crate::color_picker::COLORS;
use crate::data::{get_epoch_ms, SerialDirection};
use crate::{Packet, APP_INFO, PREFERENCES_KEY_SERIAL};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerialDevices {
pub devices: Vec,
pub labels: Vec>,
pub highlight_labels: Vec>,
pub colors: Vec>,
pub color_vals: Vec>,
pub number_of_plots: Vec,
pub number_of_highlights: Vec,
}
impl Default for SerialDevices {
fn default() -> Self {
SerialDevices {
devices: vec![Device::default()],
labels: vec![vec!["Column 0".to_string()]],
highlight_labels: vec![vec!["".to_string()]],
colors: vec![vec![COLORS[0]]],
color_vals: vec![vec![0.0]],
number_of_plots: vec![1],
number_of_highlights: vec![1],
}
}
}
pub fn load_serial_settings() -> SerialDevices {
SerialDevices::load(&APP_INFO, PREFERENCES_KEY_SERIAL).unwrap_or_else(|_| {
let serial_configs = SerialDevices::default();
// save default settings
save_serial_settings(&serial_configs);
serial_configs
})
}
pub fn save_serial_settings(serial_configs: &SerialDevices) {
if serial_configs
.save(&APP_INFO, PREFERENCES_KEY_SERIAL)
.is_err()
{
log::error!("failed to save gui_settings");
}
}
pub fn clear_serial_settings() {
let serial_configs = SerialDevices::default();
if serial_configs
.save(&APP_INFO, PREFERENCES_KEY_SERIAL)
.is_err()
{
log::error!("failed to clear gui_settings");
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Device {
pub name: String,
pub baud_rate: u32,
pub data_bits: DataBits,
pub flow_control: FlowControl,
pub parity: Parity,
pub stop_bits: StopBits,
pub timeout: Duration,
}
impl Default for Device {
fn default() -> Self {
Device {
name: "".to_string(),
baud_rate: 9600,
data_bits: DataBits::Eight,
flow_control: FlowControl::None,
parity: Parity::None,
stop_bits: StopBits::One,
timeout: Duration::from_millis(0),
}
}
}
pub fn serial_devices_thread(devices_lock: Arc>>) {
loop {
if let Ok(mut write_guard) = devices_lock.write() {
*write_guard = available_devices();
}
std::thread::sleep(Duration::from_millis(500));
}
}
fn serial_write(
port: &mut BufReader>,
cmd: &[u8],
) -> Result {
let write_port = port.get_mut();
write_port.write(cmd)
}
fn serial_read(
port: &mut BufReader>,
serial_buf: &mut String,
) -> Result {
port.read_line(serial_buf)
}
pub fn serial_thread(
send_rx: Receiver,
raw_data_tx: Sender,
device_lock: Arc>,
devices_lock: Arc>>,
connected_lock: Arc>,
) {
let mut last_connected_device = Device::default();
loop {
#[cfg(not(target_os = "ios"))]
let _not_awake = keepawake::Builder::default()
.display(false)
.reason("Serial Connection")
.app_name("Serial Monitor")
//.app_reverse_domain("io.github.myprog")
.create();
if let Ok(mut connected) = connected_lock.write() {
*connected = false;
}
let device = get_device(&devices_lock, &device_lock, &last_connected_device);
let mut port = match serialport::new(&device.name, device.baud_rate)
.timeout(Duration::from_millis(100))
.open()
{
Ok(p) => {
if let Ok(mut connected) = connected_lock.write() {
*connected = true;
}
log::info!(
"Connected to serial port: {} @ baud = {}",
device.name,
device.baud_rate
);
BufReader::new(p)
}
Err(err) => {
if let Ok(mut write_guard) = device_lock.write() {
write_guard.name.clear();
}
log::error!("Error connecting: {}", err);
continue;
}
};
let t_zero = Instant::now();
#[cfg(not(target_os = "ios"))]
let _awake = keepawake::Builder::default()
.display(true)
.reason("Serial Connection")
.app_name("Serial Monitor")
//.app_reverse_domain("io.github.myprog")
.create();
'connected_loop: loop {
if disconnected(
&device,
&device_lock,
&devices_lock,
&mut last_connected_device,
) {
break 'connected_loop;
}
perform_writes(&mut port, &send_rx, &raw_data_tx, t_zero);
perform_reads(&mut port, &raw_data_tx, t_zero);
}
std::mem::drop(port);
}
}
fn available_devices() -> Vec {
serialport::available_ports()
.unwrap()
.iter()
.map(|p| p.port_name.clone())
.collect()
}
fn get_device(
devices_lock: &Arc>>,
device_lock: &Arc>,
last_connected_device: &Device,
) -> Device {
loop {
let devices = available_devices();
if let Ok(mut write_guard) = devices_lock.write() {
*write_guard = devices.clone();
}
// do reconnect
if devices.contains(&last_connected_device.name) {
if let Ok(mut device) = device_lock.write() {
device.name = last_connected_device.name.clone();
device.baud_rate = last_connected_device.baud_rate;
}
return last_connected_device.clone();
}
if let Ok(device) = device_lock.read() {
if devices.contains(&device.name) {
return device.clone();
}
}
std::thread::sleep(Duration::from_millis(100));
}
}
fn disconnected(
device: &Device,
device_lock: &Arc>,
devices_lock: &Arc>>,
last_connected_device: &mut Device,
) -> bool {
// disconnection by button press
if let Ok(read_guard) = device_lock.try_read() {
if device.name != read_guard.name {
*last_connected_device = Device::default();
log::info!("Disconnected from serial port: {}", device.name);
return true;
}
}
if let Ok(devices) = devices_lock.try_read() {
// other types of disconnection (e.g. unplugging, power down)
if !devices.contains(&device.name) {
if let Ok(mut write_guard) = device_lock.try_write() {
write_guard.name.clear();
}
*last_connected_device = device.clone();
log::error!("Device has disconnected from serial port: {}", device.name);
return true;
};
}
false
}
fn perform_writes(
port: &mut BufReader>,
send_rx: &Receiver,
raw_data_tx: &Sender,
t_zero: Instant,
) {
if let Ok(cmd) = send_rx.try_recv() {
if let Err(e) = serial_write(port, cmd.as_bytes()) {
log::error!("Error sending command: {e}");
return;
}
let packet = Packet {
relative_time: Instant::now().duration_since(t_zero).as_millis() as f64,
absolute_time: get_epoch_ms() as f64,
direction: SerialDirection::Send,
payload: cmd,
};
raw_data_tx
.send(packet)
.expect("failed to send raw data (cmd)");
}
}
fn perform_reads(
port: &mut BufReader>,
raw_data_tx: &Sender,
t_zero: Instant,
) {
let mut buf = "".to_string();
match serial_read(port, &mut buf) {
Ok(_) => {
let delimiter = if buf.contains("\r\n") {
"\r\n"
} else if buf.contains("\r") {
"\r"
} else if buf.contains("\n") {
"\n"
} else {
"\0\0"
};
buf.split_terminator(delimiter).for_each(|s| {
let packet = Packet {
relative_time: Instant::now().duration_since(t_zero).as_millis() as f64,
absolute_time: get_epoch_ms() as f64,
direction: SerialDirection::Receive,
payload: s.to_owned(),
};
raw_data_tx.send(packet).expect("failed to send raw data");
});
}
// Timeout is ok, just means there is no data to read
Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => {}
Err(e) => {
log::error!("Error reading: {:?}", e);
}
}
}
================================================
FILE: src/settings_window.rs
================================================
use crate::gui::GuiSettingsContainer;
#[cfg(feature = "self_update")]
use crate::update::{check_update, update};
use eframe::egui;
use eframe::egui::{Align2, InnerResponse, Vec2};
use egui_theme_switch::ThemeSwitch;
#[cfg(feature = "self_update")]
use self_update::restart::restart;
#[cfg(feature = "self_update")]
use self_update::update::Release;
#[cfg(feature = "self_update")]
use semver::Version;
pub fn settings_window(
ui: &mut egui::Ui,
gui_conf: &mut GuiSettingsContainer,
#[cfg(feature = "self_update")] new_release: &mut Option,
settings_window_open: &mut bool,
update_text: &mut String,
) -> Option>> {
egui::Window::new("Settings")
.fixed_size(Vec2 { x: 600.0, y: 200.0 })
.anchor(Align2::CENTER_CENTER, Vec2 { x: 0.0, y: 0.0 })
.collapsible(false)
.show(ui, |ui| {
egui::Grid::new("theme settings")
.striped(true)
.show(ui, |ui| {
if ui
.add(ThemeSwitch::new(&mut gui_conf.theme_preference))
.changed()
{
ui.ctx().set_theme(gui_conf.theme_preference);
};
gui_conf.dark_mode = ui.ctx().theme() == egui::Theme::Dark;
ui.end_row();
ui.end_row();
});
#[cfg(feature = "self_update")]
egui::Grid::new("update settings")
.striped(true)
.show(ui, |ui| {
if ui.button("Check for Updates").clicked() {
*new_release = check_update();
}
let current_version = Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
ui.label(format!("Current version: {}", current_version));
ui.end_row();
if let Some(r) = &new_release {
ui.label(format!("New release: {}", r.version));
ui.end_row();
if ui.button("Update").clicked() {
match update(r.clone()) {
Ok(_) => {
log::info!("Update done. {} >> {}", current_version, r.version);
*new_release = None;
*update_text =
"Update done. Please Restart Application.".to_string();
}
Err(err) => {
log::error!("{}", err);
}
}
}
} else {
ui.label("");
ui.end_row();
ui.horizontal(|ui| {
ui.disable();
let _ = ui.button("Update");
});
ui.label("You have the latest version");
}
});
ui.label(update_text.clone());
ui.horizontal(|ui| {
ui.horizontal(|ui| {
if !update_text.is_empty() {
ui.disable();
};
if ui.button("Exit Settings").clicked() {
*settings_window_open = false;
*update_text = "".to_string();
}
});
#[cfg(feature = "self_update")]
if !update_text.is_empty() && ui.button("Restart").clicked() {
restart();
ui.ctx().request_repaint(); // Optional: Request repaint for immediate feedback
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
});
})
}
================================================
FILE: src/toggle.rs
================================================
//! Source code example of how to create your own widget.
//! This is meant to be read as a tutorial, hence the plethora of comments.
use eframe::egui;
use eframe::egui::StrokeKind;
/// iOS-style toggle switch:
///
/// ``` text
/// _____________
/// / /.....\
/// | |.......|
/// \_______\_____/
/// ```
///
/// ## Example:
/// ``` ignore
/// toggle_ui(ui, &mut my_bool);
/// ```
pub fn toggle_ui(ui: &mut egui::Ui, on: &mut bool) -> egui::Response {
// Widget code can be broken up in four steps:
// 1. Decide a size for the widget
// 2. Allocate space for it
// 3. Handle interactions with the widget (if any)
// 4. Paint the widget
// 1. Deciding widget size:
// You can query the `ui` how much space is available,
// but in this example we have a fixed size widget based on the height of a standard button:
let desired_size = ui.spacing().interact_size.y * egui::vec2(2.0, 1.0);
// 2. Allocating space:
// This is where we get a region of the screen assigned.
// We also tell the Ui to sense clicks in the allocated region.
let (rect, mut response) = ui.allocate_exact_size(desired_size, egui::Sense::click());
// 3. Interact: Time to check for clicks!
if response.clicked() {
*on = !*on;
response.mark_changed(); // report back that the value changed
}
// Attach some meta-data to the response which can be used by screen readers:
response.widget_info(|| {
egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, "")
});
// 4. Paint!
// Make sure we need to paint:
if ui.is_rect_visible(rect) {
// Let's ask for a simple animation from egui.
// egui keeps track of changes in the boolean associated with the id and
// returns an animated value in the 0-1 range for how much "on" we are.
let how_on = ui.ctx().animate_bool(response.id, *on);
// We will follow the current style by asking
// "how should something that is being interacted with be painted?".
// This will, for instance, give us different colors when the widget is hovered or clicked.
let visuals = ui.style().interact_selectable(&response, *on);
// All coordinates are in absolute screen coordinates so we use `rect` to place the elements.
let rect = rect.expand(visuals.expansion);
let radius = 0.5 * rect.height();
ui.painter().rect(
rect,
radius,
visuals.bg_fill,
visuals.bg_stroke,
StrokeKind::Middle,
);
// Paint the circle, animating it from left to right with `how_on`:
let circle_x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), how_on);
let center = egui::pos2(circle_x, rect.center().y);
ui.painter()
.circle(center, 0.75 * radius, visuals.bg_fill, visuals.fg_stroke);
}
// All done! Return the interaction response so the user can check what happened
// (hovered, clicked, ...) and maybe show a tooltip:
response
}
/// Here is the same code again, but a bit more compact:
#[allow(dead_code)]
fn toggle_ui_compact(ui: &mut egui::Ui, on: &mut bool) -> egui::Response {
let desired_size = ui.spacing().interact_size.y * egui::vec2(2.0, 1.0);
let (rect, mut response) = ui.allocate_exact_size(desired_size, egui::Sense::click());
if response.clicked() {
*on = !*on;
response.mark_changed();
}
response.widget_info(|| {
egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, "")
});
if ui.is_rect_visible(rect) {
let how_on = ui.ctx().animate_bool(response.id, *on);
let visuals = ui.style().interact_selectable(&response, *on);
let rect = rect.expand(visuals.expansion);
let radius = 0.5 * rect.height();
ui.painter().rect(
rect,
radius,
visuals.bg_fill,
visuals.bg_stroke,
StrokeKind::Middle,
);
let circle_x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), how_on);
let center = egui::pos2(circle_x, rect.center().y);
ui.painter()
.circle(center, 0.75 * radius, visuals.bg_fill, visuals.fg_stroke);
}
response
}
// A wrapper that allows the more idiomatic usage pattern: `ui.add(toggle(&mut my_bool))`
/// iOS-style toggle switch.
///
/// ## Example:
/// ``` ignore
/// ui.add(toggle(&mut my_bool));
/// ```
pub fn toggle(on: &mut bool) -> impl egui::Widget + '_ {
move |ui: &mut egui::Ui| toggle_ui(ui, on)
}
================================================
FILE: src/update.rs
================================================
#![cfg(feature = "self_update")]
use self_update::self_replace;
use self_update::update::Release;
use semver::Version;
use std::path::Path;
use std::{env, fs, io};
const REPO_OWNER: &str = "hacknus";
const REPO_NAME: &str = "serial-monitor-rust";
const MACOS_APP_NAME: &str = "Serial Monitor.app";
/// method to copy the complete directory `src` to `dest` but skipping the binary `binary_name`
/// since we have to use `self-replace` for that.
fn copy_dir(src: &Path, dest: &Path, binary_name: &str) -> io::Result<()> {
// Ensure the destination directory exists
if !dest.exists() {
fs::create_dir_all(dest)?;
}
// Iterate through entries in the source directory
for entry in fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
let dest_path = dest.join(entry.file_name());
if path.is_dir() {
// Recursively copy subdirectories
copy_dir(&path, &dest_path, binary_name)?;
} else if let Some(file_name) = path.file_name() {
if file_name != binary_name {
// Copy files except for the binary
fs::copy(&path, &dest_path)?;
}
}
}
Ok(())
}
/// Function to check for updates and return the latest one, if it is more recent than the current version
pub fn check_update() -> Option {
if let Ok(builder) = self_update::backends::github::ReleaseList::configure()
.repo_owner(REPO_OWNER)
.repo_name(REPO_NAME)
.build()
{
if let Ok(releases) = builder.fetch() {
let current_version = Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
return releases
.iter()
.filter_map(|release| {
let release_version_str = release
.version
.strip_prefix("v")
.unwrap_or(&release.version);
Version::parse(release_version_str)
.ok()
.map(|parsed_version| (parsed_version, release))
})
.filter(|(parsed_version, _)| parsed_version > ¤t_version) // Compare versions
.max_by(|(a, _), (b, _)| a.cmp(b)) // Find the max version
.map(|(_, release)| release.clone()); // Return the release
}
}
None
}
/// custom update function for use with bundles
pub fn update(release: Release) -> Result<(), Box> {
let target_asset = if cfg!(target_os = "windows") {
release.asset_for(self_update::get_target(), Some("exe"))
} else if cfg!(target_os = "linux") {
release.asset_for(self_update::get_target(), Some("bin"))
} else {
release.asset_for(self_update::get_target(), None)
}
.ok_or("No asset found")?;
let tmp_archive_dir = tempfile::TempDir::new()?;
let tmp_archive_path = tmp_archive_dir.path().join(&target_asset.name);
let tmp_archive = fs::File::create(&tmp_archive_path)?;
self_update::Download::from_url(&target_asset.download_url)
.set_header(reqwest::header::ACCEPT, "application/octet-stream".parse()?)
.download_to(&tmp_archive)?;
self_update::Extract::from_source(&tmp_archive_path).extract_into(tmp_archive_dir.path())?;
let new_exe = if cfg!(target_os = "windows") {
let binary = env::current_exe()?
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
tmp_archive_dir.path().join(binary)
} else if cfg!(target_os = "macos") {
let binary = env::current_exe()?
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
let app_dir = env::current_exe()?
.parent()
.unwrap()
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf();
let app_name = app_dir
.clone()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
let _ = copy_dir(&tmp_archive_dir.path().join(&app_name), &app_dir, &binary);
// MACOS_APP_NAME either needs to be hardcoded or extracted from the downloaded and
// extracted archive, but we cannot just assume that the parent directory of the
// currently running executable is equal to the app name - this is especially not
// the case if we run the code with `cargo run`.
tmp_archive_dir
.path()
.join(format!("{}/Contents/MacOS/{}", MACOS_APP_NAME, binary))
} else if cfg!(target_os = "linux") {
let binary = env::current_exe()?
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
tmp_archive_dir.path().join(binary)
} else {
return Err("Running on unsupported OS".into());
};
self_replace::self_replace(new_exe)?;
Ok(())
}
================================================
FILE: wix/License.rtf
================================================
{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Courier New;}}
{\colortbl ;\red0\green0\blue255;}
{\*\generator Riched20 10.0.15063}\viewkind4\uc1
\pard\sa180\qc\fs24\lang9 GNU GENERAL PUBLIC LICENSE\line Version 3, 29 June 2007\par
\pard\sa180 Copyright (C) 2007 Free Software Foundation, Inc. {{\field{\*\fldinst{HYPERLINK http://fsf.org/ }}{\fldrslt{http://fsf.org/\ul0\cf0}}}}\f0\fs24 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\par
\pard\sa180\qc Preamble\par
\pard\sa180 The GNU General Public License is a free, copyleft license for software and other kinds of works.\par
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.\par
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.\par
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.\par
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.\par
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\par
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.\par
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.\par
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.\par
The precise terms and conditions for copying, distribution and modification follow.\par
\pard\sa180\qc TERMS AND CONDITIONS\par
\pard\fi-360\li360\sa180\tx360 0.\tab Definitions.\par
\pard\sa180 "This License" refers to version 3 of the GNU General Public License.\par
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\par
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.\par
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.\par
A "covered work" means either the unmodified Program or a work based on the Program.\par
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\par
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\par
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\par
\pard\fi-360\li360\sa180\tx360 1.\tab Source Code.\par
\pard\sa180 The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.\par
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\par
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\par
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\par
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\par
The Corresponding Source for a work in source code form is that same work.\par
\pard\fi-360\li360\sa180\tx360 2.\tab Basic Permissions.\par
\pard\sa180 All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\par
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\par
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\par
\pard\fi-360\li360\sa180\tx360 3.\tab Protecting Users' Legal Rights From Anti-Circumvention Law.\par
\pard\sa180 No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\par
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.\par
\pard\fi-360\li360\sa180\tx360 4.\tab Conveying Verbatim Copies.\par
\pard\sa180 You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\par
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\par
\pard\fi-360\li360\sa180\tx360 5.\tab Conveying Modified Source Versions.\par
\pard\sa180 You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\par
\pard
{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}}
\fi-360\li720\sa180 The work must carry prominent notices stating that you modified\lang1033 \lang9 it, and giving a relevant date.\par
{\pntext\f0 b.\tab}The work must carry prominent notices stating that it is released under this License and any conditions added under section\lang1033 \lang9 7.\lang1033 \lang9 This requirement modifies the requirement in section 4 to\lang1033 \lang9 "keep intact all notices".\par
{\pntext\f0 c.\tab}You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7\lang1033 \lang9 additional terms, to the whole of the work, and all its parts,\lang1033 \lang9 regardless of how they are packaged. This License gives no\lang1033 \lang9 permission to license the work in any other way, but it does not\lang1033 \lang9 invalidate such permission if you have separately received it. \par
{\pntext\f0 d.\tab}If the work has interactive user interfaces, each must display\lang1033 \lang9 Appropriate Legal Notices; however, if the Program has interactive\lang1033 \lang9 interfaces that do not display Appropriate Legal Notices, your\lang1033 \lang9 work need not make them do so.\par
\pard\sa180 A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\par
\pard\fi-360\li360\sa180\tx360 6.\tab Conveying Non-Source Forms.\par
\pard\sa180 You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\par
\pard
{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}}
\fi-360\li720\sa180 Convey the object code in, or embodied in, a physical product\line (including a physical distribution medium), accompanied by the\line Corresponding Source fixed on a durable physical medium\line customarily used for software interchange.\par
{\pntext\f0 b.\tab}Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no\line more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.\par
{\pntext\f0 c.\tab}Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.\par
{\pntext\f0 d.\tab}Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.\par
{\pntext\f0 e.\tab}Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.\par
\pard\sa180 A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\par
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\par
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\par
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\par
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\par
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\par
\pard\fi-360\li360\sa180\tx360 7.\tab Additional Terms.\par
\pard\sa180 "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\par
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\par
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\par
\pard
{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}}
\fi-360\li720\sa180 Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\par
{\pntext\f0 b.\tab}Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or\par
{\pntext\f0 c.\tab}Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or\par
{\pntext\f0 d.\tab}Limiting the use for publicity purposes of names of licensors or authors of the material; or\par
{\pntext\f0 e.\tab}Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\par
{\pntext\f0 f.\tab}Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.\par
\pard\sa180 All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\par
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\par
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\par
\pard\fi-360\li360\sa180\tx360 8.\tab Termination.\par
\pard\sa180 You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\par
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\par
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.\par
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\par
\pard\fi-360\li360\sa180\tx360 9.\tab Acceptance Not Required for Having Copies.\par
\pard\sa180 You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\par
\pard\fi-360\li360\sa180\tx360 10.\tab Automatic Licensing of Downstream Recipients.\par
\pard\sa180 Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.\par
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\par
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\par
\pard\fi-360\li360\sa180\tx360 11.\tab Patents.\par
\pard\sa180 A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".\par
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\par
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\par
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\par
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\par
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\par
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\par
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\par
\pard\fi-360\li360\sa180\tx360 12.\tab No Surrender of Others' Freedom.\par
\pard\sa180 If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\par
\pard\fi-360\li360\sa180\tx360 13.\tab Use with the GNU Affero General Public License.\par
\pard\sa180 Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.\par
\pard\fi-360\li360\sa180\tx360 14.\tab Revised Versions of this License.\par
\pard\sa180 The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\par
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.\par
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\par
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\par
\pard\fi-360\li360\sa180\tx360 15.\tab Disclaimer of Warranty.\par
\pard\sa180 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par
\pard\fi-360\li360\sa180\tx360 16.\tab Limitation of Liability.\par
\pard\sa180 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\par
\pard\fi-360\li360\sa180\tx360 17.\tab Interpretation of Sections 15 and 16.\par
\pard\sa180 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.\par
\pard\sa180\qc END OF TERMS AND CONDITIONS\par
\line How to Apply These Terms to Your New Programs\par
\pard\sa180 If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.\par
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.\par
\f1 \line Copyright (C) [copyright-year] [copyright-holder]\par
\line This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\line\line This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\line\line You should have received a copy of the GNU General Public License along with this program. If not, see <{{\field{\*\fldinst{HYPERLINK "http://www.gnu.org/licenses/"}}{\fldrslt{http://www.gnu.org/licenses/\ul0\cf0}}}}\f1\fs24 >.\par
\f0 Also add information on how to contact you by electronic and paper mail.\par
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:\par
\f1 [product-name] Copyright (C) [copyright-year] [copyright-holder]\par
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details.\f0\par
The hypothetical commands {\f1 'show w'} and {\f1 'show c'} should show the appropriate arts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".\par
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see {{\field{\*\fldinst{HYPERLINK http://www.gnu.org/licenses/ }}{\fldrslt{http://www.gnu.org/licenses/\ul0\cf0}}}}\f0\fs24 .\par
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read {{\field{\*\fldinst{HYPERLINK http://www.gnu.org/philosophy/why-not-lgpl.html }}{\fldrslt{http://www.gnu.org/philosophy/why-not-lgpl.html\ul0\cf0}}}}\f0\fs24 .\par
}
================================================
FILE: wix/main.wxs
================================================