Intial GTK, swtich to Relm, basic Flatpak Build

This commit is contained in:
dav 2023-07-01 12:48:55 -05:00 committed by Conrad Kramer
parent f1d7a98491
commit 60257b256a
29 changed files with 2573 additions and 563 deletions

19
.github/workflows/build-flatpak.yml vendored Normal file
View file

@ -0,0 +1,19 @@
on:
push:
branches: [main]
pull_request:
name: Build Flatpak
jobs:
flatpak:
name: Build Flatpak
runs-on: ubuntu-latest
container:
image: bilelmoussaoui/flatpak-github-actions:gnome-45
options: --privileged
steps:
- uses: actions/checkout@v4
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
with:
bundle: Burrow.flatpak
manifest-path: burrow-gtk/com.hackclub.burrow.devel.json
cache-key: flatpak-builder-${{ github.sha }}

View file

@ -7,13 +7,14 @@ on:
- "*" - "*"
jobs: jobs:
build: build:
name: Build RPM
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
- name: Install - name: Install RPM
run: cargo install cargo-generate-rpm run: cargo install cargo-generate-rpm
- name: Build - name: Build RPM
run: | run: |
cargo build --release cargo build --release
strip -s target/release/burrow strip -s target/release/burrow

View file

@ -1,2 +1,3 @@
[workspace] [workspace]
members = ["burrow", "tun"] members = ["burrow", "tun"]
exclude = ["burrow-gtk"]

1
burrow-gtk/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
.flatpak-builder

2503
burrow-gtk/Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -3,11 +3,10 @@ name = "burrow-gtk"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
gettext-rs = { version = "0.7", features = ["gettext-system"] }
gtk = { version = "0.6", package = "gtk4" }
[dependencies.adw] [dependencies]
package = "libadwaita" relm4 = { version = "0.6.2", features = ["libadwaita"] }
version = "0.3" relm4-components = "0.6.2"
features = ["v1_2"] relm4-icons = { version = "0.6.0", features = ["plus"] }
burrow = { version = "*", path = "../burrow/" }

View file

@ -1,3 +0,0 @@
# burrow-gtk
A description of this project.

View file

