132 Commits
0.2.0 ... 0.5.0

Author SHA1 Message Date
Tom A. Wagner
3dd4623ab9 Release v0.5.0 2023-09-28 13:38:07 +02:00
Denis Drakhnia
20f64595ac pipewire connection: Show banner if disconnected 2023-09-28 12:25:04 +03:00
Tom Wagner
7d6aae70c5 pipewire connection: restart the outer loop 2023-09-27 14:08:10 +03:00
Denis Drakhnia
94323510aa pipewire connection: Reconnection to PipeWire server 2023-09-27 10:54:32 +00:00
Tom A. Wagner
f0da839383 ci: Update gnome runtime to gnome 45 2023-09-26 18:28:02 +00:00
Tom A. Wagner
7e29462b6f flatpak: Update to gnome 45 2023-09-26 18:28:02 +00:00
Tom A. Wagner
bc006fe393 ui: Add "About" window to display version, authors, license, etc.
This adds a new adw::AboutWindow containing information about version, authors, license, links etc.
It is opened via a new menu button in the toolbar, which opens a menu containing an "About Helvum" button.

The version and authors are pulled from the Cargo.toml file.
2023-09-19 16:12:29 +02:00
Tom A. Wagner
e92c77f2b1 Add flatpak builder folders to .gitignore 2023-09-19 15:30:58 +02:00
Tom A. Wagner
b9929ba776 Run rustfmt 2023-09-19 08:27:11 +02:00
Tom A. Wagner
1d51b12061 ci: Update gnome runtime image 2023-09-18 19:21:48 +02:00
Tom A. Wagner
1db39fb71f css: Add more padding to node and port names, remove column spacing in ports grid 2023-09-18 18:02:00 +02:00
Tom A. Wagner
89f417f260 node: Remove transparency in dark mode, improve contrast to graphview in light mode 2023-08-28 20:58:54 +02:00
Tom A. Wagner
2343ef824e application: Set PreferDark color scheme
Run the app in dark mode by default, unless the user explicitely wants light mode.
2023-08-28 20:58:54 +02:00
Tom A. Wagner
24724b330f readme: Update requirements section to reflect port to libadwaita 2023-08-28 20:58:54 +02:00
Tom A. Wagner
1707e84c4c readme: Update Screenshot to reflect libadwaita port and redesign 2023-08-28 20:58:54 +02:00
Tom A. Wagner
8aade39aeb css: Improve padding of node title and ports 2023-08-28 20:58:54 +02:00
Tom A. Wagner
0cb40f5cab Node: Rework adding of ports, sort ports and hide seperator when node has no ports
This reworks the adding of a port to nodes, to avoid assigning multiple nodes
to the same grid cell when a node which was not the last in its column has previously
been removed. Instead, the grid is emptied and repopulated each time.

This also lets us sort the nodes each time by name.

Finally, this hides the seperator if a node has no nodes, as it is unneeded.
2023-08-28 20:58:54 +02:00
Tom A. Wagner
4ed7e1f4be graph: Redesign nodes and ports
Nodes now have a background using the libadwaita .card style class.

Ports now have a circular handle, which is positioned on the edge of the node so that half of the circle sticks out.
Ports are also no longer themed like a button and don't receive a color based on the guessed media type, in a future commit,
the handle will be colored instead.
2023-08-28 20:58:54 +02:00
Tom A. Wagner
af4051c3c2 ui: Port to libadwaita
This ports the application to libadwaita, enabling us to use the libadwaita stylesheet and
widgets to better implement the Gnome Human Interface Guidelines.
2023-08-28 19:47:37 +02:00
Tom A. Wagner
6fd3691733 ci: Rework CI to run in flatpak 2023-08-21 14:16:46 +02:00
Tom A. Wagner
189288bb56 deps: Update to pipewire-rs 0.7.1
Fixes an issue where bindgen fails to load the clang library in some cases
2023-08-21 12:14:28 +02:00
Tom A. Wagner
c5adb2eca2 flatpak: Update to gnome 44 runtime and llvm 15 2023-08-20 14:24:02 +02:00
Tom A. Wagner
7f754b207c Color links and ports according to their formats
Format params for links and ports are now being watched for in the pipewire connection code.

The parsed media type is then set on the port widget / link object
and they are colored accordingly.

For ports, which were already colored before, this new method of determining the media type
should be more reliable and accurate as this uses the real Format/EnumFormat
params instead of parsing optional properties.
2023-08-20 10:55:25 +02:00
Tom A. Wagner
ba73d8cdcc pipewire connection: Move module to mod.rs in its folder 2023-08-18 10:24:54 +02:00
Tom A. Wagner
fdcc6146ec Release 0.4.1 2023-08-18 09:12:49 +02:00
Tom A. Wagner
14f17b3f24 Stop using deprecated gtk::StyleContext::add_provider_for_display function 2023-08-17 21:00:18 +02:00
Tom A. Wagner
48cc5672fd ci: Update ci to latest Fedora and Rust 2023-08-17 20:22:10 +02:00
Tom A. Wagner
bf5c7e4636 Update dependencies 2023-08-17 20:14:23 +02:00
Tom A. Wagner
7145c83ae1 graph: Draw "fake" link during port drag-and-drop to visualize link creating
Cursor movement during port drag-and-drop on the graph is now being tracked
and a link is drawn from the dragged port to the cursor.

If the cursor is hovering a port the source port can link to,
the second end of the link instead attaches to the ports link anchor
so that the link "snaps" to the linkable port.
2023-08-04 14:58:05 +02:00
Tom A. Wagner
d99c5e253c port: Rework how port drag-and-drop is handled
Instead of different types for each direction to avoid linking ports
of the same direction, we reject the drop early if directions of both
ports are the same.

The direction check is easily extendable to also deny links between
ports of different media types in the future.
2023-08-03 21:40:35 +02:00
Tom A. Wagner
15df88a0af graph: Move port link anchor calculation into port widget 2023-08-03 21:12:15 +02:00
Tom A. Wagner
0b3b124cdf graph: Refactor graph item management into new graph_manager object
The graph widgets management (watching a glib receiver, adding and removing
Nodes, Ports and Links) currently done in the `Application` and `GraphView`
objects has been extracted into a new GraphManager object, which watches the
receiver instead, pushes changes directly to the widgets, and reacts to their signals.

This seperates widget logic and management logic cleanly instead of both
being mixed into the GraphView, and also reduces the code size for the
Application object.
2023-08-01 09:15:40 +02:00
Tom A. Wagner
a9ad1cccf0 fix clippy warnings 2023-08-01 09:13:16 +02:00
Tom A. Wagner
7a9bc84b8b port: Use glib::properties derive macro for properties 2023-08-01 09:09:57 +02:00
Tom A. Wagner
27b76b0fe1 node: Use glib::properties derive macro for properties 2023-08-01 09:09:46 +02:00
Tom A. Wagner
f986902929 graph: Move link data into new GObject subclass 2023-07-27 14:16:42 +02:00
Tom A. Wagner
475a83fab7 Restructure view module into ui folder, graph specific widgets into graph subfolder 2023-07-27 14:16:42 +02:00
Tom A. Wagner
0e699288e1 graph: Allocate proper size to nodes when zoomed
Previously, the allocated height and width to a node on the graph was divided by the zoom factor,
to account for the changed size from them being zoomed.

To zoom each node, we `size_allocate` it with a GskTransform that scales it.

However, using a scaling transform to allocate the node already takes care of scaling the height and
width, so us also scaling the height and width manually means we were overcompensating.

This resulted in the allocation becoming to big when zooming out, and to small when zooming in.

This is observable as labels will become smaller when zooming in and ellipsize their content.

The commit removes the extra manual scaling so nodes get allocated properly when zoomed.
2023-07-27 13:14:03 +02:00
Carlos Martín Nieto
84570f44bf port: add the dragged port as the drag icon
This makes it the port label follows your cursor around instead of the generic
text document icon that doesn't make a lot of sense here.
2023-03-14 19:52:54 +01:00
Tom A. Wagner
69257ffa09 Release v0.4.0 2023-02-12 21:23:12 +01:00
Tom A. Wagner
91d7e10bdc view: Improve layout of labels on nodes and ports
This sets a maximum width of 20 chars on labels on nodes and ports.
Longer labels will wrap to a second line.

For labels longer than two lines, the label is ellipsized at the end.
The full label can still be viewed via hovering for a tooltip.

Co-authored-by: Roger Roger <me@rogerrogert.de>
2023-02-12 20:58:34 +01:00
Roger Roger
fe05282f5a Prefer description over nick for node name 2023-02-12 20:38:18 +01:00
Tom A. Wagner
146fb65dc5 Update gtk and glib dependencies 2023-02-12 20:23:56 +01:00
Tom A. Wagner
4ed52bb00d flatpak: Update to gnome 43 2023-02-12 13:30:49 +01:00
Tom A. Wagner
24b1d0dff7 Update dependencies 2023-02-12 13:14:53 +01:00
Josh Veitch-Michaelis
b5f9a706b7 Update README.md for gnome 42 2022-12-03 02:36:15 +00:00
Tom A. Wagner
b115e6f50c zooming: Add support for zooming via zoom gesture (two finger touchpad/touchscreen zooming) 2022-11-09 19:21:32 +00:00
Tom A. Wagner
1d10c179cc zooming: Add support for zooming by scrolling while holding CTRL 2022-11-09 19:21:32 +00:00
Tom A. Wagner
727326aca4 zooming: Add a control widget that allows for changing the zoom level of the graph
The new widget sits in the headerbar, and allows for changing the zoom level with "+" and "-" buttons, via text entry, and a dropdown where a list of predefined levels can be clicked.
2022-11-09 19:21:32 +00:00
Tom A. Wagner
56e73d33c9 graphview: Make graph widget zoomable via a zoom-factor property.
This adds a `zoom-factor` property.

Changing the property zooms in the entire widget including background, nodes, links, etc.
2022-11-09 19:21:32 +00:00
Tom A. Wagner
bcef1300ca ci: Update to fedora 36 and latest rust 2022-11-09 17:50:04 +01:00
Tom A. Wagner
4bf586e66c view: graph: Implement gtk::Scrollable and do not render content outside the displayed area
The graphview widget now implements the gtk::Scrollable interface, so it is no longer wrapped inside a gtk::Viewport when used in a gtk::ScrollWindow anymore.
Instead, it repositions its content itself when scrolled, and also skips rendering any content that is not inside the visible area, which should improve performance
when the graph becomes big.

This commit also makes the canvas a fixed size, with much space to each side from the starting area.
This will hopefully improve user experience, as the view can now be moved around more freely, and nodes can be dragged left and above the starting area.
2022-08-25 13:07:37 +02:00
Tom A. Wagner
637ce104df view: Node,Port: Store pipewire Id as property on node, and make its name a property too. 2022-07-21 19:14:17 +02:00
Tom A. Wagner
df72a68815 graphview: draw the background grid via CSS instead of manually with cairo
This makes gtk draw the background grid for us via CSS, instead of manually drawing each line via cairo.

This improves performance, as the grid may now be drawn via GPU, and gets rid of the custom drawing code we had.
2022-05-03 14:04:54 +02:00
Tom A. Wagner
52e48cc0a7 Adjust license headers to reflect gpl-3.0-only license. 2022-04-19 10:14:01 +02:00
Tom A. Wagner
9f3754150a flatpak: Update runtime to gnome 42 2022-04-11 10:01:13 +02:00
Tom A. Wagner
6ce5b2e367 Update dependencies 2022-03-22 18:08:02 +01:00
Tom A. Wagner
094681637e Release v0.3.4 2022-02-02 10:08:12 +01:00
Tom A. Wagner
6f92fbdb8f readme: Add flathub badge 2022-01-31 13:32:03 +01:00
Tom A. Wagner
e38426c09f Update dependencies, fix segmentation fault
Updating glib to 0.15.4 fixes a segmentation fault that could occur when logging a message with glib structured logging.
2022-01-31 13:17:55 +01:00
Tom A. Wagner
85e249cb32 Release 0.3.3 2022-01-28 13:49:49 +01:00
Tom A. Wagner
c54aed2e14 Update dependencies 2022-01-28 13:49:49 +01:00
Tom A. Wagner
6da232debf meson: Fix incorrect output file name
This fixes a typo from 96c61e43 that caused the binary to be generated with the wrong name.
2022-01-28 13:48:46 +01:00
Tom A. Wagner
96c61e43d2 meson: Remove custom build scripts 2022-01-28 13:01:35 +01:00
Tom A. Wagner
872ef7890d readme: Credit gtk-rust-template 2022-01-28 12:11:32 +01:00
Tom A. Wagner
76ad8d11d7 Change application id to org.pipewire.Helvum 2022-01-28 10:14:21 +01:00
Tom A. Wagner
4075b66865 deps: Update gtk-rs to latest release 2022-01-17 12:00:00 +01:00
Tom A. Wagner
96182826e4 logging: Use glib as log backend instead of env_logger.
This makes log output use the same logger as gtk itself and as most other gtk applications
2022-01-11 12:15:14 +01:00
Mihai Fufezan
e1fbb0cf49 Use gtk4-update-icon-cache instead of gtk3 one 2021-12-18 19:50:39 +00:00
Alireza Haghshenas
3653f2bb11 Emphasized that the flatpak-builder command needs be run inside a local clone of the project 2021-12-10 04:34:49 +00:00
Tom A. Wagner
56523f1b30 docs: Add documentation for making a release 2021-12-01 19:56:17 +01:00
Tom A. Wagner
7818bed159 Add appstream metadata file 2021-12-01 19:56:17 +01:00
Tom A. Wagner
c1ec56e115 Release 0.3.2 2021-11-30 18:25:58 +01:00
Tom A. Wagner
110e9ef67f meson: Add dist script to vendor cargo dependencies for offline builds 2021-11-30 09:59:56 +01:00
Jan Beich
3c507683b7 build-aux: relax shebang in cargo.sh after 7b1b5ea336
/bin/sh: /bin/bash: not found
2021-11-27 21:57:03 +00:00
Thomas Rosendal
1d1f8bd3d7 Add instruction to add the flatpak remote 'flathub' 2021-11-25 07:59:45 +00:00
Sebastian Grabowski
b25f6f9abb Update the extension versions in flatpak build instructions to 21.08
The extensions need to match the SDK version, that was updated to
org.gnome.Sdk//41 in Commit e5e02b13. (Version 41 is based on
org.freedesktop.Sdk//21.08)
2021-11-24 17:03:23 +01:00
Tom A. Wagner
2d51ea677e ci: use more recent fd.o ci-templates 2021-11-24 16:11:16 +01:00
Tom A. Wagner
beb03d8b09 Update CI container for rust 1.56 2021-11-24 16:11:16 +01:00
Tom A. Wagner
502cf4476b gtk4dep: bump to 4.4 for fixed gtk_pick when using affine transform
This will be needed in a later commit for zooming in on the canvas using an affine (scaling) transformation matrix
2021-11-24 16:11:16 +01:00
Tom A. Wagner
eac973da15 Swap to rust 2021 edition and move rustc version check from meson.build to Cargo.toml 2021-11-24 16:11:16 +01:00
Tom A. Wagner
82a3e4f900 graphview: draw background automatically
This removes the manual painting of the background via cairo and adds the correct color to CSS instead,
which should hopefully improve performance as we do less cpu painting like this.
2021-11-24 16:11:16 +01:00
Suchipi
2cfc8e2e6f Update build instructions to match changes in e5e02b1387 2021-11-19 01:10:14 +00:00
Tom A. Wagner
e5e02b1387 flatpak: Update to gnome runtime 41 2021-11-17 19:49:52 +01:00
Tom A. Wagner
396363cef1 README: Update screenshot 2021-11-17 19:49:52 +01:00
Tom A. Wagner
c887d77f64 graphview: Use #808080 as link color
For good contrast in both dark and light mode, the link color is now a semi-light gray instead of complete black, which had bad contrast in dark mode and good constrast in light mode.

Later, we can seperate color palettes for light and dark mode, but only together with a dark mode toggle button or system-wide darkmode toggle.
2021-11-13 20:32:40 +01:00
Tom A. Wagner
54d7ca83ae graphview: Define link and grid colors in style.css
Previously, these were defined directly in the code,
but defining them in the css helps seperating theming and behaviour
and makes the colors easier to tweak.
2021-11-13 20:08:47 +01:00
Tom A. Wagner
7b1b5ea336 build: fix and improve cargo.sh
cargo.sh previously used bash features but only used `sh` in the shebang,
and also did not properly quote some variables to avoid splitting/globbing from happening.

Also, `-euo pilefail` is now set to avoid other errors that might come up.
2021-10-26 10:04:07 +02:00
Tom A. Wagner
729d4e1555 CI: Update container 2021-10-13 12:11:06 +02:00
Tom A. Wagner
ce6cab8134 Run rustfmt 2021-10-13 12:01:22 +02:00
Tom A. Wagner
8a552d0712 graphview: Add missing }; to fix build. 2021-10-13 11:56:46 +02:00
halfbro
f76235674c Add small control point offset to links that connect from right to left (loopbacks) 2021-10-13 09:11:10 +00:00
Tom A. Wagner
92dcfd61a1 Add gpl snippets to the start of each rust source file. 2021-10-03 11:27:36 +02:00
Tom A. Wagner
02e58e9bfa LICENSE: Replace outdated and edited GPL with the lastest stock version.
The old license file contained project specific edits, but editing the GPL text is disallowed by the fsf.
The new file also contains updated links.
2021-10-03 11:14:30 +02:00
Tom A. Wagner
958fa15230 Release 0.3.1 2021-09-30 08:45:11 +02:00
Tom A. Wagner
e9753dd078 Update dependencies 2021-09-30 08:45:00 +02:00
Tom A. Wagner
dfb1b754c7 Add and install icons.
This adds one new app icon and one new symbolic icon, and makes meson install these to the appropriate
directories, and adds an appropriate entry in the .desktop file.
2021-09-30 08:28:06 +02:00
Tom A. Wagner
497da8b953 graphview: Do not crash when the position of a node not on the graph is requested
While the position of a node not on the graph should never be requested, this seems to occur sometimes,
so instead of panicking, we only log an error now, or ignore that node if it wasn't
important.
2021-09-11 15:03:03 +02:00
Tom A. Wagner
da5da90352 Add .desktop file
This adds a .desktop file (without icon for now), which will automatically be installed when
`meson install` is run.
2021-08-29 18:41:09 +02:00
Tom A. Wagner
a8bfd8383e buildsystem: Move to meson for building the project
Meson will allow us to:
- Verify the used rust compiler is recent enough
- Install ressources such as a .desktop files, icons, etc.
2021-08-29 17:28:55 +02:00
Tom A. Wagner
7ef8677c4c readme: move screenshot.png into docs/ folder 2021-08-29 16:56:56 +02:00
Roger Roger
487dc3b2d3 Group nodes into columns by major type 2021-08-18 07:23:50 +00:00
Tom A. Wagner
2ee7bca68a Release 0.3.0 2021-08-08 09:51:55 +02:00
Tom A. Wagner
494d3a383f Update dependencies 2021-08-08 09:51:42 +02:00
Tom A. Wagner
b719e0d2ec Add simple flatpak manifest 2021-07-22 11:35:12 +02:00
Tom A. Wagner
f64a936dd9 Update dependencies 2021-07-18 09:58:39 +02:00
Tom A. Wagner
179665778d view: Draw a dashed line for links that are not active 2021-07-08 13:37:37 +02:00
er888kh
be9339472e First nodes that GraphView::add_node creates, get pushed
to the left side of the screen. So by adding a constant offset,
we can avoid having possible links that are partly out of the view
just after starting the program
2021-07-06 09:39:34 +00:00
Tom A. Wagner
e29ffdeea8 view: Port: Do not inherit from gtk::Button
We do not need any button functionality, so it is more appropriate to inherit directly from gtk::Widget
2021-07-06 11:01:20 +02:00
Tom A. Wagner
add1a96b75 Deduplicate port dragging code and add some extra logging 2021-07-06 10:23:20 +02:00
Tom A. Wagner
9445e173f9 view: ports: Improve linking between ports.
Links can now created by dragging in both directions, so now from an input port to an output port, too.
The drag-n-drop handlers now use dedicated types for each direction, so that no mismatched things can be dropped on each other.
2021-06-28 13:54:53 +02:00
Tom A. Wagner
58794fe123 Remove unneeded Rc, Port is now a refcounted gobject 2021-06-28 13:29:46 +02:00
Tom A. Wagner
8d6fbe2997 Remove outdated doc comment 2021-06-28 13:29:46 +02:00
Tom A. Wagner
b0bf5e5281 Slightly improve logging 2021-06-28 13:29:46 +02:00
Tom A. Wagner
edc4064009 graphview: Place link curve control points more dynamically
Control points are now offset by half the x distance of the start and end points instead of a constant,
which makes the curve scale better with varying distance.
2021-06-28 10:48:09 +02:00
Tom A. Wagner
58cdcd859b graphview: Draw links in front of nodes, instead of behind them. 2021-06-26 12:34:48 +02:00
Tom A. Wagner
7977481689 Fix some pedantic clippy warnings 2021-06-26 12:10:36 +02:00
Tom A. Wagner
f09fd596c8 Update dependencies§ 2021-06-25 15:40:17 +02:00
Tom A. Wagner
1247b29bae Use pipewire from crates.io
The newest release contains everything we need, so we can use the crates.io version again.
2021-06-25 15:38:54 +02:00
Tom A. Wagner
74ffb06b40 Use gtk4-rs from crates.io instead from their git.
The gtk4 crate finally had its first release, so we no longer have to use their git repository directly.
2021-06-25 15:06:41 +02:00
Tom A. Wagner
81467154d9 Readme.md: Replace "Packages" section with repology badge, add license section 2021-06-07 16:03:50 +02:00
Tom A. Wagner
46b2175a78 Release v0.2.1 2021-06-06 20:44:10 +02:00
Tom A. Wagner
9aeea6b108 Update dependencies 2021-06-06 20:42:00 +02:00
Tom A. Wagner
c8f94ae302 Use link info callback instead of properties to get ids.
While the properties for a links node ids are not always set, they always are in the link info.