@ -1,7 +1,7 @@
{ {
"app-id" : "com.hackclub.Burrow", "app-id" : "com.hackclub.burrow-devel",
"runtime" : "org.gnome.Platform", "runtime" : "org.gnome.Platform",
"runtime-version" : "44", "runtime-version" : "45",
"sdk" : "org.gnome.Sdk", "sdk" : "org.gnome.Sdk",
"sdk-extensions" : [ "sdk-extensions" : [
"org.freedesktop.Sdk.Extension.rust-stable" "org.freedesktop.Sdk.Extension.rust-stable"
@ -39,11 +39,16 @@
{ {
"name" : "burrow-gtk", "name" : "burrow-gtk",
"builddir" : true, "builddir" : true,
"buildsystem" : "meson", "subdir" : "burrow-gtk",
"buildsystem" : "simple",
"build-commands": [
"cargo build",
"install -Dm755 -t /app/bin target/debug/burrow-gtk"
],
"sources" : [ "sources" : [
{ {
"type" : "git", "type": "dir",
"url" : "file:///var/home/reesericci/Code" "path": "../"
} }
] ]
} }

View file

@ -0,0 +1,56 @@
{
"app-id" : "com.hackclub.burrow",
"runtime" : "org.gnome.Platform",
"runtime-version" : "45",
"sdk" : "org.gnome.Sdk",
"sdk-extensions" : [
"org.freedesktop.Sdk.Extension.rust-stable"
],
"command" : "burrow-gtk",
"finish-args" : [
"--share=network",
"--share=ipc",
"--socket=fallback-x11",
"--device=dri",
"--socket=wayland"
],
"build-options" : {
"append-path" : "/usr/lib/sdk/rust-stable/bin",
"build-args" : [
"--share=network"
],
"env" : {
"RUST_BACKTRACE" : "1",
"RUST_LOG" : "burrow-gtk=debug"
}
},
"cleanup" : [
"/include",
"/lib/pkgconfig",
"/man",
"/share/doc",
"/share/gtk-doc",
"/share/man",
"/share/pkgconfig",
"*.la",
"*.a"
],
"modules" : [
{
"name" : "burrow-gtk",
"builddir" : true,
"subdir" : "burrow-gtk",
"buildsystem" : "simple",
"build-commands": [
"cargo build --release",
"install -Dm755 -t /app/bin target/release/burrow-gtk"
],
"sources" : [
{
"type": "dir",
"path": "../"
}
]
}
]
}

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<component type="desktop"> <component type="desktop">
<id>com.hackclub.Burrow.desktop</id> <id>com.hackclub.burrow.desktop</id>
<project_license>GPL-3.0-or-later</project_license> <project_license>GPL-3.0-or-later</project_license>
<description> <description>
<p>No description</p> <p>No description</p>

View file

@ -1,7 +1,7 @@
[Desktop Entry] [Desktop Entry]
Name=burrow-gtk Name=Burrow
Exec=burrow-gtk Exec=burrow-gtk
Icon=com.hackclub.Burrow Icon=com.hackclub.burrow
Terminal=false Terminal=false
Type=Application Type=Application
Categories=GTK;Network Categories=GTK;Network

View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<schemalist gettext-domain="burrow-gtk"> <schemalist gettext-domain="burrow-gtk">
<schema id="com.hackclub.Burrow" path="/com/hackclub/Burrow/"> <schema id="com.hackclub.burrow" path="/com/hackclub/burrow/">
</schema> </schema>
</schemalist> </schemalist>

View file

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Before After
Before After

View file

@ -1,4 +1,4 @@
application_id = 'com.hackclub.Burrow' application_id = 'com.hackclub.burrow'
scalable_dir = join_paths('hicolor', 'scalable', 'apps') scalable_dir = join_paths('hicolor', 'scalable', 'apps')
install_data( install_data(

View file

@ -1,6 +1,6 @@
desktop_file = i18n.merge_file( desktop_file = i18n.merge_file(
input: 'com.hackclub.Burrow.desktop.in', input: 'com.hackclub.burrow.desktop.in',
output: 'com.hackclub.Burrow.desktop', output: 'com.hackclub.burrow.desktop',
type: 'desktop', type: 'desktop',
po_dir: '../po', po_dir: '../po',
install: true, install: true,
@ -13,8 +13,8 @@ if desktop_utils.found()
endif endif
appstream_file = i18n.merge_file( appstream_file = i18n.merge_file(
input: 'com.hackclub.Burrow.appdata.xml.in', input: 'com.hackclub.burrow.appdata.xml.in',
output: 'com.hackclub.Burrow.appdata.xml', output: 'com.hackclub.burrow.appdata.xml',
po_dir: '../po', po_dir: '../po',
install: true, install: true,
install_dir: join_paths(get_option('datadir'), 'appdata') install_dir: join_paths(get_option('datadir'), 'appdata')
@ -25,7 +25,7 @@ if appstream_util.found()
test('Validate appstream file', appstream_util, args: ['validate', appstream_file]) test('Validate appstream file', appstream_util, args: ['validate', appstream_file])
endif endif
install_data('com.hackclub.Burrow.gschema.xml', install_data('com.hackclub.burrow.gschema.xml',
install_dir: join_paths(get_option('datadir'), 'glib-2.0/schemas') install_dir: join_paths(get_option('datadir'), 'glib-2.0/schemas')
) )

View file

@ -1,20 +0,0 @@
project('burrow-gtk', 'rust',
version: '0.1.0',
meson_version: '>= 0.62.0',
default_options: [ 'warning_level=2', 'werror=false', ],
)
i18n = import('i18n')
gnome = import('gnome')
subdir('data')
subdir('src')
subdir('po')
gnome.post_install(
glib_compile_schemas: true,
gtk_update_icon_cache: true,
update_desktop_database: true,
)

View file

@ -1,92 +0,0 @@
use gtk::prelude::*;
use adw::subclass::prelude::*;
use gtk::{gio, glib};
use crate::config::VERSION;
use crate::BurrowGtkWindow;
mod imp {
use super::*;
#[derive(Debug, Default)]
pub struct BurrowGtkApplication {}
#[glib::object_subclass]
impl ObjectSubclass for BurrowGtkApplication {
const NAME: &'static str = "BurrowGtkApplication";
type Type = super::BurrowGtkApplication;
type ParentType = adw::Application;
}
impl ObjectImpl for BurrowGtkApplication {
fn constructed(&self) {
self.parent_constructed();
let obj = self.obj();
obj.setup_gactions();
obj.set_accels_for_action("app.quit", &["<primary>q"]);
}
}
impl ApplicationImpl for BurrowGtkApplication {
// We connect to the activate callback to create a window when the application
// has been launched. Additionally, this callback notifies us when the user
// tries to launch a "second instance" of the application. When they try
// to do that, we'll just present any existing window.
fn activate(&self) {
let application = self.obj();
// Get the current window or create one if necessary
let window = if let Some(window) = application.active_window() {
window
} else {
let window = BurrowGtkWindow::new(&*application);
window.upcast()
};
// Ask the window manager/compositor to present the window
window.present();
}
}
impl GtkApplicationImpl for BurrowGtkApplication {}
impl AdwApplicationImpl for BurrowGtkApplication {}
}
glib::wrapper! {
pub struct BurrowGtkApplication(ObjectSubclass<imp::BurrowGtkApplication>)
@extends gio::Application, gtk::Application, adw::Application,
@implements gio::ActionGroup, gio::ActionMap;
}
impl BurrowGtkApplication {
pub fn new(application_id: &str, flags: &gio::ApplicationFlags) -> Self {
glib::Object::builder()
.property("application-id", application_id)
.property("flags", flags)
.build()
}
fn setup_gactions(&self) {
let quit_action = gio::ActionEntry::builder("quit")
.activate(move |app: &Self, _, _| app.quit())
.build();
let about_action = gio::ActionEntry::builder("about")
.activate(move |app: &Self, _, _| app.show_about())
.build();
self.add_action_entries([quit_action, about_action]);
}
fn show_about(&self) {
let window = self.active_window().unwrap();
let about = adw::AboutWindow::builder()
.transient_for(&window)
.application_name("burrow-gtk")
.application_icon("com.hackclub.Burrow")
.developer_name("Hack Club")
.version(VERSION)
.developers(vec!["Hack Club"])
.copyright("© 2023 The Hack Foundation")
.build();
about.present();
}
}

View file

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/com/hackclub/Burrow">
<file preprocess="xml-stripblanks">window.ui</file>
<file preprocess="xml-stripblanks">gtk/help-overlay.ui</file>
</gresource>
</gresources>

View file

@ -1,4 +0,0 @@
pub static VERSION: &str = "0.1.0";
pub static GETTEXT_PACKAGE: &str = "burrow-gtk";
pub static LOCALEDIR: &str = "/app/share/locale";
pub static PKGDATADIR: &str = "/app/share/burrow-gtk";

View file

@ -1,4 +0,0 @@
pub static VERSION: &str = @VERSION@;
pub static GETTEXT_PACKAGE: &str = @GETTEXT_PACKAGE@;
pub static LOCALEDIR: &str = @LOCALEDIR@;
pub static PKGDATADIR: &str = @PKGDATADIR@;

View file

@ -1,24 +0,0 @@
using Gtk 4.0;
ShortcutsWindow help_overlay {
modal: true;
ShortcutsSection {
section-name: "shortcuts";
max-height: 10;
ShortcutsGroup {
title: C_("shortcut window", "General");
ShortcutsShortcut {
title: C_("shortcut window", "Show Shortcuts");
action-name: "win.show-help-overlay";
}
ShortcutsShortcut {
title: C_("shortcut window", "Quit");
action-name: "app.quit";
}
}
}
}

View file

@ -1,35 +1,87 @@
mod application; use adw::prelude::*;
mod config; use burrow::{DaemonClient, DaemonCommand, DaemonStartOptions};
mod window; use gtk::Align;
use relm4::{
component::{AsyncComponent, AsyncComponentParts, AsyncComponentSender},
prelude::*,
};
use self::application::BurrowGtkApplication; struct App {}
use self::window::BurrowGtkWindow;
use config::{GETTEXT_PACKAGE, LOCALEDIR, PKGDATADIR}; #[derive(Debug)]
use gettextrs::{bind_textdomain_codeset, bindtextdomain, textdomain}; enum Msg {
use gtk::{gio, glib}; Start,
use gtk::prelude::*; Stop,
}
fn main() -> glib::ExitCode {
// Set up gettext translations #[relm4::component(async)]
bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR).expect("Unable to bind the text domain"); impl AsyncComponent for App {
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8") type Init = ();
.expect("Unable to set the text domain encoding"); type Input = Msg;
textdomain(GETTEXT_PACKAGE).expect("Unable to switch to the text domain"); type Output = ();
type CommandOutput = ();
// Load resources
let resources = gio::Resource::load(PKGDATADIR.to_owned() + "/burrow-gtk.gresource") view! {
.expect("Could not load resources"); adw::Window {
gio::resources_register(&resources); set_title: Some("Simple app"),
set_default_size: (640, 480),
// Create a new GtkApplication. The application manages our main loop,
// application windows, integration with the window manager/compositor, and gtk::Box {
// desktop features such as file opening and single-instance applications. set_orientation: gtk::Orientation::Vertical,
let app = BurrowGtkApplication::new("com.hackclub.Burrow", &gio::ApplicationFlags::empty()); set_spacing: 5,
set_margin_all: 5,
// Run the application. This function will block until the application set_valign: Align::Center,
// exits. Upon return, we have our exit code to return to the shell. (This
// is the code you see when you do `echo $?` after running a command in a gtk::Label {
// terminal. set_label: "Burrow GTK Switch",
app.run() },
gtk::Switch {
set_halign: Align::Center,
set_hexpand: false,
set_vexpand: false,
connect_active_notify => move |switch|
sender.input(if switch.is_active() { Msg::Start } else { Msg::Stop })
},
}
}
}
async fn init(
_: Self::Init,
root: Self::Root,
sender: AsyncComponentSender<Self>,
) -> AsyncComponentParts<Self> {
let model = App {};
let widgets = view_output!();
AsyncComponentParts { model, widgets }
}
async fn update(
&mut self,
msg: Self::Input,
_sender: AsyncComponentSender<Self>,
_root: &Self::Root,
) {
match msg {
Msg::Start => {
let mut client = DaemonClient::new().await.unwrap();
client
.send_command(DaemonCommand::Start(DaemonStartOptions::default()))
.await
.unwrap();
}
Msg::Stop => {
let mut client = DaemonClient::new().await.unwrap();
client.send_command(DaemonCommand::Stop).await.unwrap();
}
}
}
}
fn main() {
let app = RelmApp::new("com.hackclub.burrow");
app.run_async::<App>(());
} }

View file

@ -1,67 +0,0 @@
pkgdatadir = join_paths(get_option('prefix'), get_option('datadir'), meson.project_name())
gnome = import('gnome')
blueprints = custom_target('blueprints',
input: files(
'gtk/help-overlay.blp',
'window.blp',
),
output: '.',
command: [find_program('blueprint-compiler'), 'batch-compile', '@OUTPUT@', '@CURRENT_SOURCE_DIR@', '@INPUT@'],
)
gnome.compile_resources('burrow-gtk',
'burrow-gtk.gresource.xml',
gresource_bundle: true,
install: true,
install_dir: pkgdatadir,
dependencies: blueprints
)
conf = configuration_data()
conf.set_quoted('VERSION', meson.project_version())
conf.set_quoted('GETTEXT_PACKAGE', 'burrow-gtk')
conf.set_quoted('LOCALEDIR', join_paths(get_option('prefix'), get_option('localedir')))
conf.set_quoted('PKGDATADIR', pkgdatadir)
configure_file(
input: 'config.rs.in',
output: 'config.rs',
configuration: conf
)
# Copy the config.rs output to the source directory.
run_command(
'cp',
join_paths(meson.project_build_root(), 'src', 'config.rs'),
join_paths(meson.project_source_root(), 'src', 'config.rs'),
check: true
)
cargo_bin = find_program('cargo')
cargo_opt = [ '--manifest-path', meson.project_source_root() / 'Cargo.toml' ]
cargo_opt += [ '--target-dir', meson.project_build_root() / 'src' ]
cargo_env = [ 'CARGO_HOME=' + meson.project_build_root() / 'cargo-home' ]
if get_option('buildtype') == 'release'
cargo_options += [ '--release' ]
rust_target = 'release'
else
rust_target = 'debug'
endif
cargo_build = custom_target(
'cargo-build',
build_by_default: true,
build_always_stale: true,
output: meson.project_name(),
console: true,
install: true,
install_dir: get_option('bindir'),
command: [
'env', cargo_env,
cargo_bin, 'build',
cargo_opt, '&&', 'cp', 'src' / rust_target / meson.project_name(), '@OUTPUT@',
]
)

View file

@ -1,48 +0,0 @@
using Gtk 4.0;
using Adw 1;
template BurrowGtkWindow : Adw.ApplicationWindow {
default-width: 600;
default-height: 400;
Box {
orientation: vertical;
HeaderBar header_bar {
[end]
MenuButton {
icon-name: "open-menu-symbolic";
menu-model: primary_menu;
}
}
Label label {
label: "Burrow GNOME";
vexpand: true;
styles [
"title-1",
]
}
}
}
menu primary_menu {
section {
item {
label: _("_Preferences");
action: "app.preferences";
}
item {
label: _("_Keyboard Shortcuts");
action: "win.show-help-overlay";
}
item {
label: _("_About Burrow-gtk");
action: "app.about";
}
}
}

View file

@ -1,51 +0,0 @@
use gtk::prelude::*;
use adw::subclass::prelude::*;
use gtk::{gio, glib};
mod imp {
use super::*;
#[derive(Debug, Default, gtk::CompositeTemplate)]
#[template(resource = "/com/hackclub/Burrow/window.ui")]
pub struct BurrowGtkWindow {
// Template widgets
#[template_child]
pub header_bar: TemplateChild<gtk::HeaderBar>,
#[template_child]
pub label: TemplateChild<gtk::Label>,
}
#[glib::object_subclass]
impl ObjectSubclass for BurrowGtkWindow {
const NAME: &'static str = "BurrowGtkWindow";
type Type = super::BurrowGtkWindow;
type ParentType = adw::ApplicationWindow;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for BurrowGtkWindow {}
impl WidgetImpl for BurrowGtkWindow {}
impl WindowImpl for BurrowGtkWindow {}
impl ApplicationWindowImpl for BurrowGtkWindow {}
impl AdwApplicationWindowImpl for BurrowGtkWindow {}
}
glib::wrapper! {
pub struct BurrowGtkWindow(ObjectSubclass<imp::BurrowGtkWindow>)
@extends gtk::Widget, gtk::Window, gtk::ApplicationWindow, adw::ApplicationWindow, @implements gio::ActionGroup, gio::ActionMap;
}
impl BurrowGtkWindow {
pub fn new<P: glib::IsA<gtk::Application>>(application: &P) -> Self {
glib::Object::builder()
.property("application", application)
.build()
}
}

View file

@ -1,8 +0,0 @@
[wrap-git]
directory = blueprint-compiler
url = https://gitlab.gnome.org/jwestman/blueprint-compiler.git
revision = main
depth = 1
[provide]
program_names = blueprint-compiler

View file

@ -1,15 +1,20 @@
use super::*; use super::*;
use std::{ascii, io, os::fd::{FromRawFd, RawFd}, os::unix::net::UnixListener as StdUnixListener, path::Path};
use std::hash::Hash;
use std::path::PathBuf;
use anyhow::anyhow; use anyhow::anyhow;
use log::log; use log::log;
use tracing::info; use std::hash::Hash;
use std::path::PathBuf;
use std::{
ascii, io,
os::fd::{FromRawFd, RawFd},
os::unix::net::UnixListener as StdUnixListener,
path::Path,
};
use tokio::{ use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::{UnixListener, UnixStream}, net::{UnixListener, UnixStream},
}; };
use tracing::debug; use tracing::debug;
use tracing::info;
#[cfg(not(target_vendor = "apple"))] #[cfg(not(target_vendor = "apple"))]
const UNIX_SOCKET_PATH: &str = "/run/burrow.sock"; const UNIX_SOCKET_PATH: &str = "/run/burrow.sock";
@ -18,16 +23,18 @@ const UNIX_SOCKET_PATH: &str = "/run/burrow.sock";
const UNIX_SOCKET_PATH: &str = "burrow.sock"; const UNIX_SOCKET_PATH: &str = "burrow.sock";
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn fetch_socket_path() -> Option<PathBuf>{ fn fetch_socket_path() -> Option<PathBuf> {
let tries = vec![ let tries = vec![
"burrow.sock".to_string(), "burrow.sock".to_string(),
format!("{}/Library/Containers/com.hackclub.burrow.network/Data/burrow.sock", format!(
std::env::var("HOME").unwrap_or_default()) "{}/Library/Containers/com.hackclub.burrow.network/Data/burrow.sock",
std::env::var("HOME").unwrap_or_default()
)
.to_string(), .to_string(),
]; ];
for path in tries{ for path in tries {
let path = PathBuf::from(path); let path = PathBuf::from(path);
if path.exists(){ if path.exists() {
return Some(path); return Some(path);
} }
} }
@ -35,11 +42,14 @@ fn fetch_socket_path() -> Option<PathBuf>{
} }
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
fn fetch_socket_path() -> Option<PathBuf>{ fn fetch_socket_path() -> Option<PathBuf> {
Some(Path::new(UNIX_SOCKET_PATH).to_path_buf()) Some(Path::new(UNIX_SOCKET_PATH).to_path_buf())
} }
pub async fn listen(cmd_tx: async_channel::Sender<DaemonCommand>, rsp_rx: async_channel::Receiver<DaemonResponse>) -> Result<()> { pub async fn listen(
cmd_tx: async_channel::Sender<DaemonCommand>,
rsp_rx: async_channel::Receiver<DaemonResponse>,
) -> Result<()> {
listen_with_optional_fd(cmd_tx, rsp_rx, None).await listen_with_optional_fd(cmd_tx, rsp_rx, None).await
} }
@ -61,14 +71,12 @@ pub(crate) async fn listen_with_optional_fd(
listener listener
} else { } else {
// Won't help all that much, if we use the async version of fs. // Won't help all that much, if we use the async version of fs.
if let Some(par) = path.parent(){ if let Some(par) = path.parent() {
std::fs::create_dir_all( std::fs::create_dir_all(par)?;
par
)?;
} }
match std::fs::remove_file(path){ match std::fs::remove_file(path) {
Err(e) if e.kind()==io::ErrorKind::NotFound => {Ok(())} Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
stuff => stuff stuff => stuff,
}?; }?;
info!("Relative path: {}", path.to_string_lossy()); info!("Relative path: {}", path.to_string_lossy());
UnixListener::bind(path)? UnixListener::bind(path)?
@ -89,7 +97,7 @@ pub(crate) async fn listen_with_optional_fd(
while let Ok(Some(line)) = lines.next_line().await { while let Ok(Some(line)) = lines.next_line().await {
info!("Got line: {}", line); info!("Got line: {}", line);
debug!("Line raw data: {:?}", line.as_bytes()); debug!("Line raw data: {:?}", line.as_bytes());
let mut res : DaemonResponse = DaemonResponseData::None.into(); let mut res: DaemonResponse = DaemonResponseData::None.into();
let req = match serde_json::from_str::<DaemonRequest>(&line) { let req = match serde_json::from_str::<DaemonRequest>(&line) {
Ok(req) => Some(req), Ok(req) => Some(req),
Err(e) => { Err(e) => {
@ -100,7 +108,6 @@ pub(crate) async fn listen_with_optional_fd(
let mut res = serde_json::to_string(&res).unwrap(); let mut res = serde_json::to_string(&res).unwrap();
res.push('\n'); res.push('\n');
if let Some(req) = req { if let Some(req) = req {
cmd_tx.send(req.command).await.unwrap(); cmd_tx.send(req.command).await.unwrap();
let res = rsp_rxc.recv().await.unwrap().with_id(req.id); let res = rsp_rxc.recv().await.unwrap().with_id(req.id);
@ -114,14 +121,14 @@ pub(crate) async fn listen_with_optional_fd(
} }
} }
#[derive(Debug)]
pub struct DaemonClient { pub struct DaemonClient {
connection: UnixStream, connection: UnixStream,
} }
impl DaemonClient { impl DaemonClient {
pub async fn new() -> Result<Self> { pub async fn new() -> Result<Self> {
let path = fetch_socket_path() let path = fetch_socket_path().ok_or(anyhow!("Failed to find socket path"))?;
.ok_or(anyhow!("Failed to find socket path"))?;
// debug!("found path: {:?}", path); // debug!("found path: {:?}", path);
let connection = UnixStream::connect(path).await?; let connection = UnixStream::connect(path).await?;
debug!("connected to socket"); debug!("connected to socket");

View file

@ -14,7 +14,9 @@ use tun::TunInterface;
// TODO Separate start and retrieve functions // TODO Separate start and retrieve functions
mod daemon; mod daemon;
pub use daemon::{DaemonCommand, DaemonResponseData, DaemonStartOptions, DaemonResponse, ServerInfo}; pub use daemon::{
DaemonClient, DaemonCommand, DaemonResponse, DaemonResponseData, DaemonStartOptions, ServerInfo,
};
#[cfg(target_vendor = "apple")] #[cfg(target_vendor = "apple")]
mod apple; mod apple;