Also, the work done in this commit will easily allow to get the format of links and ports later,
so that we can get the format of them much more reliably,
and we can also get notified of changes to an existing global via the info callback.
2021-06-06 20:28:19 +02:00
Tom A. Wagner
92101d860c Update ARCHITECTURE.md to reflect state having moved to the pipewire thread 2021-06-06 09:36:57 +02:00
Tom A. Wagner
907ef328d2 Move state to pipewire thread instead of the gtk thread.
This will allow easier state-keeping later, when setting up info-listeners on structs.
2021-06-06 09:20:07 +02:00
Tom A. Wagner
118c1ca28c Get node_from, node_to ids from state instead of props when a new link appears.
This is more reliable than assuming the link carries the id of its nodes, as there have been cases where a link was created without those
properties set.
Instead, we can just pull them from the state via the port ids of the link.
2021-06-04 10:30:31 +02:00
Tom A. Wagner
a9aec985b0 pipewire: Edit fixme about port media type 2021-05-25 22:45:13 +02:00
Tom A. Wagner
dce228ff60 Update dependencies
Glib MainContext is now aquired manually because a change in gtk-rs would lead to
a panic when attaching the receiver otherwise, because gtk::init() doesn't
"leak" the default main context anymore.
2021-05-22 14:00:51 +02:00
Jan Vanmullem
24fd54affe references both AUR release & git packages 2021-05-18 16:25:49 +02:00
Mathias Rav
3cd19f2d1d When dragging a node, don't snap its top-left corner to the cursor
Revamp the node dragging implementation, moving it into the GraphView
widget.

When a drag is initiated, the node widget's current position is stored.
Whenever the drag gesture is updated, the node widget's position is set
by adding the relative drag vector to the position at the start of the
drag.

A drag gesture on the node widget rather than the GraphView widget was
considered, but this seems to lead to a weird flickering effect when the
node is moved while the drag gesture on the node is active.

To avoid interfering with the drag handlers on the ports, check if the
GraphView drag gesture targets a port, in which case the handler does
nothing.
2021-05-10 18:21:00 +00:00
Mathias Rav
6d60095da8 Move CSS to its own file 2021-05-09 21:53:27 +02:00
46 changed files with 7349 additions and 1699 deletions

3
.gitignore vendored
View File

@@ -1,2 +1,5 @@
/.flatpak
/.flatpak-builder
/.vscode
/_build
/target

View File

@@ -1,75 +1,53 @@
include:
- project: 'freedesktop/ci-templates' # the project to include from
ref: '98f557799157ebb0395cf11d40f01f61fbbace20' # git ref of that project
file: '/templates/fedora.yml' # the actual file to include
stages:
- prepare
- build
- lint
- test
- extras
.flatpak:
image: 'quay.io/gnome_infrastructure/gnome-runtime-images:gnome-45'
variables:
FDO_UPSTREAM_REPO: 'ryuukyu/helvum'
FLATPAK_BUILD_DIR: _build
MANIFEST_PATH: build-aux/org.pipewire.Helvum.json
APP_FLATPAK_MODULE: Helvum
before_script:
- flatpak --version
- flatpak info org.gnome.Platform
- flatpak info org.gnome.Sdk
- flatpak info org.freedesktop.Sdk.Extension.llvm16
- flatpak info org.freedesktop.Sdk.Extension.rust-stable
- flatpak-builder --version
# Version and tag for our current container
.fedora:
variables:
FDO_DISTRIBUTION_VERSION: '34'
# Update this to trigger a container rebuild
FDO_DISTRIBUTION_TAG: '2021-05-06.0'
build-fedora-container:
extends:
- .fedora # our template job above
- .fdo.container-build@fedora@x86_64 # the CI template
stage: prepare
variables:
# clang-devel: required by rust bindgen
FDO_DISTRIBUTION_PACKAGES: >-
rust
cargo
rustfmt
clippy
pipewire-devel
gtk4-devel
clang-devel
rustfmt:
extends:
- .fedora
- .fdo.distribution-image@fedora
stage: lint
build:
stage: build
extends: .flatpak
script:
- cargo fmt --version
- cargo fmt -- --color=always --check
- flatpak-builder --keep-build-dirs --user --disable-rofiles-fuse ${FLATPAK_BUILD_DIR} ${MANIFEST_PATH}
test-stable:
extends:
- .fedora
- .fdo.distribution-image@fedora
stage: test
script:
- rustc --version
- cargo build --color=always --all-targets
- cargo test --color=always
rustdoc:
extends:
- .fedora
- .fdo.distribution-image@fedora
stage: extras
variables:
RUSTDOCFLAGS: '-Dwarnings'
script:
- rustdoc --version
- cargo doc --no-deps
# TODO: Run meson test
clippy:
extends:
- .fedora
- .fdo.distribution-image@fedora
stage: extras
stage: lint
extends: .flatpak
script:
- cargo clippy --version
- cargo clippy --color=always --all-targets -- -D warnings
- flatpak-builder --keep-build-dirs --user --disable-rofiles-fuse --stop-at=${APP_FLATPAK_MODULE} ${FLATPAK_BUILD_DIR} ${MANIFEST_PATH}
- >-
flatpak-builder --run ${FLATPAK_BUILD_DIR} ${MANIFEST_PATH}
cargo clippy --color=always --all-targets -- -D warnings
rustfmt:
stage: lint
image: "rust:slim" # TODO: Check image
script:
- rustup component add rustfmt
- rustc -Vv && cargo -Vv
- cargo fmt --version
- cargo fmt --all -- --color=always --check
rustdoc:
stage: lint
extends: .flatpak
script:
- flatpak-builder --keep-build-dirs --user --disable-rofiles-fuse --stop-at=${APP_FLATPAK_MODULE} ${FLATPAK_BUILD_DIR} ${MANIFEST_PATH}
- >-
flatpak-builder --run ${FLATPAK_BUILD_DIR} ${MANIFEST_PATH}
env RUSTDOCFLAGS=-Dwarnings cargo doc --no-deps

848
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,12 @@
[package]
name = "helvum"
version = "0.2.0"
authors = ["Tom A. Wagner <tom.a.wagner@protonmail.com>"]
edition = "2018"
version = "0.5.0"
authors = ["Tom Wagner <tom.a.wagner@protonmail.com>"]
edition = "2021"
rust-version = "1.70"
license = "GPL-3.0-only"
description = "A GTK patchbay for pipewire"
repository = "https://gitlab.freedesktop.org/ryuukyu/helvum"
repository = "https://gitlab.freedesktop.org/pipewire/helvum"
readme = "README.md"
keywords = ["pipewire", "gtk", "patchbay", "gui", "utility"]
categories = ["gui", "multimedia"]
@@ -13,10 +14,12 @@ categories = ["gui", "multimedia"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
gtk = { git = "https://github.com/gtk-rs/gtk4-rs/", package = "gtk4" }
pipewire = { git = "https://gitlab.freedesktop.org/pipewire/pipewire-rs", branch = "main" }
pipewire = "0.7.1"
adw = { version = "0.5", package = "libadwaita", features = ["v1_3"] }
glib = { version = "0.18", features = ["log"] }
log = "0.4.11"
env_logger = "0.8.2"
once_cell = "1.7.2"
libc = "0.2"

14
LICENSE
View File

@@ -1,7 +1,7 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@@ -631,8 +631,8 @@ 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.
Helvum
Copyright (C) 2020 Ryuukyu
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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
@@ -645,14 +645,14 @@ the "copyright" line and a pointer to where the full notice is found.
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 <http://www.gnu.org/licenses/>.
along with this program. If not, see <https://www.gnu.org/licenses/>.
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:
Helvum Copyright (C) 2020 Ryuukyu
<program> Copyright (C) <year> <name of author>
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.
@@ -664,11 +664,11 @@ 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
<http://www.gnu.org/licenses/>.
<https://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -1,6 +1,10 @@
Helvum is a GTK-based patchbay for pipewire, inspired by the JACK tool [catia](https://kx.studio/Applications:Catia).
![Screenshot](screenshot.png)
![Screenshot](docs/screenshot.png)
<a href="https://flathub.org/apps/details/org.pipewire.Helvum"><img src="https://flathub.org/assets/badges/flathub-badge-en.png" width="300"/></a>
<a href="https://repology.org/project/helvum/versions"><img src="https://repology.org/badge/vertical-allrepos/helvum.svg" width="300"/></a>
# Features planned
@@ -9,20 +13,51 @@ Helvum is a GTK-based patchbay for pipewire, inspired by the JACK tool [catia](h
More suggestions are welcome!
# Distribution packages
- ArchLinux: [aur/helvum-git](https://aur.archlinux.org/packages/helvum-git)
# Building
## Via flatpak
If you don't have the flathub repo in your remote-list for flatpak you will need to add that first:
```shell
$ flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
```
Then install the required flatpak platform and SDK, if you dont have them already:
```shell
$ flatpak install org.gnome.{Platform,Sdk}//45 org.freedesktop.Sdk.Extension.rust-stable//23.08 org.freedesktop.Sdk.Extension.llvm16//23.08
```
To compile and install as a flatpak, clone the project, change to the project directory, and run:
```shell
$ flatpak-builder --install flatpak-build/ build-aux/org.pipewire.Helvum.json
```
You can then run the app via
```shell
$ flatpak run org.pipewire.Helvum
```
## Manually
For compilation, you will need:
- Meson
- An up-to-date rust toolchain
- `libclang-3.7` or higher
- `gtk-4.0` and `pipewire-0.3` development headers
- `libadwaita-1` and `libpipewire-0.3` development packages and their dependencies
To compile, run
To compile and install, run
$ cargo build --release
```shell
$ meson setup build && cd build
$ meson compile
$ meson install
```
in the repository root.
The resulting binary will be at `target/release/helvum`.
This will install the compiled project files into `/usr/local`.
# License and Credits
Helvum is distributed under the terms of the GPL3 license.
See LICENSE for more information.
Parts of the build system were taken from the [gtk-rust-template](https://gitlab.gnome.org/World/Rust/gtk-rust-template) project,
which is provided under the terms of the [MIT license](https://gitlab.gnome.org/World/Rust/gtk-rust-template/-/blob/master/LICENSE.md).

12
build-aux/dist-vendor.sh Normal file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
export DIST="$1"
export SOURCE_ROOT="$2"
cd "$SOURCE_ROOT"
mkdir "$DIST"/.cargo
cargo vendor > $DIST/.cargo/config
# Move vendor into dist tarball directory
mv vendor "$DIST"

View File

@@ -0,0 +1,40 @@
{
"id": "org.pipewire.Helvum",
"runtime": "org.gnome.Platform",
"runtime-version": "45",
"sdk": "org.gnome.Sdk",
"sdk-extensions": [
"org.freedesktop.Sdk.Extension.rust-stable",
"org.freedesktop.Sdk.Extension.llvm16"
],
"command": "helvum",
"finish-args": [
"--socket=fallback-x11",
"--socket=wayland",
"--device=dri",
"--share=ipc",
"--filesystem=xdg-run/pipewire-0"
],
"build-options": {
"append-path": "/usr/lib/sdk/rust-stable/bin:/usr/lib/sdk/llvm16/bin",
"prepend-ld-library-path": "/usr/lib/sdk/llvm16/lib",
"build-args": [
"--share=network"
]
},
"modules": [
{
"name": "Helvum",
"buildsystem": "meson",
"sources": [
{
"type": "dir",
"path": "../"
}
],
"config-opts": [
"-Dprofile=development"
]
}
]
}

9
data/icons/meson.build Normal file
View File

@@ -0,0 +1,9 @@
install_data(
'@0@.svg'.format(base_id),
install_dir: iconsdir / 'hicolor' / 'scalable' / 'apps'
)
install_data(
'@0@-symbolic.svg'.format(base_id),
install_dir: iconsdir / 'hicolor' / 'symbolic' / 'apps',
)

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 3.5 2.5 h 9 c 1.378906 0 2.5 1.121094 2.5 2.5 v 5 c 0 1.378906 -1.121094 2.5 -2.5 2.5 h -9 c -1.378906 0 -2.5 -1.121094 -2.5 -2.5 v -5 c 0 -1.378906 1.121094 -2.5 2.5 -2.5 z m 0 0" fill="#241f31" fill-rule="evenodd"/>
<g fill="none" stroke="#8a8891">
<path d="m 11 7.5 h -6"/>
<path d="m 5 7.5 c 0 -4.15625 -1.382812 -10.855469 -3.90625 -13.25" stroke-linecap="round" stroke-linejoin="bevel" stroke-width="4"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 589 B

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 187 KiB

View File

@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg height="128px" viewBox="0 0 128 128" width="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<linearGradient id="a" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#9a9996"/>
<stop offset="0.5" stop-color="#c0bfbc"/>
<stop offset="1" stop-color="#deddda"/>
</linearGradient>
<linearGradient id="b" x1="26.263471" x2="26.263586" xlink:href="#a" y1="24.848538" y2="37.1125"/>
<linearGradient id="c" gradientUnits="userSpaceOnUse" x1="7.39555839647" x2="120.60350567947" y1="82.86737386462" y2="82.86737386462">
<stop offset="0" stop-color="#5e5c64"/>
<stop offset="0.0384615" stop-color="#77767b"/>
<stop offset="0.0768555" stop-color="#5e5c64"/>
<stop offset="0.923077" stop-color="#5e5c64"/>
<stop offset="0.961538" stop-color="#77767b"/>
<stop offset="1" stop-color="#5e5c64"/>
</linearGradient>
<linearGradient id="d" gradientTransform="matrix(2.571428 0 0 2.454545 22.856596 -228.048061)" x1="16" x2="16" xlink:href="#a" y1="121.582512" y2="127.082512"/>
<linearGradient id="e" gradientTransform="matrix(2.571428 0 0 2.454545 22.856596 -253.563246)" x1="16" x2="16" xlink:href="#a" y1="121.582512" y2="127.082512"/>
<linearGradient id="f" gradientTransform="matrix(2.571428 0 0 2.454545 60.592569 -253.563246)" x1="16" x2="16" xlink:href="#a" y1="121.582512" y2="127.082512"/>
<linearGradient id="g" gradientTransform="matrix(2.571428 0 0 2.454545 60.592569 -228.048061)" x1="16" x2="16" xlink:href="#a" y1="121.582512" y2="127.082512"/>
<linearGradient id="h" gradientTransform="matrix(2.358499 0 0 2.251294 -11.472502 -204.652927)" gradientUnits="userSpaceOnUse" x1="12.5" x2="19.5" y1="113.832512" y2="113.832512">
<stop offset="0" stop-color="#c0bfbc"/>
<stop offset="0.5" stop-color="#9a9996"/>
<stop offset="1" stop-color="#c0bfbc"/>
</linearGradient>
<linearGradient id="i" gradientTransform="matrix(2.571428 0 0 2.454545 -14.879853 -228.048061)" x1="16" x2="16" xlink:href="#a" y1="121.582512" y2="127.082512"/>
<path d="m 34.519531 30.980469 c 0 3.386719 -3.695312 6.132812 -8.257812 6.132812 c -4.558594 0 -8.253907 -2.746093 -8.253907 -6.132812 s 3.695313 -6.132813 8.253907 -6.132813 c 4.5625 0 8.257812 2.746094 8.257812 6.132813 z m 0 0" fill="url(#b)" fill-rule="evenodd"/>
<path d="m 120.601562 82.867188 v 18.867187 c 0 5.226563 -4.207031 9.433594 -9.433593 9.433594 h -94.339844 c -5.226563 0 -9.433594 -4.207031 -9.433594 -9.433594 v -18.867187 z m 0 0" fill="url(#c)" fill-rule="evenodd"/>
<path d="m 16.828125 35.699219 c -5.226563 0 -9.433594 4.207031 -9.433594 9.433593 v 37.734376 c 0 5.226562 4.207031 9.433593 9.433594 9.433593 h 94.339844 c 5.226562 0 9.4375 -4.207031 9.4375 -9.433593 v -37.734376 c 0 -5.226562 -4.210938 -9.433593 -9.4375 -9.433593 h -76.648438 v 2.355469 h -16.511719 v -2.355469 z m 0 0" fill="#77767b" fill-rule="evenodd"/>
<path d="m 93.480469 76.378906 l -30.660157 -24.761718" fill="none" stroke="#77767b" stroke-linecap="square" stroke-width="3.74412"/>
<path d="m 64 58.691406 v 10.613282" fill="none" stroke="#999999" stroke-width="1.5"/>
<g fill-rule="evenodd">
<path d="m 75 77.132812 c 0 4.554688 -4.925781 8.25 -11 8.25 s -11 -3.695312 -11 -8.25 c 0 -4.558593 4.925781 -8.25 11 -8.25 s 11 3.691407 11 8.25 z m 0 0" fill="#e01b24"/>
<path d="m 73 77.132812 c 0 3.726563 -4.03125 6.75 -9 6.75 c -4.972656 0 -9 -3.023437 -9 -6.75 c 0 -3.730468 4.027344 -6.75 9 -6.75 c 4.96875 0 9 3.019532 9 6.75 z m 0 0" fill="url(#d)"/>
<path d="m 71 77.132812 c 0 2.898438 -3.132812 5.25 -7 5.25 s -7 -2.351562 -7 -5.25 c 0 -2.902343 3.132812 -5.25 7 -5.25 s 7 2.347657 7 5.25 z m 0 0" fill="#3d3846"/>
<path d="m 75 51.617188 c 0 4.554687 -4.925781 8.25 -11 8.25 s -11 -3.695313 -11 -8.25 c 0 -4.558594 4.925781 -8.25 11 -8.25 s 11 3.691406 11 8.25 z m 0 0" fill="#1c71d8"/>
<path d="m 73 51.617188 c 0 3.726562 -4.03125 6.75 -9 6.75 c -4.972656 0 -9 -3.023438 -9 -6.75 c 0 -3.730469 4.027344 -6.75 9 -6.75 c 4.96875 0 9 3.019531 9 6.75 z m 0 0" fill="url(#e)"/>
<path d="m 71 51.617188 c 0 2.898437 -3.132812 5.25 -7 5.25 s -7 -2.351563 -7 -5.25 c 0 -2.898438 3.132812 -5.25 7 -5.25 s 7 2.351562 7 5.25 z m 0 0" fill="#3d3846"/>
<path d="m 112.734375 51.617188 c 0 4.554687 -4.921875 8.25 -11 8.25 c -6.074219 0 -11 -3.695313 -11 -8.25 c 0 -4.558594 4.925781 -8.25 11 -8.25 c 6.078125 0 11 3.691406 11 8.25 z m 0 0" fill="#1c71d8"/>
<path d="m 110.734375 51.617188 c 0 3.726562 -4.027344 6.75 -9 6.75 c -4.96875 0 -9 -3.023438 -9 -6.75 c 0 -3.730469 4.03125 -6.75 9 -6.75 c 4.972656 0 9 3.019531 9 6.75 z m 0 0" fill="url(#f)"/>
<path d="m 108.734375 51.617188 c 0 2.898437 -3.132813 5.25 -7 5.25 c -3.863281 0 -7 -2.351563 -7 -5.25 c 0 -2.898438 3.136719 -5.25 7 -5.25 c 3.867187 0 7 2.351562 7 5.25 z m 0 0" fill="#3d3846"/>
</g>
<path d="m 101.734375 58.691406 v 10.613282" fill="none" stroke="#999999" stroke-width="1.5"/>
<path d="m 112.734375 77.132812 c 0 4.554688 -4.921875 8.25 -11 8.25 c -6.074219 0 -11 -3.695312 -11 -8.25 c 0 -4.558593 4.925781 -8.25 11 -8.25 c 6.078125 0 11 3.691407 11 8.25 z m 0 0" fill="#e01b24" fill-rule="evenodd"/>
<path d="m 110.734375 77.132812 c 0 3.726563 -4.027344 6.75 -9 6.75 c -4.96875 0 -9 -3.023437 -9 -6.75 c 0 -3.730468 4.03125 -6.75 9 -6.75 c 4.972656 0 9 3.019532 9 6.75 z m 0 0" fill="url(#g)" fill-rule="evenodd"/>
<path d="m 108.734375 77.132812 c 0 2.898438 -3.132813 5.25 -7 5.25 c -3.863281 0 -7 -2.351562 -7 -5.25 c 0 -2.902343 3.136719 -5.25 7 -5.25 c 3.867187 0 7 2.347657 7 5.25 z m 0 0" fill="#3d3846" fill-rule="evenodd"/>
<path d="m 26.261719 69.339844 v -10.648438" fill="none" stroke="#999999" stroke-width="1.5"/>
<path d="m 37.261719 52.515625 c 0 4.238281 -4.921875 7.671875 -11 7.671875 c -6.074219 0 -11 -3.433594 -11 -7.671875 c 0 -4.234375 4.925781 -7.671875 11 -7.671875 c 6.078125 0 11 3.4375 11 7.671875 z m 0 0" fill="#1c71d8" fill-rule="evenodd"/>
<path d="m 18.007812 30.980469 v 20.636719 c 0.003907 3.417968 3.699219 6.191406 8.253907 6.191406 c 4.554687 0 8.25 -2.765625 8.253906 -6.183594 c 0 0 0 -0.003906 0 -0.007812 v -20.636719 c -1.308594 2.597656 -4.589844 6.132812 -8.253906 6.132812 c -3.660157 0 -6.941407 -3.535156 -8.253907 -6.132812 z m 0 0" fill="url(#h)" fill-rule="evenodd"/>
<path d="m 37.261719 77.132812 c 0 4.554688 -4.921875 8.25 -11 8.25 c -6.074219 0 -11 -3.695312 -11 -8.25 c 0 -4.558593 4.925781 -8.25 11 -8.25 c 6.078125 0 11 3.691407 11 8.25 z m 0 0" fill="#e01b24" fill-rule="evenodd"/>
<path d="m 35.261719 77.132812 c 0 3.726563 -4.027344 6.75 -9 6.75 c -4.96875 0 -9 -3.023437 -9 -6.75 c 0 -3.730468 4.03125 -6.75 9 -6.75 c 4.972656 0 9 3.019532 9 6.75 z m 0 0" fill="url(#i)" fill-rule="evenodd"/>
<path d="m 33.261719 77.132812 c 0 2.898438 -3.132813 5.25 -7 5.25 c -3.863281 0 -7 -2.351562 -7 -5.25 c 0 -2.902343 3.136719 -5.25 7 -5.25 c 3.867187 0 7 2.347657 7 5.25 z m 0 0" fill="#3d3846" fill-rule="evenodd"/>
<path d="m 34.519531 30.980469 c 0 3.386719 -3.695312 6.132812 -8.257812 6.132812 c -4.558594 0 -8.253907 -2.746093 -8.253907 -6.132812 s 3.695313 -6.132813 8.253907 -6.132813 c 4.5625 0 8.257812 2.746094 8.257812 6.132813 z m 0 0" fill="#c0bfbc" fill-rule="evenodd"/>
<path d="m 30.980469 30.980469 c 0 1.953125 -2.113281 3.539062 -4.71875 3.539062 c -2.601563 0 -4.714844 -1.585937 -4.714844 -3.539062 s 2.113281 -3.539063 4.714844 -3.539063 c 2.605469 0 4.71875 1.585938 4.71875 3.539063 z m 0 0" fill="#1a5fb4" fill-rule="evenodd"/>
<path d="m 26.261719 30.980469 c 0 -7.074219 0.628906 -18.371094 -10.285157 -21.847657 c -11.828124 -3.765624 -33.882812 3 -33.882812 3" fill="none" stroke="#1a5fb4" stroke-width="9.434"/>
</svg>

After

Width:  |  Height:  |  Size: 7.7 KiB

49
data/meson.build Normal file
View File

@@ -0,0 +1,49 @@
subdir('icons')
desktop_conf = configuration_data()
desktop_conf.set('icon', base_id)
desktop_file = configure_file(
input: '@0@.desktop.in'.format(base_id),
output: '@BASENAME@',
configuration: desktop_conf
)
if desktop_file_validate.found()
test(
'validate-desktop',
desktop_file_validate,
args: [
desktop_file
],
)
endif
install_data(
desktop_file,
install_dir: datadir / 'applications'
)
appdata_conf = configuration_data()
appdata_conf.set('app-id', base_id)
appdata_file = configure_file(
input: '@0@.metainfo.xml.in'.format(base_id),
output: '@BASENAME@',
configuration: appdata_conf
)
# Validate Appdata
if appstream_util.found()
test(
'validate-appdata',
appstream_util,
args: [
'validate', '--nonet', appdata_file
],
)
endif
install_data(
appdata_file,
install_dir: datadir / 'metainfo'
)

View File

@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Helvum
GenericName=Patchbay
Comment=A patchbay for pipewire
Type=Application
Exec=helvum
Terminal=false
Categories=AudioVideo;Audio;Video;Midi;Settings;GNOME;GTK;
Icon=@icon@

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com> -->
<component type="desktop-application">
<id>@app-id@</id>
<metadata_license>CC-BY-SA-4.0</metadata_license>
<project_license>GPL-3.0-only</project_license>
<name>Helvum</name>
<summary>Patchbay for PipeWire</summary>
<description>
<p>
Helvum is a graphical patchbay for PipeWire.
It allows creating and removing connections between applications and/or devices to reroute
flow of audio, video and MIDI data to where it is needed.
</p>
</description>
<screenshots>
<screenshot type="default">
<image>https://gitlab.freedesktop.org/pipewire/helvum/-/raw/main/docs/screenshot.png</image>
</screenshot>
</screenshots>
<launchable type="desktop-id">@app-id@.desktop</launchable>
<url type="homepage">https://gitlab.freedesktop.org/pipewire/helvum</url>
<url type="bugtracker">https://gitlab.freedesktop.org/pipewire/helvum/-/issues</url>
<content_rating type="oars-1.0" />
<releases>
<release version="0.5.0" date="2023-09-28" />
<release version="0.4.1" date="2023-08-18" />
<release version="0.4.0" date="2023-02-12" />
<release version="0.3.4" date="2022-02-02" />
<release version="0.3.3" date="2022-01-28" />
<release version="0.3.2" date="2021-11-30" />
<release version="0.3.1" date="2021-09-30" />
<release version="0.3.0" date="2021-08-08" />
<release version="0.2.1" date="2021-06-06" />
<release version="0.2.0" date="2021-05-21" />
<release version="0.1.0" date="2021-01-12" />
</releases>
<kudos>
<kodu>HiDpiIcon</kodu>
<kudo>ModernToolkit</kudo>
</kudos>
<developer_name>Tom A. Wagner</developer_name>
<update_contact>tom.a.wagner@protonmail.com</update_contact>
</component>

View File

@@ -14,41 +14,37 @@ Helvum uses an architecture with the components laid out like this:
│ View │
└────┬─┘
Λ ┆
│<───── updates view
│ ┆
│ ┆<─ notifies of user input
│ ┆ (using signals)
│ ┆
│ ┆
│ V notifies of remote changes
┌┴────────────┐ via messages ┌──────────────────┐
│<───── updates view ┌───────┐
│ ┆ │ State │
│ ┆<─ notifies of user input └───────┘
│ ┆ (using signals) Λ
│ ┆
│ ┆ │<─── updates/reads state
│ V notifies of remote changes
┌┴────────────┐ via messages ┌──────────────────┐
│ Application │<╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤ Seperate │
│ Object ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌>│ Pipewire Thread │
────────────┘ request changes to remote └───────────────────┘
via messages Λ
│<─── updates/reads state
V
┌───────┐ V
│ State │ [ Remote Pipewire Server ]
└───────┘
────────────┘ request changes to remote └───────────────────┘
via messages Λ
V
[ Remote Pipewire Server ]
```
The program is split between two threads, with most stuff happening inside the GTK thread.
The GTK thread will sit in a GTK event processing loop, while the pipewire thread will sit in a
pipewire event processing loop.
The program is split between two cooperating threads.
The GTK thread (displayed on the left side) will sit in a GTK event processing loop, while the pipewire thread (displayed on the right side) will sit in a pipewire event processing loop.
The `Application` object inside the GTK thread is the centerpiece of this architecture.
It communicates with the pipewire thread using two channels,
The `Application` object inside the GTK thread communicates with the pipewire thread using two channels,
where each message sent by one thread will trigger the loop of the other thread to invoke a callback
with the received message.
For each change on the remote pipewire server, the `Application` in the GTK thread is notified by the pipewire thread
and updates the view to reflect those changes, and additionally memorizes anything it might need later in the state.
For each change on the remote pipewire server, the pipewire thread updates the state and notifies
the `Application` in the GTK thread if changes are needed.
The `Application` then updates the view to reflect those changes.
Additionally, a user may also make changes using the view.
For each change, the view notifies the `Application` by emitting a matching signal.
The `Application` will then request the pipewire thread to make those changes on the remote. \
The `Application` will then ask the pipewire thread to make those changes on the remote. \
These changes will then be applied to the view like any other remote changes as explained above.
# View Architecture

22
docs/making_a_release.md Normal file
View File

@@ -0,0 +1,22 @@
# Making a release
The following describes the process of making a new release:
1. In `data/org.pipewire.Helvum.metainfo.xml.in`,
add a new `<release>` tag to the releases section with the appropriate version and date.
2. In `meson.build` and `Cargo.toml`, bumb the projects version to the new version.
3. Ensure cargo dependencies are up-to-date by running `cargo outdated` (may require running `cargo install cargo-outdated`) and updating outdated dependencies (including the versions specified in `Cargo.lock`).
4. Commit the changes with the a message of the format "Release x.y.z"
5. Add a tag to the release with the new version and a description from describing the changes as a message (run `git tag -a x.y.z`, then write the message)
6. Make a **new** meson build directory and run `meson dist`.
Two files should be created in a `meson-dist` subdirectory:
`helvum-x.y.z.tar.xz` and
`helvum-x.y.z.tar.xz.sha256sum`
7. Push the new commit and tag to upstream, then create a new release on gitlab from the new tag, the description from the tags message formatted as markdown, and also add the two files from step 6 to the description.

BIN
docs/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

39
meson.build Normal file
View File

@@ -0,0 +1,39 @@
project(
'helvum',
'rust',
version: '0.5.0',
license: 'GPL-3.0',
meson_version: '>=0.59.0'
)
gnome = import('gnome')
base_id = 'org.pipewire.Helvum'
dependency('glib-2.0', version: '>= 2.66')
dependency('gtk4', version: '>= 4.4.0')
dependency('libadwaita-1', version: '>= 1.3')
dependency('libpipewire-0.3')
desktop_file_validate = find_program('desktop-file-validate', required: false)
appstream_util = find_program('appstream-util', required: false)
cargo = find_program('cargo', required: true)
prefix = get_option('prefix')
bindir = prefix / get_option('bindir')
datadir = prefix / get_option('datadir')
iconsdir = datadir / 'icons'
meson.add_dist_script(
'build-aux/dist-vendor.sh',
meson.project_build_root() / 'meson-dist' / meson.project_name() + '-' + meson.project_version(),
meson.project_source_root()
)
subdir('src')
subdir('data')
gnome.post_install(
gtk_update_icon_cache: true,
update_desktop_database: true,
)

11
meson_options.txt Normal file
View File

@@ -0,0 +1,11 @@
option(
'profile',
type: 'combo',
choices: [
'default',
'development'
],
value: 'default',
description: 'The build profile for Helvum. One of "default" or "development".'
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

View File

@@ -1,101 +1,138 @@
use std::{cell::RefCell, collections::HashMap};
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use gtk::{
use adw::{
gio,
glib::{self, clone, Continue, Receiver},
glib::{self, clone, Receiver},
gtk,
prelude::*,
subclass::prelude::*,
};
use log::{info, warn};
use pipewire::{channel::Sender, spa::Direction};
use pipewire::channel::Sender;
use crate::{
view::{self},
GtkMessage, PipewireLink, PipewireMessage,
};
use crate::{graph_manager::GraphManager, ui, GtkMessage, PipewireMessage};
#[derive(Debug, Copy, Clone)]
pub enum MediaType {
Audio,
Video,
Midi,
}
// FIXME: This should be in its own .css file.
static STYLE: &str = "
.audio {
background: rgb(50,100,240);
color: black;
}
.video {
background: rgb(200,200,0);
color: black;
}
.midi {
background: rgb(200,0,50);
color: black;
}
";
static STYLE: &str = include_str!("style.css");
static APP_ID: &str = "org.pipewire.Helvum";
static VERSION: &str = env!("CARGO_PKG_VERSION");
static AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
mod imp {
use super::*;
use adw::subclass::prelude::AdwApplicationImpl;
use once_cell::unsync::OnceCell;
#[derive(Default)]
pub struct Application {
pub(super) graphview: view::GraphView,
pub(super) state: RefCell<State>,
pub(super) pw_sender: OnceCell<RefCell<Sender<GtkMessage>>>,
pub(super) window: ui::Window,
pub(super) graph_manager: OnceCell<GraphManager>,
}
#[glib::object_subclass]
impl ObjectSubclass for Application {
const NAME: &'static str = "HelvumApplication";
type Type = super::Application;
type ParentType = gtk::Application;
type ParentType = adw::Application;
}
impl ObjectImpl for Application {}
impl ApplicationImpl for Application {
fn activate(&self, app: &Self::Type) {
let scrollwindow = gtk::ScrolledWindowBuilder::new()
.child(&self.graphview)
.build();
let window = gtk::ApplicationWindowBuilder::new()
.application(app)
.default_width(1280)
.default_height(720)
.title("Helvum - Pipewire Patchbay")
.child(&scrollwindow)
.build();
window
.settings()
.set_gtk_application_prefer_dark_theme(true);
window.show();
fn activate(&self) {
let app = &*self.obj();
let graphview = self.window.graph();
self.window.set_application(Some(app));
let zoom_set_action =
gio::SimpleAction::new("set-zoom", Some(&f64::static_variant_type()));
zoom_set_action.connect_activate(clone!(@weak graphview => move|_, param| {
let zoom_factor = param.unwrap().get::<f64>().unwrap();
graphview.set_zoom_factor(zoom_factor, None)
}));
self.window.add_action(&zoom_set_action);
self.window.show();
}
fn startup(&self, app: &Self::Type) {
self.parent_startup(app);
fn startup(&self) {
self.parent_startup();
self.obj()
.style_manager()
.set_color_scheme(adw::ColorScheme::PreferDark);
// Load CSS from the STYLE variable.
let provider = gtk::CssProvider::new();
provider.load_from_data(STYLE.as_bytes());
gtk::StyleContext::add_provider_for_display(
provider.load_from_data(STYLE);
gtk::style_context_add_provider_for_display(
&gtk::gdk::Display::default().expect("Error initializing gtk css provider."),
&provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
self.setup_actions();
}
}
impl GtkApplicationImpl for Application {}
impl AdwApplicationImpl for Application {}
impl Application {
fn setup_actions(&self) {
let obj = &*self.obj();
// Add <Control-Q> shortcut for quitting the application.
let quit = gtk::gio::SimpleAction::new("quit", None);
quit.connect_activate(clone!(@weak obj => move |_, _| {
obj.quit();
}));
obj.set_accels_for_action("app.quit", &["<Control>Q"]);
obj.add_action(&quit);
let action_about = gio::ActionEntry::builder("about")
.activate(|obj: &super::Application, _, _| {
obj.imp().show_about_dialog();
})
.build();
obj.add_action_entries([action_about]);
}
fn show_about_dialog(&self) {
let authors: Vec<&str> = AUTHORS.split(':').collect();
let about_window = adw::AboutWindow::builder()
.application_icon(APP_ID)
.application_name("Helvum")
.developer_name("Tom Wagner")
.developers(authors)
.version(VERSION)
.website("https://gitlab.freedesktop.org/pipewire/helvum")
.issue_url("https://gitlab.freedesktop.org/pipewire/helvum/-/issues")
.license_type(gtk::License::Gpl30Only)
.build();
about_window.present();
}
}
}
glib::wrapper! {
pub struct Application(ObjectSubclass<imp::Application>)
@extends gio::Application, gtk::Application,
@extends gio::Application, gtk::Application, adw::Application,
@implements gio::ActionGroup, gio::ActionMap;
}
@@ -106,287 +143,21 @@ impl Application {
gtk_receiver: Receiver<PipewireMessage>,
pw_sender: Sender<GtkMessage>,
) -> Self {
let app: Application =
glib::Object::new(&[("application-id", &"org.freedesktop.ryuukyu.helvum")])
.expect("Failed to create new Application");
let app: Application = glib::Object::builder()
.property("application-id", APP_ID)
.build();
let imp = imp::Application::from_instance(&app);
imp.pw_sender
.set(RefCell::new(pw_sender))
// Discard the returned sender, as it does not implement `Debug`.
.map_err(|_| ())
.expect("pw_sender field was already set");
let imp = app.imp();
// Add <Control-Q> shortcut for quitting the application.
let quit = gtk::gio::SimpleAction::new("quit", None);
quit.connect_activate(clone!(@weak app => move |_, _| {
app.quit();
}));
app.set_accels_for_action("app.quit", &["<Control>Q"]);
app.add_action(&quit);
// React to messages received from the pipewire thread.
gtk_receiver.attach(
None,
clone!(
@weak app => @default-return Continue(true),
move |msg| {
match msg {
PipewireMessage::NodeAdded {
id,
name,
media_type,
} => app.add_node(id, name, media_type),
PipewireMessage::PortAdded {
id,
node_id,
name,
direction,
} => app.add_port(id, name, node_id, direction),
PipewireMessage::LinkAdded { id, link } => app.add_link(id, link),
PipewireMessage::ObjectRemoved { id } => app.remove_global(id),
};
Continue(true)
}
),
);
imp.graph_manager
.set(GraphManager::new(
&imp.window.graph(),
&imp.window.connection_banner(),
pw_sender,
gtk_receiver,
))
.expect("Should be able to set graph manager");
app
}
/// Add a new node to the view.
pub fn add_node(&self, id: u32, name: String, media_type: Option<MediaType>) {
info!("Adding node to graph: id {}", id);
let imp = imp::Application::from_instance(self);
imp.state.borrow_mut().insert(
id,
Item::Node {
// widget: node_widget,
media_type,
},
);
imp.graphview.add_node(id, view::Node::new(name.as_str()));
}
/// Add a new port to the view.
pub fn add_port(&self, id: u32, name: String, node_id: u32, direction: Direction) {
info!("Adding port to graph: id {}", id);
let imp = imp::Application::from_instance(self);
// Find out the nodes media type so that the port can be colored.
let media_type =
if let Some(Item::Node { media_type, .. }) = imp.state.borrow().get(node_id) {
media_type.to_owned()
} else {
warn!("Node not found for Port {}", id);
None
};
// Save node_id so we can delete this port easily.
imp.state.borrow_mut().insert(id, Item::Port { node_id });
let port = view::Port::new(id, name.as_str(), direction, media_type);
// Create or delete a link if the widget emits the "port-toggled" signal.
if let Err(e) = port.connect_local(
"port_toggled",
false,
clone!(@weak self as app => @default-return None, move |args| {
// Args always look like this: &[widget, id_port_from, id_port_to]
let port_from = args[1].get::<u32>().unwrap();
let port_to = args[2].get::<u32>().unwrap();
app.toggle_link(port_from, port_to);
None
}),
) {
warn!("Failed to connect to \"port-toggled\" signal: {}", e);
}
imp.graphview.add_port(node_id, id, port);
}
/// Add a new link to the view.
pub fn add_link(&self, id: u32, link: PipewireLink) {
info!("Adding link to graph: id {}", id);
let imp = imp::Application::from_instance(self);
// FIXME: Links should be colored depending on the data they carry (video, audio, midi) like ports are.
imp.state.borrow_mut().insert(
id,
Item::Link {
output_port: link.port_from,
input_port: link.port_to,
},
);
// Update graph to contain the new link.
imp.graphview.add_link(id, link);
}
// Toggle a link between the two specified ports on the remote pipewire server.
fn toggle_link(&self, port_from: u32, port_to: u32) {
let imp = imp::Application::from_instance(self);
let sender = imp.pw_sender.get().expect("pw_sender not set").borrow_mut();
let state = imp.state.borrow_mut();
if let Some(id) = state.get_link_id(port_from, port_to) {
info!("Requesting removal of link with id {}", id);
sender
.send(GtkMessage::DestroyGlobal(id))
.expect("Failed to send message");
} else {
info!(
"Requesting creation of link from port id:{} to port id:{}",
port_from, port_to
);
let node_from = state
.get_node_of_port(port_from)
.expect("Requested port not in state");
let node_to = state
.get_node_of_port(port_to)
.expect("Requested port not in state");
sender
.send(GtkMessage::CreateLink(PipewireLink {
node_from,
port_from,
node_to,
port_to,
}))
.expect("Failed to send message");
}
}
/// Handle a global object being removed.
pub fn remove_global(&self, id: u32) {
let imp = imp::Application::from_instance(self);
if let Some(item) = imp.state.borrow_mut().remove(id) {
match item {
Item::Node { .. } => self.remove_node(id),
Item::Port { node_id } => self.remove_port(id, node_id),
Item::Link { .. } => self.remove_link(id),
}
} else {
warn!(
"Attempted to remove item with id {} that is not saved in state",
id
);
}
}
/// Remove the node with the specified id from the view.
fn remove_node(&self, id: u32) {
info!("Removing node from graph: id {}", id);
let imp = imp::Application::from_instance(self);
imp.graphview.remove_node(id);
}
/// Remove the port with the id `id` from the node with the id `node_id`
/// from the view.
fn remove_port(&self, id: u32, node_id: u32) {
info!("Removing port from graph: id {}, node_id: {}", id, node_id);
let imp = imp::Application::from_instance(self);
imp.graphview.remove_port(id, node_id);
}
/// Remove the link with the specified id from the view.
fn remove_link(&self, id: u32) {
info!("Removing link from graph: id {}", id);
let imp = imp::Application::from_instance(self);
imp.graphview.remove_link(id);
}
}
/// Any pipewire item we need to keep track of.
/// These will be saved in the [`Application`]s `state` struct associated with their id.
enum Item {
Node {
// Keep track of the nodes media type to color ports on it.
media_type: Option<MediaType>,
},
Port {
// Save the id of the node this is on so we can remove the port from it
// when it is deleted.
node_id: u32,
},
// We don't need to memorize anything about links right now, but we need to
// be able to find out an id is a link.
Link {
output_port: u32,
input_port: u32,
},
}
/// This struct keeps track of any relevant items and stores them under their IDs.
///
/// Given two port ids, it can also efficiently find the id of the link that connects them.
#[derive(Default)]
struct State {
/// Map pipewire ids to items.
items: HashMap<u32, Item>,
/// Map `(output port id, input port id)` tuples to the id of the link that connects them.
links: HashMap<(u32, u32), u32>,
}
impl State {
/// Add a new item under the specified id.
fn insert(&mut self, id: u32, item: Item) {
if let Item::Link {
output_port,
input_port,
} = item
{
self.links.insert((output_port, input_port), id);
}
self.items.insert(id, item);
}
/// Get the item that has the specified id.
fn get(&self, id: u32) -> Option<&Item> {
self.items.get(&id)
}
/// Get the id of the link that links the two specified ports.
fn get_link_id(&self, output_port: u32, input_port: u32) -> Option<u32> {
self.links.get(&(output_port, input_port)).copied()
}
/// Remove the item with the specified id, returning it if it exists.
fn remove(&mut self, id: u32) -> Option<Item> {
let removed = self.items.remove(&id);
if let Some(Item::Link {
output_port,
input_port,
}) = removed
{
self.links.remove(&(output_port, input_port));
}
removed
}
/// Convenience function: Get the id of the node a port is on
fn get_node_of_port(&self, port: u32) -> Option<u32> {
if let Some(Item::Port { node_id }) = self.get(port) {
Some(*node_id)
} else {
None
}
}
}

327
src/graph_manager.rs Normal file
View File

@@ -0,0 +1,327 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{glib, prelude::*, subclass::prelude::*};
use pipewire::channel::Sender as PwSender;
use crate::{ui::graph::GraphView, GtkMessage, PipewireMessage};
mod imp {
use super::*;
use std::{cell::RefCell, collections::HashMap};
use once_cell::unsync::OnceCell;
use crate::{ui::graph, MediaType, NodeType};
#[derive(Default, glib::Properties)]
#[properties(wrapper_type = super::GraphManager)]
pub struct GraphManager {
#[property(get, set, construct_only)]
pub graph: OnceCell<crate::ui::graph::GraphView>,
#[property(get, set, construct_only)]
pub connection_banner: OnceCell<adw::Banner>,
pub pw_sender: OnceCell<PwSender<crate::GtkMessage>>,
pub items: RefCell<HashMap<u32, glib::Object>>,
}
#[glib::object_subclass]
impl ObjectSubclass for GraphManager {
const NAME: &'static str = "HelvumGraphManager";
type Type = super::GraphManager;
type ParentType = glib::Object;
}
#[glib::derived_properties]
impl ObjectImpl for GraphManager {}
impl GraphManager {
pub fn attach_receiver(&self, receiver: glib::Receiver<crate::PipewireMessage>) {
receiver.attach(None, glib::clone!(
@weak self as imp => @default-return glib::ControlFlow::Continue,
move |msg| {
match msg {
PipewireMessage::NodeAdded { id, name, node_type } => imp.add_node(id, name.as_str(), node_type),
PipewireMessage::PortAdded { id, node_id, name, direction } => imp.add_port(id, name.as_str(), node_id, direction),
PipewireMessage::PortFormatChanged { id, media_type } => imp.port_media_type_changed(id, media_type),
PipewireMessage::LinkAdded {
id, port_from, port_to, active, media_type
} => imp.add_link(id, port_from, port_to, active, media_type),
PipewireMessage::LinkStateChanged { id, active } => imp.link_state_changed(id, active),
PipewireMessage::LinkFormatChanged { id, media_type } => imp.link_format_changed(id, media_type),
PipewireMessage::NodeRemoved { id } => imp.remove_node(id),
PipewireMessage::PortRemoved { id, node_id } => imp.remove_port(id, node_id),
PipewireMessage::LinkRemoved { id } => imp.remove_link(id),
PipewireMessage::Connecting => {
imp.obj().connection_banner().set_revealed(true);
}
PipewireMessage::Connected => {
imp.obj().connection_banner().set_revealed(false);
},
PipewireMessage::Disconnected => {
imp.clear();
},
};
glib::ControlFlow::Continue
}
));
}
/// Add a new node to the view.
fn add_node(&self, id: u32, name: &str, node_type: Option<NodeType>) {
log::info!("Adding node to graph: id {}", id);
let node = graph::Node::new(name, id);
self.items.borrow_mut().insert(id, node.clone().upcast());
self.obj().graph().add_node(node, node_type);
}
/// Remove the node with the specified id from the view.
fn remove_node(&self, id: u32) {
log::info!("Removing node from graph: id {}", id);
let Some(node) = self.items.borrow_mut().remove(&id) else {
log::warn!("Unknown node (id={id}) removed from graph");
return;
};
let Ok(node) = node.dynamic_cast::<graph::Node>() else {
log::warn!("Graph Manager item under node id {id} is not a node");
return;
};
self.obj().graph().remove_node(&node);
}
/// Add a new port to the view.
fn add_port(&self, id: u32, name: &str, node_id: u32, direction: pipewire::spa::Direction) {
log::info!("Adding port to graph: id {}", id);
let mut items = self.items.borrow_mut();
let Some(node) = items.get(&node_id) else {
log::warn!("Node (id: {node_id}) for port (id: {id}) not found in graph manager");
return;
};
let Ok(node) = node.clone().dynamic_cast::<graph::Node>() else {
log::warn!("Graph Manager item under node id {node_id} is not a node");
return;
};
let port = graph::Port::new(id, name, direction);
// Create or delete a link if the widget emits the "port-toggled" signal.
port.connect_local(
"port_toggled",
false,
glib::clone!(@weak self as app => @default-return None, move |args| {
// Args always look like this: &[widget, id_port_from, id_port_to]
let port_from = args[1].get::<u32>().unwrap();
let port_to = args[2].get::<u32>().unwrap();
app.toggle_link(port_from, port_to);
None
}),
);
items.insert(id, port.clone().upcast());
node.add_port(port);
}
fn port_media_type_changed(&self, id: u32, media_type: MediaType) {
let items = self.items.borrow();
let Some(port) = items.get(&id) else {
log::warn!("Port (id: {id}) for changed media type not found in graph manager");
return;
};
let Some(port) = port.dynamic_cast_ref::<graph::Port>() else {
log::warn!("Graph Manager item under port id {id} is not a port");
return;
};
port.set_media_type(media_type.as_raw())
}
/// Remove the port with the id `id` from the node with the id `node_id`
/// from the view.
fn remove_port(&self, id: u32, node_id: u32) {
log::info!("Removing port from graph: id {}, node_id: {}", id, node_id);
let mut items = self.items.borrow_mut();
let Some(node) = items.get(&node_id) else {
log::warn!("Node (id: {node_id}) for port (id: {id}) not found in graph manager");
return;
};
let Ok(node) = node.clone().dynamic_cast::<graph::Node>() else {
log::warn!("Graph Manager item under node id {node_id} is not a node");
return;
};
let Some(port) = items.remove(&id) else {
log::warn!("Unknown Port (id: {id}) removed from graph");
return;
};
let Ok(port) = port.dynamic_cast::<graph::Port>() else {
log::warn!("Graph Manager item under port id {id} is not a port");
return;
};
node.remove_port(&port);
}
/// Add a new link to the view.
fn add_link(
&self,
id: u32,
output_port_id: u32,
input_port_id: u32,
active: bool,
media_type: MediaType,
) {
log::info!("Adding link to graph: id {}", id);
let mut items = self.items.borrow_mut();
let Some(output_port) = items.get(&output_port_id) else {
log::warn!("Output port (id: {output_port_id}) for link (id: {id}) not found in graph manager");
return;
};
let Ok(output_port) = output_port.clone().dynamic_cast::<graph::Port>() else {
log::warn!("Graph Manager item under port id {output_port_id} is not a port");
return;
};
let Some(input_port) = items.get(&input_port_id) else {
log::warn!("Output port (id: {input_port_id}) for link (id: {id}) not found in graph manager");
return;
};
let Ok(input_port) = input_port.clone().dynamic_cast::<graph::Port>() else {
log::warn!("Graph Manager item under port id {input_port_id} is not a port");
return;
};
let link = graph::Link::new();
link.set_output_port(Some(&output_port));
link.set_input_port(Some(&input_port));
link.set_active(active);
link.set_media_type(media_type);
items.insert(id, link.clone().upcast());
// Update graph to contain the new link.
self.graph
.get()
.expect("graph should be set")
.add_link(link);
}
fn link_state_changed(&self, id: u32, active: bool) {
log::info!(
"Link state changed: Link (id={id}) is now {}",
if active { "active" } else { "inactive" }
);
let items = self.items.borrow();
let Some(link) = items.get(&id) else {
log::warn!("Link state changed on unknown link (id={id})");
return;
};
let Some(link) = link.dynamic_cast_ref::<graph::Link>() else {
log::warn!("Graph Manager item under link id {id} is not a link");
return;
};
link.set_active(active);
}
fn link_format_changed(&self, id: u32, media_type: pipewire::spa::format::MediaType) {
let items = self.items.borrow();
let Some(link) = items.get(&id) else {
log::warn!("Link (id: {id}) for changed media type not found in graph manager");
return;
};
let Some(link) = link.dynamic_cast_ref::<graph::Link>() else {
log::warn!("Graph Manager item under link id {id} is not a link");
return;
};
link.set_media_type(media_type);
}
// Toggle a link between the two specified ports on the remote pipewire server.
fn toggle_link(&self, port_from: u32, port_to: u32) {
let sender = self.pw_sender.get().expect("pw_sender shoud be set");
sender
.send(crate::GtkMessage::ToggleLink { port_from, port_to })
.expect("Failed to send message");
}
/// Remove the link with the specified id from the view.
fn remove_link(&self, id: u32) {
log::info!("Removing link from graph: id {}", id);
let Some(link) = self.items.borrow_mut().remove(&id) else {
log::warn!("Unknown Link (id={id}) removed from graph");
return;
};
let Ok(link) = link.dynamic_cast::<graph::Link>() else {
log::warn!("Graph Manager item under link id {id} is not a link");
return;
};
self.obj().graph().remove_link(&link);
}
fn clear(&self) {
self.items.borrow_mut().clear();
self.obj().graph().clear();
}
}
}
glib::wrapper! {
pub struct GraphManager(ObjectSubclass<imp::GraphManager>);
}
impl GraphManager {
pub fn new(
graph: &GraphView,
connection_banner: &adw::Banner,
sender: PwSender<GtkMessage>,
receiver: glib::Receiver<PipewireMessage>,
) -> Self {
let res: Self = glib::Object::builder()
.property("graph", graph)
.property("connection-banner", connection_banner)
.build();
res.imp().attach_receiver(receiver);
assert!(
res.imp().pw_sender.set(sender).is_ok(),
"Should be able to set pw_sender)"
);
res
}
}

View File

@@ -1,45 +1,88 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
mod application;
mod graph_manager;
mod pipewire_connection;
mod view;
mod ui;
use application::MediaType;
use gtk::{
glib::{self, PRIORITY_DEFAULT},
prelude::*,
};
use pipewire::spa::Direction;
use adw::{gtk, prelude::*};
use pipewire::spa::{format::MediaType, Direction};
/// Messages used GTK thread to command the pipewire thread.
/// Messages sent by the GTK thread to notify the pipewire thread.
#[derive(Debug, Clone)]
enum GtkMessage {
/// Create a new link.
CreateLink(PipewireLink),
/// Destroy the global with the specified id.
DestroyGlobal(u32),
pub enum GtkMessage {
/// Toggle a link between the two specified ports.
ToggleLink { port_from: u32, port_to: u32 },
/// Quit the event loop and let the thread finish.
Terminate,
}
/// Messages used pipewire thread to notify the GTK thread.
/// Messages sent by the pipewire thread to notify the GTK thread.
#[derive(Debug, Clone)]
enum PipewireMessage {
/// A new node has appeared.
pub enum PipewireMessage {
NodeAdded {
id: u32,
name: String,
media_type: Option<MediaType>,
node_type: Option<NodeType>,
},
/// A new port has appeared.
PortAdded {
id: u32,
node_id: u32,
name: String,
direction: Direction,
},
/// A new link has appeared.
LinkAdded { id: u32, link: PipewireLink },
/// An object was removed
ObjectRemoved { id: u32 },
PortFormatChanged {
id: u32,
media_type: MediaType,
},
LinkAdded {
id: u32,
port_from: u32,
port_to: u32,
active: bool,
media_type: MediaType,
},
LinkStateChanged {
id: u32,
active: bool,
},
LinkFormatChanged {
id: u32,
media_type: MediaType,
},
NodeRemoved {
id: u32,
},
PortRemoved {
id: u32,
node_id: u32,
},
LinkRemoved {
id: u32,
},
Connecting,
Connected,
Disconnected,
}
#[derive(Debug, Clone)]
pub enum NodeType {
Input,
Output,
}
#[derive(Debug, Clone)]
@@ -50,12 +93,29 @@ pub struct PipewireLink {
pub port_to: u32,
}
static GLIB_LOGGER: glib::GlibLogger = glib::GlibLogger::new(
glib::GlibLoggerFormat::Structured,
glib::GlibLoggerDomain::CrateTarget,
);
fn init_glib_logger() {
log::set_logger(&GLIB_LOGGER).expect("Failed to set logger");
// Glib does not have a "Trace" log level, so only print messages "Debug" or higher priority.
log::set_max_level(log::LevelFilter::Debug);
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
init_glib_logger();
gtk::init()?;
// Aquire main context so that we can attach the gtk channel later.
let ctx = glib::MainContext::default();
let _guard = ctx.acquire().unwrap();
// Start the pipewire thread with channels in both directions.
let (gtk_sender, gtk_receiver) = glib::MainContext::channel(PRIORITY_DEFAULT);
let (gtk_sender, gtk_receiver) = glib::MainContext::channel(glib::Priority::DEFAULT);
let (pw_sender, pw_receiver) = pipewire::channel::channel();
let pw_thread =
std::thread::spawn(move || pipewire_connection::thread_main(gtk_sender, pw_receiver));

31
src/meson.build Normal file
View File

@@ -0,0 +1,31 @@
cargo_options = [ '--manifest-path', meson.project_source_root() / 'Cargo.toml' ]
cargo_options += [ '--target-dir', meson.project_build_root() / 'src' ]
if get_option('profile') == 'default'
cargo_options += [ '--release' ]
rust_target = 'release'
message('Building in release mode')
else
rust_target = 'debug'
message('Building in debug mode')
endif
cargo_env = [ 'CARGO_HOME=' + meson.project_build_root() / 'cargo-home' ]
custom_target(
'cargo-build',
build_by_default: true,
build_always_stale: true,
output: meson.project_name(),
console: true,
install: true,
install_dir: bindir,
command: [
'env',
cargo_env,
cargo, 'build',
cargo_options,
'&&',
'cp', 'src' / rust_target / meson.project_name(), '@OUTPUT@',
],
)

View File

@@ -1,182 +0,0 @@
use std::rc::Rc;
use gtk::glib::{self, clone};
use log::warn;
use pipewire::{
link::Link,
prelude::*,
properties,
registry::GlobalObject,
spa::{Direction, ForeignDict},
types::ObjectType,
Context, MainLoop,
};
use crate::{application::MediaType, GtkMessage, PipewireMessage};
/// The "main" function of the pipewire thread.
pub(super) fn thread_main(
gtk_sender: glib::Sender<PipewireMessage>,
pw_receiver: pipewire::channel::Receiver<GtkMessage>,
) {
let mainloop = MainLoop::new().expect("Failed to create mainloop");
let context = Context::new(&mainloop).expect("Failed to create context");
let core = context.connect(None).expect("Failed to connect to remote");
let registry = Rc::new(core.get_registry().expect("Failed to get registry"));
let _receiver = pw_receiver.attach(&mainloop, {
let mainloop = mainloop.clone();
clone!(@weak registry => move |msg| match msg {
GtkMessage::CreateLink(link) => {
if let Err(e) = core.create_object::<Link, _>(
"link-factory",
&properties! {
"link.output.node" => link.node_from.to_string(),
"link.output.port" => link.port_from.to_string(),
"link.input.node" => link.node_to.to_string(),
"link.input.port" => link.port_to.to_string(),
"object.linger" => "1"
},
) {
warn!("Failed to create link: {}", e);
}
}
GtkMessage::DestroyGlobal(id) => {
// FIXME: Handle error
registry.destroy_global(id);
}
GtkMessage::Terminate => mainloop.quit(),
})
});
let _listener = registry
.add_listener_local()
.global({
let sender = gtk_sender.clone();
move |global| match global.type_ {
ObjectType::Node => handle_node(global, &sender),
ObjectType::Port => handle_port(global, &sender),
ObjectType::Link => handle_link(global, &sender),
_ => {
// Other objects are not interesting to us
}
}
})
.global_remove(move |id| {
gtk_sender
.send(PipewireMessage::ObjectRemoved { id })
.expect("Failed to send message")
})
.register();
mainloop.run();
}
/// Handle a new node being added
fn handle_node(node: &GlobalObject<ForeignDict>, sender: &glib::Sender<PipewireMessage>) {
let props = node
.props
.as_ref()
.expect("Node object is missing properties");
// Get the nicest possible name for the node, using a fallback chain of possible name attributes.
let name = String::from(
props
.get("node.nick")
.or_else(|| props.get("node.description"))
.or_else(|| props.get("node.name"))
.unwrap_or_default(),
);
// FIXME: This relies on the node being passed to us by the pipwire server before its port.
let media_type = props
.get("media.class")
.map(|class| {
if class.contains("Audio") {
Some(MediaType::Audio)
} else if class.contains("Video") {
Some(MediaType::Video)
} else if class.contains("Midi") {
Some(MediaType::Midi)
} else {
None
}
})
.flatten();
sender
.send(PipewireMessage::NodeAdded {
id: node.id,
name,
media_type,
})
.expect("Failed to send message");
}
/// Handle a new port being added
fn handle_port(port: &GlobalObject<ForeignDict>, sender: &glib::Sender<PipewireMessage>) {
let props = port
.props
.as_ref()
.expect("Port object is missing properties");
let name = props.get("port.name").unwrap_or_default().to_string();
let node_id: u32 = props
.get("node.id")
.expect("Port has no node.id property!")
.parse()
.expect("Could not parse node.id property");
let direction = if matches!(props.get("port.direction"), Some("in")) {
Direction::Input
} else {
Direction::Output
};
sender
.send(PipewireMessage::PortAdded {
id: port.id,
node_id,
name,
direction,
})
.expect("Failed to send message");
}
/// Handle a new link being added
fn handle_link(link: &GlobalObject<ForeignDict>, sender: &glib::Sender<PipewireMessage>) {
let props = link
.props
.as_ref()
.expect("Link object is missing properties");
let node_from: u32 = props
.get("link.output.node")
.expect("Link has no link.input.node property")
.parse()
.expect("Could not parse link.input.node property");
let port_from: u32 = props
.get("link.output.port")
.expect("Link has no link.output.port property")
.parse()
.expect("Could not parse link.output.port property");
let node_to: u32 = props
.get("link.input.node")
.expect("Link has no link.input.node property")
.parse()
.expect("Could not parse link.input.node property");
let port_to: u32 = props
.get("link.input.port")
.expect("Link has no link.input.port property")
.parse()
.expect("Could not parse link.input.port property");
sender
.send(PipewireMessage::LinkAdded {
id: link.id,
link: crate::PipewireLink {
node_from,
port_from,
node_to,
port_to,
},
})
.expect("Failed to send message");
}

View File

@@ -0,0 +1,466 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
mod state;
use std::{
cell::{Cell, RefCell},
collections::HashMap,
rc::Rc,
time::Duration,
};
use adw::glib::{self, clone};
use log::{debug, error, info, warn};
use pipewire::{
link::{Link, LinkChangeMask, LinkInfo, LinkListener, LinkState},
port::{Port, PortChangeMask, PortInfo, PortListener},
prelude::*,
properties,
registry::{GlobalObject, Registry},
spa::{
param::{ParamInfoFlags, ParamType},
ForeignDict, SpaResult,
},
types::ObjectType,
Context, Core, MainLoop,
};
use crate::{GtkMessage, MediaType, NodeType, PipewireMessage};
use state::{Item, State};
enum ProxyItem {
Port {
proxy: Port,
_listener: PortListener,
},
Link {
_proxy: Link,
_listener: LinkListener,
},
}
/// The "main" function of the pipewire thread.
pub(super) fn thread_main(
gtk_sender: glib::Sender<PipewireMessage>,
mut pw_receiver: pipewire::channel::Receiver<GtkMessage>,
) {
let mainloop = MainLoop::new().expect("Failed to create mainloop");
let context = Rc::new(Context::new(&mainloop).expect("Failed to create context"));
let is_stopped = Rc::new(Cell::new(false));
let mut is_connecting = false;
while !is_stopped.get() {
// Try to connect
let core = match context.connect(None) {
Ok(core) => Rc::new(core),
Err(_) => {
if !is_connecting {
is_connecting = true;
gtk_sender
.send(PipewireMessage::Connecting)
.expect("Failed to send message");
}
// If connection is failed, try to connect again in 200ms
let interval = Some(Duration::from_millis(200));
let timer = mainloop.add_timer(clone!(@strong mainloop => move |_| {
mainloop.quit();
}));
timer.update_timer(interval, None).into_result().unwrap();
let receiver = pw_receiver.attach(&mainloop, {
clone!(@strong mainloop, @strong is_stopped => move |msg|
if let GtkMessage::Terminate = msg {
// main thread requested stop
is_stopped.set(true);
mainloop.quit();
}
)
});
mainloop.run();
pw_receiver = receiver.deattach();
continue;
}
};
if is_connecting {
is_connecting = false;
gtk_sender
.send(PipewireMessage::Connected)
.expect("Failed to send message");
}
let registry = Rc::new(core.get_registry().expect("Failed to get registry"));
// Keep proxies and their listeners alive so that we can receive info events.
let proxies = Rc::new(RefCell::new(HashMap::new()));
let state = Rc::new(RefCell::new(State::new()));
let receiver = pw_receiver.attach(&mainloop, {
clone!(@strong mainloop, @weak core, @weak registry, @strong state, @strong is_stopped => move |msg| match msg {
GtkMessage::ToggleLink { port_from, port_to } => toggle_link(port_from, port_to, &core, &registry, &state),
GtkMessage::Terminate => {
// main thread requested stop
is_stopped.set(true);
mainloop.quit();
}
})
});
let gtk_sender = gtk_sender.clone();
let _listener = core.add_listener_local()
.error(clone!(@strong mainloop, @strong gtk_sender, @strong is_stopped => move |id, _seq, res, message| {
if id != pipewire::PW_ID_CORE {
return;
}
if res == -libc::EPIPE {
gtk_sender.send(PipewireMessage::Disconnected)
.expect("Failed to send message");
mainloop.quit();
} else {
let serr = SpaResult::from_c(res).into_result().unwrap_err();
error!("Pipewire Core received error {serr}: {message}");
}
}))
.register();
let _listener = registry
.add_listener_local()
.global(clone!(@strong gtk_sender, @weak registry, @strong proxies, @strong state =>
move |global| match global.type_ {
ObjectType::Node => handle_node(global, &gtk_sender, &state),
ObjectType::Port => handle_port(global, &gtk_sender, &registry, &proxies, &state),
ObjectType::Link => handle_link(global, &gtk_sender, &registry, &proxies, &state),
_ => {
// Other objects are not interesting to us
}
}
))
.global_remove(clone!(@strong proxies, @strong state => move |id| {
if let Some(item) = state.borrow_mut().remove(id) {
gtk_sender.send(match item {
Item::Node { .. } => PipewireMessage::NodeRemoved {id},
Item::Port { node_id } => PipewireMessage::PortRemoved {id, node_id},
Item::Link { .. } => PipewireMessage::LinkRemoved {id},
}).expect("Failed to send message");
} else {
warn!(
"Attempted to remove item with id {} that is not saved in state",
id
);
}
proxies.borrow_mut().remove(&id);
}))
.register();
mainloop.run();
pw_receiver = receiver.deattach();
}
}
/// Handle a new node being added
fn handle_node(
node: &GlobalObject<ForeignDict>,
sender: &glib::Sender<PipewireMessage>,
state: &Rc<RefCell<State>>,
) {
let props = node
.props
.as_ref()
.expect("Node object is missing properties");
// Get the nicest possible name for the node, using a fallback chain of possible name attributes.
let name = String::from(
props
.get("node.description")
.or_else(|| props.get("node.nick"))
.or_else(|| props.get("node.name"))
.unwrap_or_default(),
);
let media_class = |class: &str| {
if class.contains("Sink") || class.contains("Input") {
Some(NodeType::Input)
} else if class.contains("Source") || class.contains("Output") {
Some(NodeType::Output)
} else {
None
}
};
let node_type = props
.get("media.category")
.and_then(|class| {
if class.contains("Duplex") {
None
} else {
props.get("media.class").and_then(media_class)
}
})
.or_else(|| props.get("media.class").and_then(media_class));
state.borrow_mut().insert(node.id, Item::Node);
sender
.send(PipewireMessage::NodeAdded {
id: node.id,
name,
node_type,
})
.expect("Failed to send message");
}
/// Handle a new port being added
fn handle_port(
port: &GlobalObject<ForeignDict>,
sender: &glib::Sender<PipewireMessage>,
registry: &Rc<Registry>,
proxies: &Rc<RefCell<HashMap<u32, ProxyItem>>>,
state: &Rc<RefCell<State>>,
) {
let port_id = port.id;
let proxy: Port = registry.bind(port).expect("Failed to bind to port proxy");
let listener = proxy
.add_listener_local()
.info(
clone!(@strong proxies, @strong state, @strong sender => move |info| {
handle_port_info(info, &proxies, &state, &sender);
}),
)
.param(clone!(@strong sender => move |_, param_id, _, _, param| {
if param_id == ParamType::EnumFormat {
handle_port_enum_format(port_id, param, &sender)
}
}))
.register();
proxies.borrow_mut().insert(
port.id,
ProxyItem::Port {
proxy,
_listener: listener,
},
);
}
fn handle_port_info(
info: &PortInfo,
proxies: &Rc<RefCell<HashMap<u32, ProxyItem>>>,
state: &Rc<RefCell<State>>,
sender: &glib::Sender<PipewireMessage>,
) {
debug!("Received port info: {:?}", info);
let id = info.id();
let proxies = proxies.borrow();
let Some(ProxyItem::Port { proxy, .. }) = proxies.get(&id) else {
log::error!("Received info on unknown port with id {id}");
return;
};
let mut state = state.borrow_mut();
if let Some(Item::Port { .. }) = state.get(id) {
// Info was an update, figure out if we should notify the GTK thread
if info.change_mask().contains(PortChangeMask::PARAMS) {
// TODO: React to param changes
}
} else {
// First time we get info. We can now notify the gtk thread of a new link.
let props = info.props().expect("Port object is missing properties");
let name = props.get("port.name").unwrap_or_default().to_string();
let node_id: u32 = props
.get("node.id")
.expect("Port has no node.id property!")
.parse()
.expect("Could not parse node.id property");
state.insert(id, Item::Port { node_id });
let params = info.params();
let enum_format_info = params
.iter()
.find(|param| param.id() == ParamType::EnumFormat);
if let Some(enum_format_info) = enum_format_info {
if enum_format_info.flags().contains(ParamInfoFlags::READ) {
proxy.enum_params(0, Some(ParamType::EnumFormat), 0, u32::MAX);
}
}
sender
.send(PipewireMessage::PortAdded {
id,
node_id,
name,
direction: info.direction(),
})
.expect("Failed to send message");
}
}
fn handle_port_enum_format(
port_id: u32,
param: Option<&pipewire::spa::pod::Pod>,
sender: &glib::Sender<PipewireMessage>,
) {
let media_type = param
.and_then(|param| pipewire::spa::param::format_utils::parse_format(param).ok())
.map(|(media_type, _media_subtype)| media_type)
.unwrap_or(MediaType::Unknown);
sender
.send(PipewireMessage::PortFormatChanged {
id: port_id,
media_type,
})
.expect("Failed to send message")
}
/// Handle a new link being added
fn handle_link(
link: &GlobalObject<ForeignDict>,
sender: &glib::Sender<PipewireMessage>,
registry: &Rc<Registry>,
proxies: &Rc<RefCell<HashMap<u32, ProxyItem>>>,
state: &Rc<RefCell<State>>,
) {
debug!(
"New link (id:{}) appeared, setting up info listener.",
link.id
);
let proxy: Link = registry.bind(link).expect("Failed to bind to link proxy");
let listener = proxy
.add_listener_local()
.info(clone!(@strong state, @strong sender => move |info| {
handle_link_info(info, &state, &sender);
}))
.register();
proxies.borrow_mut().insert(
link.id,
ProxyItem::Link {
_proxy: proxy,
_listener: listener,
},
);
}
fn handle_link_info(
info: &LinkInfo,
state: &Rc<RefCell<State>>,
sender: &glib::Sender<PipewireMessage>,
) {
debug!("Received link info: {:?}", info);
let id = info.id();
let mut state = state.borrow_mut();
if let Some(Item::Link { .. }) = state.get(id) {
// Info was an update - figure out if we should notify the gtk thread
if info.change_mask().contains(LinkChangeMask::STATE) {
sender
.send(PipewireMessage::LinkStateChanged {
id,
active: matches!(info.state(), LinkState::Active),
})
.expect("Failed to send message");
}
if info.change_mask().contains(LinkChangeMask::FORMAT) {
sender
.send(PipewireMessage::LinkFormatChanged {
id,
media_type: get_link_media_type(info),
})
.expect("Failed to send message");
}
} else {
// First time we get info. We can now notify the gtk thread of a new link.
let port_from = info.output_port_id();
let port_to = info.input_port_id();
state.insert(id, Item::Link { port_from, port_to });
sender
.send(PipewireMessage::LinkAdded {
id,
port_from,
port_to,
active: matches!(info.state(), LinkState::Active),
media_type: get_link_media_type(info),
})
.expect("Failed to send message");
}
}
/// Toggle a link between the two specified ports.
fn toggle_link(
port_from: u32,
port_to: u32,
core: &Rc<Core>,
registry: &Rc<Registry>,
state: &Rc<RefCell<State>>,
) {
let state = state.borrow_mut();
if let Some(id) = state.get_link_id(port_from, port_to) {
info!("Requesting removal of link with id {}", id);
// FIXME: Handle error
registry.destroy_global(id);
} else {
info!(
"Requesting creation of link from port id:{} to port id:{}",
port_from, port_to
);
let node_from = state
.get_node_of_port(port_from)
.expect("Requested port not in state");
let node_to = state
.get_node_of_port(port_to)
.expect("Requested port not in state");
if let Err(e) = core.create_object::<Link, _>(
"link-factory",
&properties! {
"link.output.node" => node_from.to_string(),
"link.output.port" => port_from.to_string(),
"link.input.node" => node_to.to_string(),
"link.input.port" => port_to.to_string(),
"object.linger" => "1"
},
) {
warn!("Failed to create link: {}", e);
}
}
}
fn get_link_media_type(link_info: &LinkInfo) -> MediaType {
let media_type = link_info
.format()
.and_then(|format| pipewire::spa::param::format_utils::parse_format(format).ok())
.map(|(media_type, _media_subtype)| media_type)
.unwrap_or(MediaType::Unknown);
media_type
}

View File

@@ -0,0 +1,92 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashMap;
/// Any pipewire item we need to keep track of.
/// These will be saved in the `State` struct associated with their id.
pub(super) enum Item {
Node,
Port {
// Save the id of the node this is on so we can remove the port from it
// when it is deleted.
node_id: u32,
},
Link {
port_from: u32,
port_to: u32,
},
}
/// This struct keeps track of any relevant items and stores them under their IDs.
///
/// Given two port ids, it can also efficiently find the id of the link that connects them.
#[derive(Default)]
pub(super) struct State {
/// Map pipewire ids to items.
items: HashMap<u32, Item>,
/// Map `(output port id, input port id)` tuples to the id of the link that connects them.
links: HashMap<(u32, u32), u32>,
}
impl State {
/// Create a new, empty state.
pub fn new() -> Self {
Self::default()
}
/// Add a new item under the specified id.
pub fn insert(&mut self, id: u32, item: Item) {
if let Item::Link {
port_from, port_to, ..
} = item
{
self.links.insert((port_from, port_to), id);
}
self.items.insert(id, item);
}
/// Get the item that has the specified id.
pub fn get(&self, id: u32) -> Option<&Item> {
self.items.get(&id)
}
/// Get the id of the link that links the two specified ports.
pub fn get_link_id(&self, output_port: u32, input_port: u32) -> Option<u32> {
self.links.get(&(output_port, input_port)).copied()
}
/// Remove the item with the specified id, returning it if it exists.
pub fn remove(&mut self, id: u32) -> Option<Item> {
let removed = self.items.remove(&id);
if let Some(Item::Link { port_from, port_to }) = removed {
self.links.remove(&(port_from, port_to));
}
removed
}
/// Convenience function: Get the id of the node a port is on
pub fn get_node_of_port(&self, port: u32) -> Option<u32> {
if let Some(Item::Port { node_id }) = self.get(port) {
Some(*node_id)
} else {
None
}
}
}

55
src/style.css Normal file
View File

@@ -0,0 +1,55 @@
/* Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as published by
the Free Software Foundation.
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 <http://www.gnu.org/licenses/>.
SPDX-License-Identifier: GPL-3.0-only
*/
@define-color media-type-audio rgb( 50, 100, 240);
@define-color media-type-video rgb(200, 200, 0);
@define-color media-type-midi rgb(200, 0, 50);
@define-color media-type-unknown rgb(128, 128, 128);
.audio {
background: @media-type-audio;
color: black;
}
.video {
background: @media-type-video;
color: black;
}
.midi {
background: @media-type-midi;
color: black;
}
node {
/* Compared to the default card color, this is not transparent in dark-mode
and provides a better contrast to the background in light mode */
background-color: @headerbar_bg_color;
}
node label.heading {
padding: 4px 7px;
}
port label {
padding: 4px 6px;
}
port-handle {
border-radius: 50%;
background-color: @media-type-unknown;
}

836
src/ui/graph/graph_view.rs Normal file
View File

@@ -0,0 +1,836 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{
gio,
glib::{self, clone},
gtk::{
self, cairo,
graphene::{self, Point},
gsk,
},
prelude::*,
subclass::prelude::*,
};
use std::cmp::Ordering;
use super::{Link, Node, Port};
use crate::NodeType;
const CANVAS_SIZE: f64 = 5000.0;
mod imp {
use super::*;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use adw::gtk::gdk::{self};
use log::warn;
use once_cell::sync::Lazy;
use pipewire::spa::format::MediaType;
use pipewire::spa::Direction;
pub struct Colors {
audio: gdk::RGBA,
video: gdk::RGBA,
midi: gdk::RGBA,
unknown: gdk::RGBA,
}
impl Colors {
pub fn color_for_media_type(&self, media_type: MediaType) -> &gdk::RGBA {
match media_type {
MediaType::Audio => &self.audio,
MediaType::Video => &self.video,
MediaType::Stream | MediaType::Application => &self.midi,
_ => &self.unknown,
}
}
}
pub struct DragState {
node: glib::WeakRef<Node>,
/// This stores the offset of the pointer to the origin of the node,
/// so that we can keep the pointer over the same position when moving the node
///
/// The offset is normalized to the default zoom-level of 1.0.
offset: Point,
}
pub struct GraphView {
/// Stores nodes and their positions.
pub(super) nodes: RefCell<HashMap<Node, Point>>,
/// Stores the links and whether they are currently active.
pub(super) links: RefCell<HashSet<Link>>,
// Properties for zooming and scrolling the hraph
pub hadjustment: RefCell<Option<gtk::Adjustment>>,
pub vadjustment: RefCell<Option<gtk::Adjustment>>,
pub zoom_factor: Cell<f64>,
/// This keeps track of an ongoing node drag operation.
pub dragged_node: RefCell<Option<DragState>>,
// These keep track of an ongoing port drag operation
pub dragged_port: glib::WeakRef<Port>,
pub port_drag_cursor: Cell<Point>,
// Memorized data for an in-progress zoom gesture
pub zoom_gesture_initial_zoom: Cell<Option<f64>>,
pub zoom_gesture_anchor: Cell<Option<(f64, f64)>>,
}
impl Default for GraphView {
fn default() -> Self {
Self {
nodes: Default::default(),
links: Default::default(),
hadjustment: Default::default(),
vadjustment: Default::default(),
zoom_factor: Default::default(),
dragged_node: Default::default(),
dragged_port: Default::default(),
port_drag_cursor: Cell::new(Point::new(0.0, 0.0)),
zoom_gesture_initial_zoom: Default::default(),
zoom_gesture_anchor: Default::default(),
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for GraphView {
const NAME: &'static str = "HelvumGraphView";
type Type = super::GraphView;
type ParentType = gtk::Widget;
type Interfaces = (gtk::Scrollable,);
fn class_init(klass: &mut Self::Class) {
klass.set_css_name("graphview");
}
}
impl ObjectImpl for GraphView {
fn constructed(&self) {
self.parent_constructed();
self.obj().add_css_class("view");
self.obj().set_overflow(gtk::Overflow::Hidden);
self.setup_node_dragging();
self.setup_port_drag_and_drop();
self.setup_scroll_zooming();
self.setup_zoom_gesture();
}
fn dispose(&self) {
self.nodes
.borrow()
.iter()
.for_each(|(node, _)| node.unparent())
}
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
vec![
glib::ParamSpecOverride::for_interface::<gtk::Scrollable>("hadjustment"),
glib::ParamSpecOverride::for_interface::<gtk::Scrollable>("vadjustment"),
glib::ParamSpecOverride::for_interface::<gtk::Scrollable>("hscroll-policy"),
glib::ParamSpecOverride::for_interface::<gtk::Scrollable>("vscroll-policy"),
glib::ParamSpecDouble::builder("zoom-factor")
.minimum(0.3)
.maximum(4.0)
.default_value(1.0)
.flags(glib::ParamFlags::CONSTRUCT | glib::ParamFlags::READWRITE)
.build(),
]
});
PROPERTIES.as_ref()
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
match pspec.name() {
"hadjustment" => self.hadjustment.borrow().to_value(),
"vadjustment" => self.vadjustment.borrow().to_value(),
"hscroll-policy" | "vscroll-policy" => gtk::ScrollablePolicy::Natural.to_value(),
"zoom-factor" => self.zoom_factor.get().to_value(),
_ => unimplemented!(),
}
}
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
let obj = self.obj();
match pspec.name() {
"hadjustment" => {
self.set_adjustment(&obj, value.get().ok(), gtk::Orientation::Horizontal)
}
"vadjustment" => {
self.set_adjustment(&obj, value.get().ok(), gtk::Orientation::Vertical)
}
"hscroll-policy" | "vscroll-policy" => {}
"zoom-factor" => {
self.zoom_factor.set(value.get().unwrap());
obj.queue_allocate();
}
_ => unimplemented!(),
}
}
}
impl WidgetImpl for GraphView {
fn size_allocate(&self, _width: i32, _height: i32, baseline: i32) {
let widget = &*self.obj();
for (node, point) in self.nodes.borrow().iter() {
let (_, natural_size) = node.preferred_size();
let transform = self
.canvas_space_to_screen_space_transform()
.translate(point);
node.allocate(
natural_size.width(),
natural_size.height(),
baseline,
Some(transform),
);
}
if let Some(ref hadjustment) = *self.hadjustment.borrow() {
self.set_adjustment_values(widget, hadjustment, gtk::Orientation::Horizontal);
}
if let Some(ref vadjustment) = *self.vadjustment.borrow() {
self.set_adjustment_values(widget, vadjustment, gtk::Orientation::Vertical);
}
}
fn snapshot(&self, snapshot: &gtk::Snapshot) {
let widget = &*self.obj();
let alloc = widget.allocation();
// Draw all visible children
self.nodes
.borrow()
.iter()
// Cull nodes from rendering when they are outside the visible canvas area
.filter(|(node, _)| alloc.intersect(&node.allocation()).is_some())
.for_each(|(node, _)| widget.snapshot_child(node, snapshot));
self.snapshot_links(widget, snapshot);
}
}
impl ScrollableImpl for GraphView {}
impl GraphView {
/// Returns a [`gsk::Transform`] matrix that can translate from canvas space to screen space.
///
/// Canvas space is non-zoomed, and (0, 0) is fixed at the middle of the graph. \
/// Screen space is zoomed and adjusted for scrolling, (0, 0) is at the top-left corner of the window.
///
/// This is the inverted form of [`Self::screen_space_to_canvas_space_transform()`].
fn canvas_space_to_screen_space_transform(&self) -> gsk::Transform {
let hadj = self.hadjustment.borrow().as_ref().unwrap().value();
let vadj = self.vadjustment.borrow().as_ref().unwrap().value();
let zoom_factor = self.zoom_factor.get();
gsk::Transform::new()
.translate(&Point::new(-hadj as f32, -vadj as f32))
.scale(zoom_factor as f32, zoom_factor as f32)
}
/// Returns a [`gsk::Transform`] matrix that can translate from screen space to canvas space.
///
/// This is the inverted form of [`Self::canvas_space_to_screen_space_transform()`], see that function for a more detailed explantion.
fn screen_space_to_canvas_space_transform(&self) -> gsk::Transform {
self.canvas_space_to_screen_space_transform()
.invert()
.unwrap()
}
fn setup_node_dragging(&self) {
let drag_controller = gtk::GestureDrag::new();
drag_controller.connect_drag_begin(|drag_controller, x, y| {
let widget = drag_controller
.widget()
.dynamic_cast::<super::GraphView>()
.expect("drag-begin event is not on the GraphView");
let mut dragged_node = widget.imp().dragged_node.borrow_mut();
// pick() should at least return the widget itself.
let target = widget
.pick(x, y, gtk::PickFlags::DEFAULT)
.expect("drag-begin pick() did not return a widget");
*dragged_node = if target.ancestor(Port::static_type()).is_some() {
// The user targeted a port, so the dragging should be handled by the Port
// component instead of here.
None
} else if let Some(target) = target.ancestor(Node::static_type()) {
// The user targeted a Node without targeting a specific Port.
// Drag the Node around the screen.
let node = target.dynamic_cast_ref::<Node>().unwrap();
let Some(canvas_node_pos) = widget.node_position(node) else {
return;
};
let canvas_cursor_pos = widget
.imp()
.screen_space_to_canvas_space_transform()
.transform_point(&Point::new(x as f32, y as f32));
Some(DragState {
node: node.clone().downgrade(),
offset: Point::new(
canvas_cursor_pos.x() - canvas_node_pos.x(),
canvas_cursor_pos.y() - canvas_node_pos.y(),
),
})
} else {
None
}
});
drag_controller.connect_drag_update(|drag_controller, x, y| {
let widget = drag_controller
.widget()
.dynamic_cast::<super::GraphView>()
.expect("drag-update event is not on the GraphView");
let dragged_node = widget.imp().dragged_node.borrow();
let Some(DragState { node, offset }) = dragged_node.as_ref() else {
return;
};
let Some(node) = node.upgrade() else { return };
let (start_x, start_y) = drag_controller
.start_point()
.expect("Drag has no start point");
let onscreen_node_origin = Point::new((start_x + x) as f32, (start_y + y) as f32);
let transform = widget.imp().screen_space_to_canvas_space_transform();
let canvas_node_origin = transform.transform_point(&onscreen_node_origin);
widget.move_node(
&node,
&Point::new(
canvas_node_origin.x() - offset.x(),
canvas_node_origin.y() - offset.y(),
),
);
});
self.obj().add_controller(drag_controller);
}
fn setup_port_drag_and_drop(&self) {
let controller = gtk::DropControllerMotion::new();
controller.connect_enter(|controller, x, y| {
let graph = controller
.widget()
.downcast::<super::GraphView>()
.expect("Widget should be a graphview");
graph.imp().port_drag_enter(controller, x, y)
});
controller.connect_motion(|controller, x, y| {
let graph = controller
.widget()
.downcast::<super::GraphView>()
.expect("Widget should be a graphview");
graph.imp().port_drag_motion(x, y)
});
controller.connect_leave(|controller| {
let graph = controller
.widget()
.downcast::<super::GraphView>()
.expect("Widget should be a graphview");
graph.imp().port_drag_leave()
});
self.obj().add_controller(controller);
}
fn port_drag_enter(&self, controller: &gtk::DropControllerMotion, x: f64, y: f64) {
let Some(drop) = controller.drop() else {
return;
};
self.port_drag_cursor.set(Point::new(x as f32, y as f32));
drop.read_value_async(
Port::static_type(),
glib::Priority::DEFAULT,
Option::<&gio::Cancellable>::None,
clone!(@weak self as imp => move|value| {
let Ok(value) = value else {
return;
};
let port: &Port = value.get().expect("Value should contain a port");
imp.dragged_port.set(Some(port));
}),
);
self.obj().queue_draw();
}
fn port_drag_motion(&self, x: f64, y: f64) {
if self.dragged_port.upgrade().is_some() {
self.port_drag_cursor.set(Point::new(x as f32, y as f32));
self.obj().queue_draw();
}
}
fn port_drag_leave(&self) {
if self.dragged_port.upgrade().is_some() {
self.dragged_port.set(None);
self.obj().queue_draw();
}
}
fn setup_scroll_zooming(&self) {
// We're only interested in the vertical axis, but for devices like touchpads,
// not capturing a small accidental horizontal move may cause the scroll to be disrupted if a widget
// higher up captures it instead.
let scroll_controller =
gtk::EventControllerScroll::new(gtk::EventControllerScrollFlags::BOTH_AXES);
scroll_controller.connect_scroll(|eventcontroller, _, delta_y| {
let event = eventcontroller.current_event().unwrap(); // We are inside the event handler, so it must have an event
if event
.modifier_state()
.contains(gdk::ModifierType::CONTROL_MASK)
{
let widget = eventcontroller
.widget()
.downcast::<super::GraphView>()
.unwrap();
widget.set_zoom_factor(widget.zoom_factor() + (0.1 * -delta_y), None);
glib::Propagation::Stop
} else {
glib::Propagation::Proceed
}
});
self.obj().add_controller(scroll_controller);
}
fn setup_zoom_gesture(&self) {
let zoom_gesture = gtk::GestureZoom::new();
zoom_gesture.connect_begin(|gesture, _| {
let widget = gesture.widget().downcast::<super::GraphView>().unwrap();
widget
.imp()
.zoom_gesture_initial_zoom
.set(Some(widget.zoom_factor()));
widget
.imp()
.zoom_gesture_anchor
.set(gesture.bounding_box_center());
});
zoom_gesture.connect_scale_changed(move |gesture, delta| {
let widget = gesture.widget().downcast::<super::GraphView>().unwrap();
let initial_zoom = widget
.imp()
.zoom_gesture_initial_zoom
.get()
.expect("Initial zoom not set during zoom gesture");
widget.set_zoom_factor(initial_zoom * delta, gesture.bounding_box_center());
});
self.obj().add_controller(zoom_gesture);
}
fn draw_link(
&self,
link_cr: &cairo::Context,
output_anchor: &Point,
input_anchor: &Point,
active: bool,
color: &gdk::RGBA,
) {
let output_x: f64 = output_anchor.x().into();
let output_y: f64 = output_anchor.y().into();
let input_x: f64 = input_anchor.x().into();
let input_y: f64 = input_anchor.y().into();
// Use dashed line for inactive links, full line otherwise.
if active {
link_cr.set_dash(&[], 0.0);
} else {
link_cr.set_dash(&[10.0, 5.0], 0.0);
}
link_cr.set_source_rgba(
color.red().into(),
color.green().into(),
color.blue().into(),
color.alpha().into(),
);
// If the output port is farther right than the input port and they have
// a similar y coordinate, apply a y offset to the control points
// so that the curve sticks out a bit.
let y_control_offset = if output_x > input_x {
f64::max(0.0, 25.0 - (output_y - input_y).abs())
} else {
0.0
};
// Place curve control offset by half the x distance between the two points.
// This makes the curve scale well for varying distances between the two ports,
// especially when the output port is farther right than the input port.
let half_x_dist = f64::abs(output_x - input_x) / 2.0;
link_cr.move_to(output_x, output_y);
link_cr.curve_to(
output_x + half_x_dist,
output_y - y_control_offset,
input_x - half_x_dist,
input_y - y_control_offset,
input_x,
input_y,
);
if let Err(e) = link_cr.stroke() {
warn!("Failed to draw graphview links: {}", e);
};
}
fn draw_dragged_link(&self, port: &Port, link_cr: &cairo::Context, colors: &Colors) {
let Some(port_anchor) = port.compute_point(&*self.obj(), &port.link_anchor()) else {
return;
};
let drag_cursor = self.port_drag_cursor.get();
/* If we can find a linkable port under the cursor, link to its anchor,
* otherwise link to the mouse cursor */
let picked_port = self
.obj()
.pick(
drag_cursor.x().into(),
drag_cursor.y().into(),
gtk::PickFlags::DEFAULT,
)
.and_then(|widget| widget.ancestor(Port::static_type()).and_downcast::<Port>())
.filter(|picked_port| port.is_linkable_to(picked_port));
let picked_port_anchor = picked_port.and_then(|picked_port| {
picked_port.compute_point(&*self.obj(), &picked_port.link_anchor())
});
let other_anchor = picked_port_anchor.unwrap_or(drag_cursor);
let (output_anchor, input_anchor) = match Direction::from_raw(port.direction()) {
Direction::Output => (&port_anchor, &other_anchor),
Direction::Input => (&other_anchor, &port_anchor),
_ => unreachable!(),
};
let color = &colors.color_for_media_type(MediaType::from_raw(port.media_type()));
self.draw_link(link_cr, output_anchor, input_anchor, false, color);
}
fn snapshot_links(&self, widget: &super::GraphView, snapshot: &gtk::Snapshot) {
let alloc = widget.allocation();
let link_cr = snapshot.append_cairo(&graphene::Rect::new(
0.0,
0.0,
alloc.width() as f32,
alloc.height() as f32,
));
link_cr.set_line_width(2.0 * self.zoom_factor.get());
let colors = Colors {
audio: widget
.style_context()
.lookup_color("media-type-audio")
.expect("color not found"),
video: widget
.style_context()
.lookup_color("media-type-video")
.expect("color not found"),
midi: widget
.style_context()
.lookup_color("media-type-midi")
.expect("color not found"),
unknown: widget
.style_context()
.lookup_color("media-type-unknown")
.expect("color not found"),
};
for link in self.links.borrow().iter() {
let color = &colors.color_for_media_type(link.media_type());
// TODO: Do not draw links when they are outside the view
let Some((output_anchor, input_anchor)) = self.get_link_coordinates(link) else {
warn!("Could not get allocation of ports of link: {:?}", link);
continue;
};
self.draw_link(
&link_cr,
&output_anchor,
&input_anchor,
link.active(),
color,
);
}
if let Some(port) = self.dragged_port.upgrade() {
self.draw_dragged_link(&port, &link_cr, &colors);
}
}
/// Get coordinates for the drawn link to start at and to end at.
///
/// # Returns
/// `Some((output_anchor, input_anchor))` if all objects the links refers to exist as widgets
/// and those widgets are contained by the graph.
///
/// The returned coordinates are in screen-space of the graph.
fn get_link_coordinates(&self, link: &Link) -> Option<(graphene::Point, graphene::Point)> {
let widget = &*self.obj();
let output_port = link.output_port()?;
let output_anchor = output_port.compute_point(widget, &output_port.link_anchor())?;
let input_port = link.input_port()?;
let input_anchor = input_port.compute_point(widget, &input_port.link_anchor())?;
Some((output_anchor, input_anchor))
}
fn set_adjustment(
&self,
obj: &super::GraphView,
adjustment: Option<&gtk::Adjustment>,
orientation: gtk::Orientation,
) {
match orientation {
gtk::Orientation::Horizontal => {
*self.hadjustment.borrow_mut() = adjustment.cloned()
}
gtk::Orientation::Vertical => *self.vadjustment.borrow_mut() = adjustment.cloned(),
_ => unimplemented!(),
}
if let Some(adjustment) = adjustment {
adjustment
.connect_value_changed(clone!(@weak obj => move |_| obj.queue_allocate() ));
}
}
fn set_adjustment_values(
&self,
obj: &super::GraphView,
adjustment: &gtk::Adjustment,
orientation: gtk::Orientation,
) {
let size = match orientation {
gtk::Orientation::Horizontal => obj.width(),
gtk::Orientation::Vertical => obj.height(),
_ => unimplemented!(),
};
let zoom_factor = self.zoom_factor.get();
adjustment.configure(
adjustment.value(),
-(CANVAS_SIZE / 2.0) * zoom_factor,
(CANVAS_SIZE / 2.0) * zoom_factor,
(f64::from(size) * 0.1) * zoom_factor,
(f64::from(size) * 0.9) * zoom_factor,
f64::from(size) * zoom_factor,
);
}
}
}
glib::wrapper! {
pub struct GraphView(ObjectSubclass<imp::GraphView>)
@extends gtk::Widget;
}
impl GraphView {
pub const ZOOM_MIN: f64 = 0.3;
pub const ZOOM_MAX: f64 = 4.0;
pub fn new() -> Self {
glib::Object::new()
}
pub fn zoom_factor(&self) -> f64 {
self.property("zoom-factor")
}
/// Set the scale factor.
///
/// A factor of 1.0 is equivalent to 100% zoom, 0.5 to 50% zoom etc.
///
/// An optional anchor (in canvas-space coordinates) can be specified, which will be used as the center of the zoom,
/// so that its position stays fixed.
/// If no anchor is specified, the middle of the screen is used instead.
///
/// Note that the zoom level is [clamped](`f64::clamp`) to between 30% and 300%.
/// See [`Self::ZOOM_MIN`] and [`Self::ZOOM_MAX`].
pub fn set_zoom_factor(&self, zoom_factor: f64, anchor: Option<(f64, f64)>) {
let zoom_factor = zoom_factor.clamp(Self::ZOOM_MIN, Self::ZOOM_MAX);
let (anchor_x_screen, anchor_y_screen) = anchor.unwrap_or_else(|| {
(
self.allocation().width() as f64 / 2.0,
self.allocation().height() as f64 / 2.0,
)
});
let old_zoom = self.imp().zoom_factor.get();
let hadjustment_ref = self.imp().hadjustment.borrow();
let vadjustment_ref = self.imp().vadjustment.borrow();
let hadjustment = hadjustment_ref.as_ref().unwrap();
let vadjustment = vadjustment_ref.as_ref().unwrap();
let x_total = (anchor_x_screen + hadjustment.value()) / old_zoom;
let y_total = (anchor_y_screen + vadjustment.value()) / old_zoom;
let new_hadjustment = x_total * zoom_factor - anchor_x_screen;
let new_vadjustment = y_total * zoom_factor - anchor_y_screen;
hadjustment.set_value(new_hadjustment);
vadjustment.set_value(new_vadjustment);
self.set_property("zoom-factor", zoom_factor);
}
pub fn add_node(&self, node: Node, node_type: Option<NodeType>) {
let imp = self.imp();
node.set_parent(self);
// Place widgets in colums of 3, growing down
let x = if let Some(node_type) = node_type {
match node_type {
NodeType::Output => 20.0,
NodeType::Input => 820.0,
}
} else {
420.0
};
let y = imp
.nodes
.borrow()
.iter()
.map(|node| {
// Map nodes to their locations
let point = self.node_position(&node.0.clone().upcast()).unwrap();
(point.x(), point.y())
})
.filter(|(x2, _)| {
// Only look for other nodes that have a similar x coordinate
(x - x2).abs() < 50.0
})
.max_by(|y1, y2| {
// Get max in column
y1.partial_cmp(y2).unwrap_or(Ordering::Equal)
})
.map_or(20_f32, |(_x, y)| y + 120.0);
imp.nodes.borrow_mut().insert(node, Point::new(x, y));
}
pub fn remove_node(&self, node: &Node) {
let mut nodes = self.imp().nodes.borrow_mut();
if nodes.remove(node).is_some() {
node.unparent();
} else {
log::warn!("Tried to remove non-existant node widget from graph");
}
}
pub fn add_link(&self, link: Link) {
link.connect_notify_local(
Some("active"),
glib::clone!(@weak self as graph => move |_, _| {
graph.queue_draw();
}),
);
link.connect_notify_local(
Some("media-type"),
glib::clone!(@weak self as graph => move |_, _| {
graph.queue_draw();
}),
);
self.imp().links.borrow_mut().insert(link);
self.queue_draw();
}
pub fn remove_link(&self, link: &Link) {
let mut links = self.imp().links.borrow_mut();
links.remove(link);
self.queue_draw();
}
pub fn clear(&mut self) {
self.imp().links.borrow_mut().clear();
for (node, _) in self.imp().nodes.borrow_mut().drain() {
node.unparent();
}
self.queue_draw();
}
/// Get the position of the specified node inside the graphview.
///
/// The returned position is in canvas-space (non-zoomed, (0, 0) fixed in the middle of the canvas).
pub(super) fn node_position(&self, node: &Node) -> Option<Point> {
self.imp().nodes.borrow().get(node).copied()
}
pub(super) fn move_node(&self, widget: &Node, point: &Point) {
let mut nodes = self.imp().nodes.borrow_mut();
let node_point = nodes.get_mut(widget).expect("Node is not on the graph");
// Clamp the new position to within the graph, so a node can't be moved outside it and be lost.
node_point.set_x(point.x().clamp(
-(CANVAS_SIZE / 2.0) as f32,
(CANVAS_SIZE / 2.0) as f32 - widget.width() as f32,
));
node_point.set_y(point.y().clamp(
-(CANVAS_SIZE / 2.0) as f32,
(CANVAS_SIZE / 2.0) as f32 - widget.height() as f32,
));
self.queue_allocate();
}
}
impl Default for GraphView {
fn default() -> Self {
Self::new()
}
}

148
src/ui/graph/link.rs Normal file
View File

@@ -0,0 +1,148 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{glib, prelude::*, subclass::prelude::*};
use pipewire::spa::format::MediaType;
use super::Port;
mod imp {
use super::*;
use std::cell::Cell;
use once_cell::sync::Lazy;
pub struct Link {
pub output_port: glib::WeakRef<Port>,
pub input_port: glib::WeakRef<Port>,
pub active: Cell<bool>,
pub media_type: Cell<MediaType>,
}
impl Default for Link {
fn default() -> Self {
Self {
output_port: glib::WeakRef::default(),
input_port: glib::WeakRef::default(),
active: Cell::default(),
media_type: Cell::new(MediaType::Unknown),
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for Link {
const NAME: &'static str = "HelvumLink";
type Type = super::Link;
type ParentType = glib::Object;
}
impl ObjectImpl for Link {
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
vec![
glib::ParamSpecObject::builder::<Port>("output-port")
.flags(glib::ParamFlags::READWRITE)
.build(),
glib::ParamSpecObject::builder::<Port>("input-port")
.flags(glib::ParamFlags::READWRITE)
.build(),
glib::ParamSpecBoolean::builder("active")
.default_value(false)
.flags(glib::ParamFlags::READWRITE)
.build(),
glib::ParamSpecUInt::builder("media-type")
.default_value(MediaType::Unknown.as_raw())
.flags(glib::ParamFlags::READWRITE)
.build(),
]
});
PROPERTIES.as_ref()
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
match pspec.name() {
"output-port" => self.output_port.upgrade().to_value(),
"input-port" => self.input_port.upgrade().to_value(),
"active" => self.active.get().to_value(),
"media-type" => self.media_type.get().as_raw().to_value(),
_ => unimplemented!(),
}
}
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
match pspec.name() {
"output-port" => self.output_port.set(value.get().unwrap()),
"input-port" => self.input_port.set(value.get().unwrap()),
"active" => self.active.set(value.get().unwrap()),
"media-type" => self
.media_type
.set(MediaType::from_raw(value.get().unwrap())),
_ => unimplemented!(),
}
}
}
}
glib::wrapper! {
pub struct Link(ObjectSubclass<imp::Link>);
}
impl Link {
pub fn new() -> Self {
glib::Object::new()
}
pub fn output_port(&self) -> Option<Port> {
self.property("output-port")
}
pub fn set_output_port(&self, port: Option<&Port>) {
self.set_property("output-port", port);
}
pub fn input_port(&self) -> Option<Port> {
self.property("input-port")
}
pub fn set_input_port(&self, port: Option<&Port>) {
self.set_property("input-port", port);
}
pub fn active(&self) -> bool {
self.property("active")
}
pub fn set_active(&self, active: bool) {
self.set_property("active", active);
}
pub fn media_type(&self) -> MediaType {
MediaType::from_raw(self.property("media-type"))
}
pub fn set_media_type(&self, media_type: MediaType) {
self.set_property("media-type", media_type.as_raw())
}
}
impl Default for Link {
fn default() -> Self {
Self::new()
}
}

28
src/ui/graph/mod.rs Normal file
View File

@@ -0,0 +1,28 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
mod graph_view;
pub use graph_view::*;
mod node;
pub use node::*;
mod port;
pub use port::*;
mod port_handle;
pub use port_handle::*;
mod link;
pub use link::*;
mod zoomentry;
pub use zoomentry::*;

163
src/ui/graph/node.rs Normal file
View File

@@ -0,0 +1,163 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{glib, gtk, prelude::*, subclass::prelude::*};
use pipewire::spa::Direction;
use super::Port;
mod imp {
use super::*;
use std::{
cell::{Cell, RefCell},
collections::HashSet,
};
#[derive(glib::Properties, gtk::CompositeTemplate, Default)]
#[properties(wrapper_type = super::Node)]
#[template(file = "node.ui")]
pub struct Node {
#[property(get, set, construct_only)]
pub(super) pipewire_id: Cell<u32>,
#[property(
name = "name", type = String,
get = |this: &Self| this.label.text().to_string(),
set = |this: &Self, val| {
this.label.set_text(val);
this.label.set_tooltip_text(Some(val));
}
)]
#[template_child]
pub(super) label: TemplateChild<gtk::Label>,
#[template_child]
pub(super) separator: TemplateChild<gtk::Separator>,
#[template_child]
pub(super) port_grid: TemplateChild<gtk::Grid>,
pub(super) ports: RefCell<HashSet<Port>>,
}
#[glib::object_subclass]
impl ObjectSubclass for Node {
const NAME: &'static str = "HelvumNode";
type Type = super::Node;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.set_layout_manager_type::<gtk::BoxLayout>();
klass.bind_template();
klass.set_css_name("node");
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
#[glib::derived_properties]
impl ObjectImpl for Node {
fn constructed(&self) {
self.parent_constructed();
// Display a grab cursor when the mouse is over the label so the user knows the node can be dragged.
self.label
.set_cursor(gtk::gdk::Cursor::from_name("grab", None).as_ref());
}
fn dispose(&self) {
if let Some(child) = self.obj().first_child() {
child.unparent();
}
}
}
impl WidgetImpl for Node {}
impl Node {
/// Update the internal ports grid to reflect the ports stored in the ports set.
pub fn update_ports(&self) {
// We first remove all ports from the grid, then re-add them all, so that
// ports that have been removed do not leave gaps in the grid.
while let Some(ref child) = self.port_grid.first_child() {
self.port_grid.remove(child);
}
let ports = self.ports.borrow();
let mut ports_out = Vec::new();
let mut ports_in = Vec::new();
ports
.iter()
.for_each(|port| match Direction::from_raw(port.direction()) {
Direction::Output => {
ports_out.push(port);
}
Direction::Input => {
ports_in.push(port);
}
_ => unreachable!(),
});
ports_out.sort_unstable_by_key(|port| port.name());
ports_in.sort_unstable_by_key(|port| port.name());
// In case no ports have been added to the port, hide the seperator as it is not needed
self.separator
.set_visible(!ports_out.is_empty() || !ports_in.is_empty());
for (i, port) in ports_in.into_iter().enumerate() {
self.port_grid.attach(port, 0, i.try_into().unwrap(), 1, 1);
}
for (i, port) in ports_out.into_iter().enumerate() {
self.port_grid.attach(port, 1, i.try_into().unwrap(), 1, 1);
}
}
}
}
glib::wrapper! {
pub struct Node(ObjectSubclass<imp::Node>)
@extends gtk::Widget;
}
impl Node {
pub fn new(name: &str, pipewire_id: u32) -> Self {
glib::Object::builder()
.property("name", name)
.property("pipewire-id", pipewire_id)
.build()
}
pub fn add_port(&self, port: Port) {
let imp = self.imp();
imp.ports.borrow_mut().insert(port);
imp.update_ports();
}
pub fn remove_port(&self, port: &Port) {
let imp = self.imp();
if imp.ports.borrow_mut().remove(port) {
imp.update_ports();
} else {
log::warn!("Tried to remove non-existant port widget from node");
}
}
}

34
src/ui/graph/node.ui Normal file
View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk" version="4.0"/>
<template class="HelvumNode" parent="GtkWidget">
<style>
<class name="card"></class>
</style>>
<child>
<object class="GtkBox">
<property name="orientation">vertical</property>
<child>
<object class="GtkLabel" id="label">
<style>
<class name="heading"></class>
</style>
<property name="wrap">true</property>
<property name="ellipsize">PANGO_ELLIPSIZE_END</property>
<property name="lines">2</property>
<property name="max-width-chars">20</property>
</object>
</child>
<child>
<object class="GtkSeparator" id="separator">
<!-- The node will show the seperator only once ports are added to it -->
<property name="visible">false</property>
</object>
</child>
<child>
<object class="GtkGrid" id="port_grid"></object>
</child>
</object>
</child>
</template>
</interface>

361
src/ui/graph/port.rs Normal file
View File

@@ -0,0 +1,361 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{
gdk,
glib::{self, subclass::Signal},
gtk::{self, graphene},
prelude::*,
subclass::prelude::*,
};
use pipewire::spa::Direction;
use super::PortHandle;
mod imp {
use super::*;
use std::cell::Cell;
use once_cell::{sync::Lazy, unsync::OnceCell};
use pipewire::spa::{format::MediaType, Direction};
/// Graphical representation of a pipewire port.
#[derive(gtk::CompositeTemplate, glib::Properties)]
#[properties(wrapper_type = super::Port)]
#[template(file = "port.ui")]
pub struct Port {
#[property(get, set, construct_only)]
pub(super) pipewire_id: OnceCell<u32>,
#[property(
type = u32,
get = |_| self.media_type.get().as_raw(),
set = Self::set_media_type
)]
pub(super) media_type: Cell<MediaType>,
#[property(
type = u32,
get = |_| self.direction.get().as_raw(),
set = Self::set_direction,
construct_only
)]
pub(super) direction: Cell<Direction>,
#[property(
name = "name", type = String,
get = |this: &Self| this.label.text().to_string(),
set = |this: &Self, val| {
this.label.set_text(val);
this.label.set_tooltip_text(Some(val));
}
)]
#[template_child]
pub(super) label: TemplateChild<gtk::Label>,
#[template_child]
pub(super) handle: TemplateChild<PortHandle>,
}
impl Default for Port {
fn default() -> Self {
Self {
pipewire_id: OnceCell::default(),
media_type: Cell::new(MediaType::Unknown),
direction: Cell::new(Direction::Output),
label: TemplateChild::default(),
handle: TemplateChild::default(),
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for Port {
const NAME: &'static str = "HelvumPort";
type Type = super::Port;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.set_css_name("port");
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
#[glib::derived_properties]
impl ObjectImpl for Port {
fn constructed(&self) {
self.parent_constructed();
// Display a grab cursor when the mouse is over the port so the user knows it can be dragged to another port.
self.obj()
.set_cursor(gtk::gdk::Cursor::from_name("grab", None).as_ref());
self.setup_port_drag_and_drop();
}
fn signals() -> &'static [Signal] {
static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
vec![Signal::builder("port-toggled")
// Provide id of output port and input port to signal handler.
.param_types([<u32>::static_type(), <u32>::static_type()])
.build()]
});
SIGNALS.as_ref()
}
}
impl WidgetImpl for Port {
fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) {
match orientation {
gtk::Orientation::Horizontal => {
let (min_handle_width, nat_handle_width, _, _) =
self.handle.measure(orientation, for_size);
let (min_label_width, nat_label_width, _, _) = self
.label
.measure(orientation, i32::max(for_size - (nat_handle_width / 2), -1));
(
(min_handle_width / 2) + min_label_width,
(nat_handle_width / 2) + nat_label_width,
-1,
-1,
)
}
gtk::Orientation::Vertical => {
let (min_label_height, nat_label_height, _, _) =
self.label.measure(orientation, for_size);
let (min_handle_height, nat_handle_height, _, _) =
self.handle.measure(orientation, for_size);
(
i32::max(min_label_height, min_handle_height),
i32::max(nat_label_height, nat_handle_height),
-1,
-1,
)
}
_ => unimplemented!(),
}
}
fn size_allocate(&self, width: i32, height: i32, _baseline: i32) {
let (_, nat_handle_height, _, _) =
self.handle.measure(gtk::Orientation::Vertical, height);
let (_, nat_handle_width, _, _) =
self.handle.measure(gtk::Orientation::Horizontal, width);
match Direction::from_raw(self.obj().direction()) {
Direction::Input => {
let alloc = gtk::Allocation::new(
-nat_handle_width / 2,
(height - nat_handle_height) / 2,
nat_handle_width,
nat_handle_height,
);
self.handle.size_allocate(&alloc, -1);
let alloc = gtk::Allocation::new(
nat_handle_width / 2,
0,
width - (nat_handle_width / 2),
height,
);
self.label.size_allocate(&alloc, -1);
}
Direction::Output => {
let alloc = gtk::Allocation::new(
width - (nat_handle_width / 2),
(height - nat_handle_height) / 2,
nat_handle_width,
nat_handle_height,
);
self.handle.size_allocate(&alloc, -1);
let alloc = gtk::Allocation::new(0, 0, width - (nat_handle_width / 2), height);
self.label.size_allocate(&alloc, -1);
}
_ => unreachable!(),
}
}
}
impl Port {
fn setup_port_drag_and_drop(&self) {
let obj = &*self.obj();
// Add a drag source and drop target controller with the type depending on direction,
// they will be responsible for link creation by dragging an output port onto an input port or the other way around.
// The port will simply provide its pipewire id to the drag target.
// The drop target will accept the source port and use it to emit its `port-toggled` signal.
// FIXME: We should protect against different media types, e.g. it should not be possible to drop a video port on an audio port.
let drag_src = gtk::DragSource::builder()
.content(&gdk::ContentProvider::for_value(&obj.to_value()))
.build();
// Override the default drag icon with an empty one so that only a grab cursor is shown.
// The graph will render a link from the source port to the cursor to visualize the drag instead.
drag_src.set_icon(Some(&gdk::Paintable::new_empty(0, 0)), 0, 0);
drag_src.connect_drag_begin(|drag_source, _| {
let port = drag_source
.widget()
.dynamic_cast::<super::Port>()
.expect("Widget should be a Port");
log::trace!("Drag started from port {}", port.pipewire_id());
});
drag_src.connect_drag_cancel(|drag_source, _, _| {
let port = drag_source
.widget()
.dynamic_cast::<super::Port>()
.expect("Widget should be a Port");
log::trace!("Drag from port {} was cancelled", port.pipewire_id());
false
});
obj.add_controller(drag_src);
let drop_target =
gtk::DropTarget::new(super::Port::static_type(), gdk::DragAction::COPY);
drop_target.set_preload(true);
drop_target.connect_value_notify(|drop_target| {
let port = drop_target
.widget()
.dynamic_cast::<super::Port>()
.expect("Widget should be a Port");
let Some(value) = drop_target.value() else {
return;
};
let other_port: super::Port = value.get().expect("Drop value should be a port");
// Disallow drags between two ports that have the same direction
if !port.is_linkable_to(&other_port) {
// FIXME: For some reason, this prints error:
// "gdk_drop_get_actions: assertion 'GDK_IS_DROP (self)' failed"
drop_target.reject();
}
});
drop_target.connect_drop(|drop_target, val, _, _| {
let port = drop_target
.widget()
.dynamic_cast::<super::Port>()
.expect("Widget should be a Port");
let other_port = val
.get::<super::Port>()
.expect("Dropped value should be a Port");
// Do not accept a drop between imcompatible ports
if !port.is_linkable_to(&other_port) {
log::warn!("Tried to link incompatible ports");
return false;
}
let (output_port, input_port) = match Direction::from_raw(port.direction()) {
Direction::Output => (&port, &other_port),
Direction::Input => (&other_port, &port),
_ => unreachable!(),
};
port.emit_by_name::<()>(
"port-toggled",
&[&output_port.pipewire_id(), &input_port.pipewire_id()],
);
true
});
obj.add_controller(drop_target);
}
fn set_media_type(&self, media_type: u32) {
let media_type = MediaType::from_raw(media_type);
self.media_type.set(media_type);
for css_class in ["video", "audio", "midi"] {
self.handle.remove_css_class(css_class)
}
// Color the port according to its media type.
match media_type {
MediaType::Video => self.handle.add_css_class("video"),
MediaType::Audio => self.handle.add_css_class("audio"),
MediaType::Application | MediaType::Stream => self.handle.add_css_class("midi"),
_ => {}
}
}
fn set_direction(&self, direction: u32) {
let direction = Direction::from_raw(direction);
self.direction.set(direction);
match direction {
Direction::Input => {
self.obj().set_halign(gtk::Align::Start);
self.label.set_halign(gtk::Align::Start);
}
Direction::Output => {
self.obj().set_halign(gtk::Align::End);
self.label.set_halign(gtk::Align::End);
}
_ => unreachable!(),
}
}
}
}
glib::wrapper! {
pub struct Port(ObjectSubclass<imp::Port>)
@extends gtk::Widget;
}
impl Port {
pub fn new(id: u32, name: &str, direction: Direction) -> Self {
glib::Object::builder()
.property("pipewire-id", id)
.property("direction", direction.as_raw())
.property("name", name)
.build()
}
pub fn link_anchor(&self) -> graphene::Point {
let style_context = self.style_context();
let padding_right: f32 = style_context.padding().right().into();
let border_right: f32 = style_context.border().right().into();
let padding_left: f32 = style_context.padding().left().into();
let border_left: f32 = style_context.border().left().into();
let direction = Direction::from_raw(self.direction());
graphene::Point::new(
match direction {
Direction::Output => self.width() as f32 + padding_right + border_right,
Direction::Input => 0.0 - padding_left - border_left,
_ => unreachable!(),
},
self.height() as f32 / 2.0,
)
}
pub fn is_linkable_to(&self, other_port: &Self) -> bool {
self.direction() != other_port.direction()
}
}

19
src/ui/graph/port.ui Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk" version="4.0"/>
<template class="HelvumPort" parent="GtkWidget">
<property name="hexpand">true</property>
<child>
<object class="GtkLabel" id="label">
<property name="wrap">true</property>
<property name="ellipsize">PANGO_ELLIPSIZE_END</property>
<property name="lines">2</property>
<property name="max-width-chars">20</property>
</object>
</child>
<child>
<object class="HelvumPortHandle" id="handle"></object>
</child>
</template>
</interface>

View File

@@ -0,0 +1,84 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
use adw::{glib, gtk, prelude::*, subclass::prelude::*};
mod imp {
use super::*;
#[derive(Default)]
pub struct PortHandle {}
#[glib::object_subclass]
impl ObjectSubclass for PortHandle {
const NAME: &'static str = "HelvumPortHandle";
type Type = super::PortHandle;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.set_css_name("port-handle");
}
}
impl ObjectImpl for PortHandle {
fn constructed(&self) {
self.parent_constructed();
let obj = &*self.obj();
obj.set_halign(gtk::Align::Center);
obj.set_valign(gtk::Align::Center);
}
}
impl WidgetImpl for PortHandle {
fn request_mode(&self) -> gtk::SizeRequestMode {
gtk::SizeRequestMode::ConstantSize
}
fn measure(&self, _orientation: gtk::Orientation, _for_size: i32) -> (i32, i32, i32, i32) {
(Self::HANDLE_SIZE, Self::HANDLE_SIZE, -1, -1)
}
}
impl PortHandle {
pub const HANDLE_SIZE: i32 = 14;
}
}
glib::wrapper! {
pub struct PortHandle(ObjectSubclass<imp::PortHandle>)
@extends gtk::Widget;
}
impl PortHandle {
pub fn new() -> Self {
glib::Object::new()
}
pub fn get_link_anchor(&self) -> gtk::graphene::Point {
gtk::graphene::Point::new(
imp::PortHandle::HANDLE_SIZE as f32 / 2.0,
imp::PortHandle::HANDLE_SIZE as f32 / 2.0,
)
}
}
impl Default for PortHandle {
fn default() -> Self {
Self::new()
}
}

172
src/ui/graph/zoomentry.rs Normal file
View File

@@ -0,0 +1,172 @@
use adw::{glib, gtk, prelude::*, subclass::prelude::*};
use super::GraphView;
mod imp {
use std::cell::RefCell;
use super::*;
use gtk::{gio, glib::clone};
use once_cell::sync::Lazy;
#[derive(gtk::CompositeTemplate)]
#[template(file = "zoomentry.ui")]
pub struct ZoomEntry {
pub graphview: RefCell<Option<GraphView>>,
#[template_child]
pub zoom_out_button: TemplateChild<gtk::Button>,
#[template_child]
pub zoom_in_button: TemplateChild<gtk::Button>,
#[template_child]
pub entry: TemplateChild<gtk::Entry>,
pub popover: gtk::PopoverMenu,
}
impl Default for ZoomEntry {
fn default() -> Self {
let menu = gio::Menu::new();
menu.append(Some("30%"), Some("win.set-zoom(0.30)"));
menu.append(Some("50%"), Some("win.set-zoom(0.50)"));
menu.append(Some("75%"), Some("win.set-zoom(0.75)"));
menu.append(Some("100%"), Some("win.set-zoom(1.0)"));
menu.append(Some("150%"), Some("win.set-zoom(1.5)"));
menu.append(Some("200%"), Some("win.set-zoom(2.0)"));
menu.append(Some("300%"), Some("win.set-zoom(3.0)"));
let popover = gtk::PopoverMenu::from_model(Some(&menu));
ZoomEntry {
graphview: Default::default(),
zoom_out_button: Default::default(),
zoom_in_button: Default::default(),
entry: Default::default(),
popover,
}
}
}
#[glib::object_subclass]
impl ObjectSubclass for ZoomEntry {
const NAME: &'static str = "HelvumZoomEntry";
type Type = super::ZoomEntry;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ZoomEntry {
fn constructed(&self) {
self.parent_constructed();
self.zoom_out_button
.connect_clicked(clone!(@weak self as imp => move |_| {
let graphview = imp.graphview.borrow();
if let Some(ref graphview) = *graphview {
graphview.set_zoom_factor(graphview.zoom_factor() - 0.1, None);
}
}));
self.zoom_in_button
.connect_clicked(clone!(@weak self as imp => move |_| {
let graphview = imp.graphview.borrow();
if let Some(ref graphview) = *graphview {
graphview.set_zoom_factor(graphview.zoom_factor() + 0.1, None);
}
}));
self.entry
.connect_activate(clone!(@weak self as imp => move |entry| {
if let Ok(zoom_factor) = entry.text().trim_matches('%').parse::<f64>() {
let graphview = imp.graphview.borrow();
if let Some(ref graphview) = *graphview {
graphview.set_zoom_factor(zoom_factor / 100.0, None);
}
}
}));
self.entry
.connect_icon_press(clone!(@weak self as imp => move |_, pos| {
if pos == gtk::EntryIconPosition::Secondary {
imp.popover.show();
}
}));
self.popover.set_parent(&self.entry.get());
}
fn dispose(&self) {
self.popover.unparent();
while let Some(child) = self.obj().first_child() {
child.unparent();
}
}
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
vec![glib::ParamSpecObject::builder::<GraphView>("zoomed-widget")
.flags(glib::ParamFlags::READWRITE | glib::ParamFlags::CONSTRUCT)
.build()]
});
PROPERTIES.as_ref()
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
match pspec.name() {
"zoomed-widget" => self.graphview.borrow().to_value(),
_ => unimplemented!(),
}
}
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
match pspec.name() {
"zoomed-widget" => {
let widget: Option<GraphView> = value.get().unwrap();
if let Some(ref widget) = widget {
widget.connect_notify_local(
Some("zoom-factor"),
clone!(@weak self as imp => move |graphview, _| {
imp.update_zoom_factor_text(graphview.zoom_factor());
}),
);
self.update_zoom_factor_text(widget.zoom_factor());
}
*self.graphview.borrow_mut() = widget;
}
_ => unimplemented!(),
}
}
}
impl WidgetImpl for ZoomEntry {}
impl BoxImpl for ZoomEntry {}
impl ZoomEntry {
/// Update the text contained in the combobox's entry to reflect the provided zoom factor.
///
/// This does not update the associated [`GraphView`]s zoom level.
fn update_zoom_factor_text(&self, zoom_factor: f64) {
self.entry
.buffer()
.set_text(format!("{factor:.0}%", factor = zoom_factor * 100.));
}
}
}
glib::wrapper! {
pub struct ZoomEntry(ObjectSubclass<imp::ZoomEntry>)
@extends gtk::Box, gtk::Widget;
}
impl ZoomEntry {
pub fn new(zoomed_widget: &GraphView) -> Self {
glib::Object::builder()
.property("zoomed-widget", zoomed_widget)
.build()
}
}

26
src/ui/graph/zoomentry.ui Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<template class="HelvumZoomEntry" parent="GtkBox">
<child>
<object class="GtkButton" id="zoom_out_button">
<property name="icon-name">zoom-out-symbolic</property>
<property name="tooltip-text">Zoom out</property>
</object>
</child>
<child>
<object class="GtkEntry" id="entry">
<property name="secondary-icon-name">go-down-symbolic</property>
<property name="input-purpose">digits</property>
</object>
</child>
<child>
<object class="GtkButton" id="zoom_in_button">
<property name="icon-name">zoom-in-symbolic</property>
<property name="tooltip-text">Zoom in</property>
</object>
</child>
<style>
<class name="linked"/>
</style>
</template>
</interface>

24
src/ui/mod.rs Normal file
View File

@@ -0,0 +1,24 @@
// Copyright 2021 Tom A. Wagner <tom.a.wagner@protonmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// 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 <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: GPL-3.0-only
//! The view presented to the user.
//!
//! This module contains gtk widgets needed to present the graphical user interface.
pub mod graph;
mod window;
pub use window::*;

65
src/ui/window.rs Normal file
View File

@@ -0,0 +1,65 @@
use adw::{gio, gtk, prelude::*, subclass::prelude::*};
use super::graph;
mod imp {
use super::*;
#[derive(Default, gtk::CompositeTemplate, glib::Properties)]
#[properties(wrapper_type = super::Window)]
#[template(file = "window.ui")]
pub struct Window {
#[template_child]
pub header_bar: TemplateChild<adw::HeaderBar>,
#[template_child]
#[property(type = adw::Banner, get = |_| self.connection_banner.clone())]
pub connection_banner: TemplateChild<adw::Banner>,
#[template_child]
#[property(type = graph::GraphView, get = |_| self.graph.clone())]
pub graph: TemplateChild<graph::GraphView>,
}
#[glib::object_subclass]
impl ObjectSubclass for Window {
const NAME: &'static str = "HelvumWindow";
type Type = super::Window;
type ParentType = adw::ApplicationWindow;
fn class_init(klass: &mut Self::Class) {
// Ensure custom types are registered
graph::GraphView::ensure_type();
graph::ZoomEntry::ensure_type();
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
#[glib::derived_properties]
impl ObjectImpl for Window {}
impl WidgetImpl for Window {}
impl WindowImpl for Window {}
impl ApplicationWindowImpl for Window {}
impl AdwApplicationWindowImpl for Window {}
}
glib::wrapper! {
pub struct Window(ObjectSubclass<imp::Window>)
@extends adw::ApplicationWindow, gtk::ApplicationWindow, gtk::Window, gtk::Widget,
@implements gio::ActionGroup, gio::ActionMap;
}
impl Window {
pub fn new() -> Self {
glib::Object::new()
}
}
impl Default for Window {
fn default() -> Self {
Self::new()
}
}

61
src/ui/window.ui Normal file
View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk" version="4.0"/>
<requires lib="Adw" version="1.0"/>
<menu id="primary_menu">
<section>
<item>
<attribute name="label">_About Helvum</attribute>
<attribute name="action">app.about</attribute>
</item>
</section>
</menu>
<template class="HelvumWindow" parent="AdwApplicationWindow">
<property name="default-width">1280</property>
<property name="default-height">720</property>
<property name="title">Helvum - Pipewire Patchbay</property>
<child>
<object class="GtkBox">
<property name="orientation">vertical</property>
<child>
<object class="AdwHeaderBar" id="header_bar">
<child type="end">
<object class="GtkBox">
<style>
<class name="toolbar"></class>
</style>
<child>
<object class="HelvumZoomEntry">
<property name="zoomed-widget">graph</property>
</object>
</child>
<child>
<object class="GtkMenuButton">
<property name="icon-name">open-menu-symbolic</property>
<property name="menu-model">primary_menu</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="AdwBanner" id="connection_banner">
<property name="title" translatable="yes">Disconnected</property>
<property name="revealed">false</property>
</object>
</child>
<child>
<object class="GtkScrolledWindow">
<child>
<object class="HelvumGraphView" id="graph">
<property name="hexpand">true</property>
<property name="vexpand">true</property>
</object>
</child>
</object>
</child>
</object>
</child>
</template>
</interface>

View File

@@ -1,285 +0,0 @@
use super::Node;
use gtk::{gdk, glib, graphene, gsk, prelude::*, subclass::prelude::*};
use std::collections::HashMap;
mod imp {
use super::*;
use std::{cell::RefCell, rc::Rc};
use log::warn;
#[derive(Default)]
pub struct GraphView {
pub(super) nodes: RefCell<HashMap<u32, Node>>,
pub(super) links: RefCell<HashMap<u32, crate::PipewireLink>>,
pub(super) dragged: Rc<RefCell<Option<gtk::Widget>>>,
}
#[glib::object_subclass]
impl ObjectSubclass for GraphView {
const NAME: &'static str = "GraphView";
type Type = super::GraphView;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
// The layout manager determines how child widgets are laid out.
klass.set_layout_manager_type::<gtk::FixedLayout>();
}
}
impl ObjectImpl for GraphView {
fn constructed(&self, obj: &Self::Type) {
self.parent_constructed(obj);
// Move the Node that is currently being dragged to the cursor position as long as Mouse Button 1 is held.
let motion_controller = gtk::EventControllerMotion::new();
motion_controller.connect_motion(|controller, x, y| {
let instance = controller
.widget()
.unwrap()
.dynamic_cast::<Self::Type>()
.unwrap();
let this = imp::GraphView::from_instance(&instance);
if let Some(ref widget) = *this.dragged.borrow() {
if controller
.current_event()
.unwrap()
.modifier_state()
.contains(gdk::ModifierType::BUTTON1_MASK)
{
instance.move_node(&widget, x as f32, y as f32);
}
};
});
obj.add_controller(&motion_controller);
}
fn dispose(&self, _obj: &Self::Type) {
self.nodes
.borrow()
.values()
.for_each(|node| node.unparent())
}
}
impl WidgetImpl for GraphView {
fn snapshot(&self, widget: &Self::Type, snapshot: &gtk::Snapshot) {
/* FIXME: A lot of hardcoded values in here.
Try to use relative units (em) and colours from the theme as much as possible. */
let alloc = widget.allocation();
let cr = snapshot
.append_cairo(&graphene::Rect::new(
0.0,
0.0,
alloc.width as f32,
alloc.height as f32,
))
.expect("Failed to get cairo context");
// Try to replace the background color with a darker one from the theme.
if let Some(rgba) = widget.style_context().lookup_color("text_view_bg") {
cr.set_source_rgb(rgba.red.into(), rgba.green.into(), rgba.blue.into());
if let Err(e) = cr.paint() {
warn!("Failed to paint graphview background: {}", e);
};
} // TODO: else log colour not found
// Draw a nice grid on the background.
cr.set_source_rgb(0.18, 0.18, 0.18);
cr.set_line_width(0.2); // TODO: Set to 1px
let mut y = 0.0;
while y < alloc.height.into() {
cr.move_to(0.0, y);
cr.line_to(alloc.width as f64, y);
y += 20.0; // TODO: Change to em;
}
let mut x = 0.0;
while x < alloc.width as f64 {
cr.move_to(x, 0.0);
cr.line_to(x, alloc.height as f64);
x += 20.0; // TODO: Change to em;
}
if let Err(e) = cr.stroke() {
warn!("Failed to draw graphview grid: {}", e);
};
// Draw all links
cr.set_line_width(2.0);
cr.set_source_rgb(0.0, 0.0, 0.0);
for link in self.links.borrow().values() {
if let Some((from_x, from_y, to_x, to_y)) = self.get_link_coordinates(link) {
cr.move_to(from_x, from_y);
cr.curve_to(from_x + 75.0, from_y, to_x - 75.0, to_y, to_x, to_y);
if let Err(e) = cr.stroke() {
warn!("Failed to draw graphview links: {}", e);
};
} else {
log::warn!("Could not get allocation of ports of link: {:?}", link);
}
}
// Draw all children
self.nodes
.borrow()
.values()
.for_each(|node| self.instance().snapshot_child(node, snapshot));
}
}
impl GraphView {
/// Get coordinates for the drawn link to start at and to end at.
///
/// # Returns
/// Some((from_x, from_y, to_x, to_y)) if all objects the links refers to exist as widgets.
fn get_link_coordinates(&self, link: &crate::PipewireLink) -> Option<(f64, f64, f64, f64)> {
let nodes = self.nodes.borrow();
// For some reason, gtk4::WidgetExt::translate_coordinates gives me incorrect values,
// so we manually calculate the needed offsets here.
let from_port = &nodes.get(&link.node_from)?.get_port(link.port_from)?;
let gtk::Allocation {
x: mut fx,
y: mut fy,
width: fw,
height: fh,
} = from_port.allocation();
let from_node = from_port
.ancestor(Node::static_type())
.expect("Port is not a child of a node");
let gtk::Allocation { x: fnx, y: fny, .. } = from_node.allocation();
fx += fnx + fw;
fy += fny + (fh / 2);
let to_port = &nodes.get(&link.node_to)?.get_port(link.port_to)?;
let gtk::Allocation {
x: mut tx,
y: mut ty,
height: th,
..
} = to_port.allocation();
let to_node = to_port
.ancestor(Node::static_type())
.expect("Port is not a child of a node");
let gtk::Allocation { x: tnx, y: tny, .. } = to_node.allocation();
tx += tnx;
ty += tny + (th / 2);
Some((fx as f64, fy as f64, tx as f64, ty as f64))
}
}
}
glib::wrapper! {
pub struct GraphView(ObjectSubclass<imp::GraphView>)
@extends gtk::Widget;
}
impl GraphView {
pub fn new() -> Self {
glib::Object::new(&[]).expect("Failed to create GraphView")
}
pub fn add_node(&self, id: u32, node: Node) {
let private = imp::GraphView::from_instance(self);
node.set_parent(self);
// Place widgets in colums of 4, growing down, then right.
// TODO: Make a better positioning algorithm.
let x = (private.nodes.borrow().len() / 4) as f32 * 400.0; // This relies on integer division rounding down.
let y = private.nodes.borrow().len() as f32 % 4.0 * 100.0;
self.move_node(&node.clone().upcast(), x, y);
private.nodes.borrow_mut().insert(id, node);
}
pub fn remove_node(&self, id: u32) {
let private = imp::GraphView::from_instance(self);
let mut nodes = private.nodes.borrow_mut();
if let Some(node) = nodes.remove(&id) {
node.unparent();
}
}
pub fn add_port(&self, node_id: u32, port_id: u32, port: crate::view::port::Port) {
let private = imp::GraphView::from_instance(self);
if let Some(node) = private.nodes.borrow_mut().get_mut(&node_id) {
node.add_port(port_id, port);
} else {
// FIXME: Log this instead
log::error!(
"Node with id {} not found when trying to add port with id {} to graph",
node_id,
port_id
);
}
}
pub fn remove_port(&self, id: u32, node_id: u32) {
let private = imp::GraphView::from_instance(self);
let nodes = private.nodes.borrow();
if let Some(node) = nodes.get(&node_id) {
node.remove_port(id);
}
}
/// Add a link to the graph.
///
/// `add_link` takes three arguments: `link_id` is the id of the link as assigned by the pipewire server,
/// `from` and `to` are the id's of the ingoing and outgoing port, respectively.
pub fn add_link(&self, link_id: u32, link: crate::PipewireLink) {
let private = imp::GraphView::from_instance(self);
private.links.borrow_mut().insert(link_id, link);
self.queue_draw();
}
pub fn remove_link(&self, id: u32) {
let private = imp::GraphView::from_instance(self);
let mut links = private.links.borrow_mut();
links.remove(&id);
self.queue_draw();
}
pub(super) fn set_dragged(&self, widget: Option<gtk::Widget>) {
*imp::GraphView::from_instance(self).dragged.borrow_mut() = widget;
}
pub(super) fn move_node(&self, node: &gtk::Widget, x: f32, y: f32) {
let layout_manager = self
.layout_manager()
.expect("Failed to get layout manager")
.dynamic_cast::<gtk::FixedLayout>()
.expect("Failed to cast to FixedLayout");
let transform = gsk::Transform::new()
// Nodes should not be able to be dragged out of the view, so we use `max(coordinate, 0.0)` to prevent that.
.translate(&graphene::Point::new(f32::max(x, 0.0), f32::max(y, 0.0)))
.unwrap();
layout_manager
.layout_child(node)
.expect("Could not get layout child")
.dynamic_cast::<gtk::FixedLayoutChild>()
.expect("Could not cast to FixedLayoutChild")
.set_transform(&transform);
// FIXME: If links become proper widgets,
// we don't need to redraw the full graph everytime.
self.queue_draw();
}
}
impl Default for GraphView {
fn default() -> Self {
Self::new()
}
}

View File

@@ -1,11 +0,0 @@
//! The view presented to the user.
//!
//! This module contains gtk widgets needed to present the graphical user interface.
mod graph_view;
mod node;
mod port;
pub use graph_view::GraphView;
pub use node::Node;
pub use port::Port;

View File

@@ -1,145 +0,0 @@
use super::graph_view::GraphView;
use gtk::{glib, prelude::*, subclass::prelude::*};
use pipewire::spa::Direction;
use std::{collections::HashMap, rc::Rc};
mod imp {
use super::*;
use std::cell::{Cell, RefCell};
pub struct Node {
pub(super) grid: gtk::Grid,
pub(super) label: gtk::Label,
pub(super) ports: RefCell<HashMap<u32, Rc<crate::view::port::Port>>>,
pub(super) num_ports_in: Cell<u32>,
pub(super) num_ports_out: Cell<u32>,
}
#[glib::object_subclass]
impl ObjectSubclass for Node {
const NAME: &'static str = "Node";
type Type = super::Node;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.set_layout_manager_type::<gtk::BinLayout>();
}
fn new() -> Self {
let grid = gtk::Grid::new();
let label = gtk::Label::new(None);
grid.attach(&label, 0, 0, 2, 1);
let motion_controller = gtk::EventControllerMotion::new();
motion_controller.connect_enter(|controller, _, _| {
// Tell the graphview that the Node is the target of a drag when the mouse enters its label
let widget = controller
.widget()
.expect("Controller with enter event has no widget")
.ancestor(super::Node::static_type())
.expect("Node label does not have a node ancestor widget");
widget
.ancestor(GraphView::static_type())
.expect("Node with enter event is not on graph")
.dynamic_cast::<GraphView>()
.unwrap()
.set_dragged(Some(widget));
});
motion_controller.connect_leave(|controller| {
// Tell the graphview that the Node is no longer the target of a drag when the mouse leaves.
// FIXME: Check that we are the current target before setting none.
controller
.widget()
.expect("Controller with leave event has no widget")
.ancestor(GraphView::static_type())
.expect("Node with leave event is not on graph")
.dynamic_cast::<GraphView>()
.unwrap()
.set_dragged(None);
});
label.add_controller(&motion_controller);
// Display a grab cursor when the mouse is over the label so the user knows the node can be dragged.
label.set_cursor(gtk::gdk::Cursor::from_name("grab", None).as_ref());
Self {
grid,
label,
ports: RefCell::new(HashMap::new()),
num_ports_in: Cell::new(0),
num_ports_out: Cell::new(0),
}
}
}
impl ObjectImpl for Node {
fn constructed(&self, obj: &Self::Type) {
self.parent_constructed(obj);
self.grid.set_parent(obj);
}
fn dispose(&self, _obj: &Self::Type) {
self.grid.unparent();
}
}
impl WidgetImpl for Node {}
}
glib::wrapper! {
pub struct Node(ObjectSubclass<imp::Node>)
@extends gtk::Widget;
}
impl Node {
pub fn new(name: &str) -> Self {
let res: Self = glib::Object::new(&[]).expect("Failed to create Node");
let private = imp::Node::from_instance(&res);
private.label.set_text(name);
res
}
pub fn add_port(&mut self, id: u32, port: super::port::Port) {
let private = imp::Node::from_instance(self);
match port.direction() {
Direction::Input => {
private
.grid
.attach(&port, 0, private.num_ports_in.get() as i32 + 1, 1, 1);
private.num_ports_in.set(private.num_ports_in.get() + 1);
}
Direction::Output => {
private
.grid
.attach(&port, 1, private.num_ports_out.get() as i32 + 1, 1, 1);
private.num_ports_out.set(private.num_ports_out.get() + 1);
}
}
private.ports.borrow_mut().insert(id, Rc::new(port));
}
pub fn get_port(&self, id: u32) -> Option<Rc<super::port::Port>> {
let private = imp::Node::from_instance(self);
private.ports.borrow_mut().get(&id).cloned()
}
pub fn remove_port(&self, id: u32) {
let private = imp::Node::from_instance(self);
if let Some(port) = private.ports.borrow_mut().remove(&id) {
match port.direction() {
Direction::Input => private.num_ports_in.set(private.num_ports_in.get() - 1),
Direction::Output => private.num_ports_in.set(private.num_ports_out.get() - 1),
}
port.unparent();
}
}
}

View File

@@ -1,130 +0,0 @@
use gtk::{
gdk,
glib::{self, subclass::Signal},
prelude::*,
subclass::prelude::*,
};
use log::warn;
use pipewire::spa::Direction;
use crate::application::MediaType;
mod imp {
use once_cell::{sync::Lazy, unsync::OnceCell};
use pipewire::spa::Direction;
use super::*;
/// Graphical representation of a pipewire port.
#[derive(Default)]
pub struct Port {
pub(super) id: OnceCell<u32>,
pub(super) direction: OnceCell<Direction>,
}
#[glib::object_subclass]
impl ObjectSubclass for Port {
const NAME: &'static str = "Port";
type Type = super::Port;
type ParentType = gtk::Button;
}
impl ObjectImpl for Port {
fn signals() -> &'static [Signal] {
static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
vec![Signal::builder(
"port-toggled",
// Provide id of output port and input port to signal handler.
&[<u32>::static_type().into(), <u32>::static_type().into()],
// signal handler sends back nothing.
<()>::static_type().into(),
)
.build()]
});
SIGNALS.as_ref()
}
}
impl WidgetImpl for Port {}
impl ButtonImpl for Port {}
}
glib::wrapper! {
pub struct Port(ObjectSubclass<imp::Port>)
@extends gtk::Button, gtk::Widget;
}
impl Port {
pub fn new(id: u32, name: &str, direction: Direction, media_type: Option<MediaType>) -> Self {
// Create the widget and initialize needed fields
let res: Self = glib::Object::new(&[]).expect("Failed to create Port");
let private = imp::Port::from_instance(&res);
private.id.set(id).expect("Port id already set");
private
.direction
.set(direction)
.expect("Port direction already set");
res.set_child(Some(&gtk::Label::new(Some(name))));
// Add either a drag source or drop target controller depending on direction,
// they will be responsible for link creation by dragging an output port onto an input port.
//
// FIXME: The type used for dragging is simply a u32.
// This means that anything that provides a u32 could be dragged onto a input port,
// leading to that port trying to create a link to an invalid output port.
// We should use a newtype instead of a plain u32.
// Additionally, this does not protect against e.g. dropping an outgoing audio port on an ingoing video port.
match direction {
Direction::Input => {
let drop_target = gtk::DropTarget::new(u32::static_type(), gdk::DragAction::COPY);
let this = res.clone();
drop_target.connect_drop(move |drop_target, val, _, _| {
if let Ok(source_id) = val.get::<u32>() {
// Get the callback registered in the widget and call it
drop_target
.widget()
.expect("Drop target has no widget")
.emit_by_name("port-toggled", &[&source_id, &this.id()])
.expect("Failed to send signal");
} else {
warn!("Invalid type dropped on ingoing port");
}
true
});
res.add_controller(&drop_target);
}
Direction::Output => {
// The port will simply provide its pipewire id to the drag target.
let drag_src = gtk::DragSourceBuilder::new()
.content(&gdk::ContentProvider::for_value(&(id.to_value())))
.build();
res.add_controller(&drag_src);
// Display a grab cursor when the mouse is over the port so the user knows it can be dragged to another port.
res.set_cursor(gtk::gdk::Cursor::from_name("grab", None).as_ref());
}
}
// Color the port according to its media type.
match media_type {
Some(MediaType::Video) => res.add_css_class("video"),
Some(MediaType::Audio) => res.add_css_class("audio"),
Some(MediaType::Midi) => res.add_css_class("midi"),
None => {}
}
res
}
pub fn id(&self) -> u32 {
let private = imp::Port::from_instance(self);
private.id.get().copied().expect("Port id is not set")
}
pub fn direction(&self) -> &Direction {
let private = imp::Port::from_instance(self);
private.direction.get().expect("Port direction is not set")
}
}