commit 11a9f3ba50e0c6ccf1a1c3236026df5f7195ea48 Author: unspeaker Date: Thu May 23 21:18:56 2024 +0300 tabula rasa diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..eb5a316c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..5a0deed6 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,538 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anstream" +version = "0.6.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" + +[[package]] +name = "anstyle-parse" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" +dependencies = [ + "anstyle", + "windows-sys 0.48.0", +] + +[[package]] +name = "autocfg" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + +[[package]] +name = "bloop" +version = "0.0.0" +dependencies = [ + "clap", + "crossterm", + "jack", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" + +[[package]] +name = "colorchoice" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" + +[[package]] +name = "crossterm" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67" +dependencies = [ + "bitflags 1.3.2", + "crossterm_winapi", + "libc", + "mio", + "parking_lot", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + +[[package]] +name = "jack" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce722655a29b13bb98ec7e8ba9dc65d670b9b37c7b1c09775c7f7516811c5a36" +dependencies = [ + "bitflags 1.3.2", + "jack-sys", + "lazy_static", + "libc", + "log", +] + +[[package]] +name = "jack-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d70559ff166d148ccb750ddd77702af760718f3a752c731add168c22c16a9f" +dependencies = [ + "bitflags 1.3.2", + "lazy_static", + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.48.0", +] + +[[package]] +name = "parking_lot" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.5", +] + +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + +[[package]] +name = "proc-macro2" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" +dependencies = [ + "bitflags 2.5.0", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "signal-hook" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +dependencies = [ + "libc", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..9a39543a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "bloop" + +[dependencies] +jack = "0.10" +clap = { version = "4.5.4", features = [ "derive" ] } +crossterm = "0.25" diff --git a/README.md b/README.md new file mode 100644 index 00000000..3b8b3cd0 --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# That's It! + +Minimal, cross-environment user interface framework. + +## Definitions + +### User interface + +A **user interface** is a program which, repeatedly: +* **renders** information to be displayed to the user; +* **handles** input from the user; +thus interactively performing tasks until an exit condition is met. + +### Engine + +An **engine** is the underlying platform responsible for: +* Displaying your program's `render`ed output to the user +* Reading user input to be `handle`d by your program. + +For example, the `tui` engine is based on `crossterm`, +a library for rendering text user interfaces. + +### Widget + +A **widget** is any struct that implements the `Input` and `Output` +traits for a given engine `E`. This enables it to act as a component of the +user interface. Widgets may contain arbitrary state -- including other widgets. +We provide a set of basic widgets that allow you to define standard hierarchical +UI layouts. It's the implementor's responsibility to define +`render` and `handle` behaviors for custom widgets. + +### Input + +**To respond to user input**, implement the trait `Input`. +It has a single method, `handle`, which takes an input +event, and returns an engine-specific value. + +In the case of the `tui` engine, the returned value is a +`bool` corresponding to whether the input event was captured +by the current widget. Returning `true` from `render` terminates +the handling of the current event; returning `false` "bubbles" it +to the parent widget. + +### Output + +**To display data to the user**, implement the trait `Output`. +It has a single method, `render`, which takes a mutable instance +of the engine, and returns and engine-specific value. + +In the case of the `tui` engine, the returned value is `[u16;2]`, +corresponding to the size requested by the widget. This allows +the layout components to implement dynamic, responsive layouts in the +terminal. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml new file mode 100644 index 00000000..e69de29b diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs new file mode 100644 index 00000000..a22bac67 --- /dev/null +++ b/crates/engine/src/lib.rs @@ -0,0 +1,179 @@ +use std::error::Error; +use std::thread; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use crate::Cli; +use jack::{ + Control, + AsyncClient, + Client, + ClientStatus, + ClientOptions, + ClosureProcessHandler, + NotificationHandler, + ProcessScope, + ProcessHandler, + Frames, + Port, + PortId, + AudioIn, + AudioOut, + MidiIn, + MidiOut, + Transport +}; + +pub struct Jack { + client: Option, + ClosureProcessHandlerControl + Send>> + >>, + pub transport: Option, + audio_ins: BTreeMap>, + audio_outs: BTreeMap>, + midi_ins: BTreeMap>, + midi_outs: BTreeMap>, +} + +impl Jack { + pub fn init_from_cli (options: &Cli) + -> Result>, Box> + { + let jack = Self::init(&options.jack_client_name)?; + { + let jack = jack.clone(); + let mut jack = jack.lock().unwrap(); + for port in options.jack_audio_ins.iter() { + jack.add_audio_in(port)?; + } + for port in options.jack_audio_outs.iter() { + jack.add_audio_out(port)?; + } + for port in options.jack_midi_ins.iter() { + jack.add_midi_in(port)?; + } + for port in options.jack_midi_outs.iter() { + jack.add_midi_out(port)?; + } + } + Ok(jack.clone()) + } + fn init (name: &str) + -> Result>, Box> + { + let jack = Arc::new(Mutex::new(Self { + client: None, + transport: None, + audio_ins: BTreeMap::new(), + audio_outs: BTreeMap::new(), + midi_ins: BTreeMap::new(), + midi_outs: BTreeMap::new(), + })); + let (client, status) = Client::new(name, ClientOptions::NO_START_SERVER)?; + println!("Client status: {status:?}"); + let jack1 = jack.clone(); + let mut jack1 = jack1.lock().unwrap(); + let jack2 = jack.clone(); + jack1.transport = Some(client.transport()); + jack1.client = Some(client.activate_async( + Box::new(Notifications), + ClosureProcessHandler::new(Box::new( + move |_client: &Client, _ps: &ProcessScope| -> Control { + let jack = jack2.lock().expect("Failed to lock jack mutex"); + jack.read_inputs(); + jack.write_outputs(); + Control::Continue + } + ) as BoxControl + Send>) + )?); + Ok(jack) + } + fn start (&self) { + } + fn process (&self, _: &Client, ps: &ProcessScope) -> Control { + Control::Continue + } + fn add_audio_in (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, AudioIn::default())?; + self.audio_ins.insert(name.into(), port); + Ok(self) + } + fn add_audio_out (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, AudioOut::default())?; + self.audio_outs.insert(name.into(), port); + Ok(self) + } + fn add_midi_in (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, MidiIn::default())?; + self.midi_ins.insert(name.into(), port); + Ok(self) + } + fn add_midi_out (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, MidiOut::default())?; + self.midi_outs.insert(name.into(), port); + Ok(self) + } + fn read_inputs (&self) { + // read input buffers + //println!("read"); + } + fn write_outputs (&self) { + // clear output buffers + // write output buffers + //println!("write"); + } +} + +struct Notifications; + +impl NotificationHandler for Notifications { + fn thread_init (&self, _: &Client) { + } + + fn shutdown (&mut self, status: ClientStatus, reason: &str) { + } + + fn freewheel (&mut self, _: &Client, is_enabled: bool) { + } + + fn sample_rate (&mut self, _: &Client, _: Frames) -> Control { + Control::Quit + } + + fn client_registration (&mut self, _: &Client, name: &str, is_reg: bool) { + } + + fn port_registration (&mut self, _: &Client, port_id: PortId, is_reg: bool) { + } + + fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control { + Control::Continue + } + + fn ports_connected (&mut self, _: &Client, id_a: PortId, id_b: PortId, are: bool) { + } + + fn graph_reorder (&mut self, _: &Client) -> Control { + Control::Continue + } + + fn xrun (&mut self, _: &Client) -> Control { + Control::Continue + } +} diff --git a/crates/midikbd/Cargo.toml b/crates/midikbd/Cargo.toml new file mode 100644 index 00000000..f1b5c883 --- /dev/null +++ b/crates/midikbd/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "midikbd" + +[dependencies] +jack = "0.10" +clap = { version = "4.5.4", features = [ "derive" ] } +crossterm = "0.25" diff --git a/crates/midikbd/src/main.rs b/crates/midikbd/src/main.rs new file mode 100644 index 00000000..655c426c --- /dev/null +++ b/crates/midikbd/src/main.rs @@ -0,0 +1,38 @@ +extern crate clap; +extern crate crossterm; +extern crate engine; + +type StdResult = Result> + +pub fn main () -> StdResult<()> { + let cli = Cli::parse(); + let engine = run_jack_engine(move |_: &Client, _: &ProcessScope| { + Control::Continue + }); + let app = App::new() +} + +pub struct App { + sleep: std::time::Duration +} + +impl App { + fn init () -> Self { + Self { + sleep: std::time::Duration::from_millis(16) + } + } + fn run (&self) -> StdResult<()> { + loop { + self.update()?; + self.render()?; + std::thread::sleep(self.sleep); + } + } + fn update (&self) -> StdResult<()> { + } + fn render (&self) -> StdResult<()> { + use crossterm::*; + let (cols, rows) = terminal::size()?; + } +} diff --git a/crates/mixer/Cargo.toml b/crates/mixer/Cargo.toml new file mode 100644 index 00000000..e69de29b diff --git a/crates/mixer/src/main.rs b/crates/mixer/src/main.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/sampler/Cargo.toml b/crates/sampler/Cargo.toml new file mode 100644 index 00000000..e69de29b diff --git a/crates/sampler/src/main.rs b/crates/sampler/src/main.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/sequencer/Cargo.toml b/crates/sequencer/Cargo.toml new file mode 100644 index 00000000..e69de29b diff --git a/crates/sequencer/src/main.rs b/crates/sequencer/src/main.rs new file mode 100644 index 00000000..e69de29b diff --git a/crates/timebase/Cargo.toml b/crates/timebase/Cargo.toml new file mode 100644 index 00000000..e69de29b diff --git a/crates/timebase/src/lib.rs b/crates/timebase/src/lib.rs new file mode 100644 index 00000000..2954660a --- /dev/null +++ b/crates/timebase/src/lib.rs @@ -0,0 +1,46 @@ +pub struct Timebase { + /// Sample rate + rate: u64, + /// Current frame + frame: u64, + /// Beats per bar + signature: (u64, u64), + /// Beats per minute + bpm: f64, +} + +impl Timebase { + pub fn new (rate: u64, signature: (u64, u64), bpm: f64) -> Self { + Self { + rate, + frame: 0, + signature, + bpm, + } + } + pub fn seconds (&self) -> f64 { + self.frame as f64 / self.rate as f64 + } + pub fn minutes (&self) -> f64 { + self.seconds / 60.0 + } + pub fn beats (&self) -> f64 { + self.minutes / self.bpm + } + pub fn bar (&self) -> u64 { + ((self.beats() * self.signature.0 as f64) / self.signature.1 as f64) as u64 + } + pub fn beat (&self) -> u64 { + ((self.beats() * self.signature.0 as f64) % self.signature.1 as f64) as u64 + } + pub fn time_string (&self) -> String { + let minutes = self.minutes() as u64; + let seconds = self.seconds() as u64; + let milliseconds = self.seconds() - seconds; + format!("{minutes}:{seconds}.{milliseconds:03}") + } + pub fn beat_string (&self) -> String { + let beats = self.beats() as u64; + format!("{beats} {}/{}", minutes, self.beat(), self.signature.1) + } +} diff --git a/crates/transport/Cargo.toml b/crates/transport/Cargo.toml new file mode 100644 index 00000000..080b2eff --- /dev/null +++ b/crates/transport/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "bloop_transport" + +[dependencies] +jack = "0.10" +clap = { version = "4.5.4", features = [ "derive" ] } +crossterm = "0.25" + diff --git a/crates/transport/src/main.rs b/crates/transport/src/main.rs new file mode 100644 index 00000000..75acb418 --- /dev/null +++ b/crates/transport/src/main.rs @@ -0,0 +1,39 @@ +extern crate clap; +extern crate crossterm; +extern crate engine; + +type StdResult = Result> + +pub fn main () -> StdResult<()> { + let cli = Cli::parse(); + let engine = run_jack_engine(move |_: &Client, _: &ProcessScope| { + Control::Continue + }); + let app = App::new() +} + +pub struct App { + sleep: std::time::Duration, + state: TransportState, +} + +impl App { + fn init () -> Self { + Self { + sleep: std::time::Duration::from_millis(16) + } + } + fn run (&self) -> StdResult<()> { + loop { + self.update()?; + self.render()?; + std::thread::sleep(self.sleep); + } + } + fn update (&self) -> StdResult<()> { + } + fn render (&self) -> StdResult<()> { + use crossterm::*; + let (cols, rows) = terminal::size()?; + } +} diff --git a/shell.nix b/shell.nix new file mode 100644 index 00000000..47206151 --- /dev/null +++ b/shell.nix @@ -0,0 +1,8 @@ +{pkgs?import{}}:pkgs.mkShell{ + nativeBuildInputs = with pkgs; [ + pkg-config + ]; + buildInputs = with pkgs; [ + jack2 + ]; +} diff --git a/src/engine.rs b/src/engine.rs new file mode 100644 index 00000000..9e4daf29 --- /dev/null +++ b/src/engine.rs @@ -0,0 +1,2 @@ +//pub mod jack; +//pub mod tui; diff --git a/src/engine/jack.rs b/src/engine/jack.rs new file mode 100644 index 00000000..5445644f --- /dev/null +++ b/src/engine/jack.rs @@ -0,0 +1,178 @@ +use std::error::Error; +use std::thread; +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use crate::Cli; +use jack::{ + Control, + AsyncClient, + Client, + ClientStatus, + ClientOptions, + ClosureProcessHandler, + NotificationHandler, + ProcessScope, + ProcessHandler, + Frames, + Port, + PortId, + AudioIn, + AudioOut, + MidiIn, + MidiOut, + Transport +}; + +pub struct Jack { + client: OptionControl + Send>> + >>, + pub transport: Option, + audio_ins: BTreeMap>, + audio_outs: BTreeMap>, + midi_ins: BTreeMap>, + midi_outs: BTreeMap>, +} + +impl Jack { + pub fn init_from_cli (options: &Cli) + -> Result>, Box> + { + let jack = Self::init(&options.jack_client_name)?; + { + let jack = jack.clone(); + let mut jack = jack.lock().unwrap(); + for port in options.jack_audio_ins.iter() { + jack.add_audio_in(port)?; + } + for port in options.jack_audio_outs.iter() { + jack.add_audio_out(port)?; + } + for port in options.jack_midi_ins.iter() { + jack.add_midi_in(port)?; + } + for port in options.jack_midi_outs.iter() { + jack.add_midi_out(port)?; + } + } + Ok(jack.clone()) + } + fn init (name: &str) + -> Result>, Box> + { + let jack = Arc::new(Mutex::new(Self { + client: None, + transport: None, + audio_ins: BTreeMap::new(), + audio_outs: BTreeMap::new(), + midi_ins: BTreeMap::new(), + midi_outs: BTreeMap::new(), + })); + let (client, status) = Client::new(name, ClientOptions::NO_START_SERVER)?; + println!("Client status: {status:?}"); + let jack1 = jack.clone(); + let mut jack1 = jack1.lock().unwrap(); + let jack2 = jack.clone(); + jack1.transport = Some(client.transport()); + jack1.client = Some(client.activate_async( + Notifications, ClosureProcessHandler::new(Box::new( + move |_client: &Client, _ps: &ProcessScope| -> Control { + let jack = jack2.lock().expect("Failed to lock jack mutex"); + jack.read_inputs(); + jack.write_outputs(); + Control::Continue + } + ) as BoxControl + Send>) + )?); + Ok(jack) + } + fn start (&self) { + } + fn process (&self, _: &Client, ps: &ProcessScope) -> Control { + Control::Continue + } + fn add_audio_in (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, AudioIn::default())?; + self.audio_ins.insert(name.into(), port); + Ok(self) + } + fn add_audio_out (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, AudioOut::default())?; + self.audio_outs.insert(name.into(), port); + Ok(self) + } + fn add_midi_in (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, MidiIn::default())?; + self.midi_ins.insert(name.into(), port); + Ok(self) + } + fn add_midi_out (&mut self, name: &str) -> Result<&mut Self, Box> { + let port = self.client + .as_ref() + .expect("Not initialized.") + .as_client() + .register_port(name, MidiOut::default())?; + self.midi_outs.insert(name.into(), port); + Ok(self) + } + fn read_inputs (&self) { + // read input buffers + //println!("read"); + } + fn write_outputs (&self) { + // clear output buffers + // write output buffers + //println!("write"); + } +} + +struct Notifications; + +impl NotificationHandler for Notifications { + fn thread_init (&self, _: &Client) { + } + + fn shutdown (&mut self, status: ClientStatus, reason: &str) { + } + + fn freewheel (&mut self, _: &Client, is_enabled: bool) { + } + + fn sample_rate (&mut self, _: &Client, _: Frames) -> Control { + Control::Quit + } + + fn client_registration (&mut self, _: &Client, name: &str, is_reg: bool) { + } + + fn port_registration (&mut self, _: &Client, port_id: PortId, is_reg: bool) { + } + + fn port_rename (&mut self, _: &Client, id: PortId, old: &str, new: &str) -> Control { + Control::Continue + } + + fn ports_connected (&mut self, _: &Client, id_a: PortId, id_b: PortId, are: bool) { + } + + fn graph_reorder (&mut self, _: &Client) -> Control { + Control::Continue + } + + fn xrun (&mut self, _: &Client) -> Control { + Control::Continue + } +} diff --git a/src/engine/tui.rs b/src/engine/tui.rs new file mode 100644 index 00000000..434987fd --- /dev/null +++ b/src/engine/tui.rs @@ -0,0 +1,54 @@ +use std::error::Error; +use std::io::{stdout, Write}; +use std::thread::spawn; +use std::time::Duration; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{channel, Sender, Receiver} +}; + +pub struct Tui { + /// Exit flag. Setting this to true terminates the main loop. + exited: Arc, + /// Receives input events from input thread. + input: Receiver, + /// Currently handled input event + pub event: Option, + /// Output. Terminal commands are written to this. + pub output: Box, + /// Currently available screen area. + pub area: [u16; 4] +} + +impl Tui { + pub fn new () -> Result> { + let output = stdout(); + crossterm::terminal::enable_raw_mode()?; + let (tx, input) = channel::(); + let exited = Arc::new(AtomicBool::new(false)); + // Spawn the input thread + let exit_input_thread = exited.clone(); + spawn(move || { + loop { + // Exit if flag is set + if exit_input_thread.fetch_and(true, Ordering::Relaxed) { + break + } + // Listen for events and send them to the main thread + if crossterm::event::poll(Duration::from_millis(100)).is_ok() { + if tx.send(crossterm::event::read().unwrap()).is_err() { + break + } + } + } + }); + Ok(Self { + exited, + input, + event: None, + output: Box::new(output), + area: [0, 0, 0, 0] + }) + } +} diff --git a/src/looper.rs b/src/looper.rs new file mode 100644 index 00000000..3055fc7f --- /dev/null +++ b/src/looper.rs @@ -0,0 +1,54 @@ +use std::error::Error; +use std::io::Write; + +pub struct Looper { + cols: u16, + rows: u16, +} + +impl Looper { + pub fn run_tui () -> Result<(), Box> { + let mut app = Self { cols: 0, rows: 0 }; + let sleep = std::time::Duration::from_millis(16); + let mut stdout = std::io::stdout(); + loop { + app.render(&mut stdout)?; + std::thread::sleep(sleep); + } + } + fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box> { + use crossterm::{*, style::{*, Stylize}}; + let (cols, rows) = terminal::size()?; + if cols != self.cols || rows != self.rows { + self.cols = cols; + self.rows = rows; + stdout + .queue(terminal::Clear(terminal::ClearType::All))? + .queue(cursor::Hide)? + + .queue(cursor::MoveTo(1, 0))? + .queue(PrintStyledContent("[Up/Down]".yellow().bold()))? + .queue(cursor::MoveTo(1, 1))? + .queue(PrintStyledContent("Select sequence".yellow()))? + + .queue(cursor::MoveTo(18, 0))? + .queue(PrintStyledContent("[Left/Right]".yellow().bold()))? + .queue(cursor::MoveTo(18, 1))? + .queue(PrintStyledContent("Select parameter".yellow()))? + + .queue(cursor::MoveTo(36, 0))? + .queue(PrintStyledContent("[Insert/Delete]".yellow().bold()))? + .queue(cursor::MoveTo(36, 1))? + .queue(PrintStyledContent("Add/remove sequence".yellow()))? + + .queue(cursor::MoveTo(0, 3))?.queue(Print(" Name Input Length Route"))? + .queue(cursor::MoveTo(0, 4))?.queue(PrintStyledContent(" Metronome [ ] ████ Track 1".bold()))? + .queue(cursor::MoveTo(0, 5))?.queue(PrintStyledContent(" Loop 1 [ ] ████ Track 1".bold()))? + .queue(cursor::MoveTo(0, 6))?.queue(PrintStyledContent(" Loop 2 [ ] ████████ Track 2".bold()))? + .queue(cursor::MoveTo(0, 7))?.queue(PrintStyledContent(" Loop 3 [ ] ████████ Track 3".bold()))? + .flush()?; + } + Ok(()) + } +} + diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 00000000..faddaf8d --- /dev/null +++ b/src/main.rs @@ -0,0 +1,41 @@ +extern crate clap; +extern crate jack; +extern crate crossterm; + +use clap::{Parser, Subcommand}; +use std::error::Error; + +//pub mod sequence; +pub mod engine; +pub mod transport; +pub mod mixer; +pub mod looper; + +fn main () -> Result<(), Box> { + let cli = Cli::parse(); + match cli.command { + Command::Transport => + crate::transport::Transport::run_tui(), + Command::Mixer => + crate::mixer::Mixer::run_tui(), + Command::Looper => + crate::looper::Looper::run_tui(), + } +} + +#[derive(Debug, Parser)] +#[command(version, about, long_about = None)] +pub struct Cli { + #[command(subcommand)] + command: Command +} + +#[derive(Debug, Clone, Subcommand)] +pub enum Command { + /// Control the master transport + Transport, + /// Control the mixer + Mixer, + /// Control the looper + Looper, +} diff --git a/src/main_.rs b/src/main_.rs new file mode 100644 index 00000000..d578a487 --- /dev/null +++ b/src/main_.rs @@ -0,0 +1,209 @@ +extern crate clap; +extern crate jack; +extern crate crossterm; + +pub mod engine; +pub mod sequence; + +use clap::Parser; +use std::error::Error; +use std::sync::{Arc, Mutex}; +use std::io::Write; +use crossterm::QueueableCommand; +use crossterm::style::Stylize; + +use crate::engine::jack::Jack; +use crate::sequence::Time; +use crate::sequence::midi::{PPQ, MIDISequence, MIDIEvent}; + +// bloop \ +// --jack-client-name blooper +// --jack-audio-out L=system/playback_1 \ +// --jack-audio-out R=system/playback_2 \ +// --jack-midi-in 1="nanoKEY Studio [20] (capture): nanoKEY Studio nanoKEY Studio _" + +fn main () -> Result<(), Box> { + let cli = Cli::parse(); + let app = App::init(&cli)?; + let sleep = std::time::Duration::from_millis(16); + let mut stdout = std::io::stdout(); + loop { + app.render(&mut stdout)?; + std::thread::sleep(sleep); + }; + Ok(()) +} + +struct App { + jack: Arc>, + time: u64, + root: MIDISequence, + stdout: std::io::Stdout, +} + +impl App { + fn init (options: &Cli) -> Result> { + let mut root = MIDISequence::new("/", 4 * PPQ); + root.add(00 * PPQ, MIDIEvent::NoteOn(36, 100)) + .add(01 * PPQ, MIDIEvent::NoteOn(40, 100)) + .add(02 * PPQ - PPQ / 2, MIDIEvent::NoteOn(36, 100)) + .add(02 * PPQ + PPQ / 2, MIDIEvent::NoteOn(36, 100)) + .add(03 * PPQ, MIDIEvent::NoteOn(40, 100)) + .add(00 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(01 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(02 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(03 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(04 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(06 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(07 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(09 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(10 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(11 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(13 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(14 * PPQ / 4, MIDIEvent::NoteOn(44, 100)) + .add(15 * PPQ / 4, MIDIEvent::NoteOn(44, 100)); + Ok(Self { + jack: Jack::init_from_cli(&options)?, + time: 0, + root, + stdout: std::io::stdout(), + }) + } + fn render (&self, stdout: &mut std::io::Stdout) -> Result<(), Box> { + use crossterm::*; + let zoom = 8; + let (cols, rows) = terminal::size()?; + let transport = self.jack + .lock() + .expect("Failed to lock engine") + .transport.as_ref() + .expect("Failed to get transport") + .query() + .expect("Failed to query transport"); + let state = transport.state; + let frame = transport.pos.frame(); + let rate = transport.pos.frame_rate(); + let time_string = if let Some(rate) = rate { + let second = (frame as f64) / (rate as f64); + let seconds = second.floor(); + let msec = ((second - seconds) * 1000f64) as u64; + let seconds = second as u64 % 60; + let minutes = second as u64 / 60; + format!("{minutes}:{seconds:02}.{msec:03}") + } else { + "".to_string() + }; + let mut x_offset = cols / 2 - 10; + let beat_string = if let Some(rate) = rate { + let second = (frame as f64) / (rate as f64); + let minute = second / 60f64; + let bpm = 120f64; + let div = 4; + let beats = minute * bpm; + let bars = beats as u64 / div as u64; + let beat = beats as u64 % div as u64 + 1; + x_offset -= ((beats as f64 % div as f64) * 8.0) as u16; + format!("{bars} {beat}/{div}") + } else { + "".to_string() + }; + + stdout + .queue(terminal::Clear(terminal::ClearType::All))? + .queue(cursor::Hide)? + + .queue(cursor::MoveTo(1, 0))? + .queue(style::PrintStyledContent("bloop!".yellow()))? + .queue(cursor::MoveTo(1, 1))? + .queue(style::PrintStyledContent("v0.0.1".white()))? + + .queue(cursor::MoveTo(10, 0))? + .queue(style::PrintStyledContent("rate".yellow()))? + .queue(cursor::MoveTo(10, 1))? + .queue(style::PrintStyledContent(format!("{}", rate.unwrap_or(0)).white()))? + + .queue(cursor::MoveTo(18, 0))? + .queue(style::PrintStyledContent("state".yellow()))? + .queue(cursor::MoveTo(18, 1))? + .queue(style::PrintStyledContent(format!("{state:?}").white()))? + + .queue(cursor::MoveTo(28, 0))? + .queue(style::PrintStyledContent("time".yellow()))? + .queue(cursor::MoveTo(28, 1))? + .queue(style::PrintStyledContent(format!("{time_string}").white()))? + + .queue(cursor::MoveTo(40, 0))? + .queue(style::PrintStyledContent("beats".yellow()))? + .queue(cursor::MoveTo(40, 1))? + .queue(style::PrintStyledContent(format!("{beat_string}").white()))? + + .queue(cursor::MoveTo(x_offset, 3.max(rows / 2 - 2)))?; + + self.root.render(stdout, zoom)?; + + stdout + .queue(cursor::MoveTo(0, rows - 2))? + .queue(style::PrintStyledContent(" SPACE".green()))? + .queue(cursor::MoveTo(0, rows - 1))? + .queue(style::PrintStyledContent(" play ".yellow()))? + + .queue(cursor::MoveTo(8, rows - 2))? + .queue(style::PrintStyledContent(" HOME".green()))? + .queue(cursor::MoveTo(8, rows - 1))? + .queue(style::PrintStyledContent(" sync ".yellow()))? + + //.queue(style::PrintStyledContent(" ↑↓←→".green()))? + //.queue(style::PrintStyledContent(" navigate ".yellow()))? + + .queue(cursor::MoveTo(14, rows - 2))? + .queue(style::PrintStyledContent(" `".green()))? + .queue(cursor::MoveTo(14, rows - 1))? + .queue(style::PrintStyledContent(" markers ".yellow()))? + + .queue(cursor::MoveTo(23, rows - 2))? + .queue(style::PrintStyledContent(" ,".green()))? + .queue(cursor::MoveTo(23, rows - 1))? + .queue(style::PrintStyledContent(" routing ".yellow()))? + + .queue(cursor::MoveTo(32, rows - 2))? + .queue(style::PrintStyledContent(" a".green()))? + .queue(cursor::MoveTo(32, rows - 1))? + .queue(style::PrintStyledContent(" add audio ".yellow()))? + + .queue(cursor::MoveTo(43, rows - 2))? + .queue(style::PrintStyledContent(" m".green()))? + .queue(cursor::MoveTo(43, rows - 1))? + .queue(style::PrintStyledContent(" add MIDI ".yellow()))? + + .queue(cursor::MoveTo(54, rows - 2))? + .queue(style::PrintStyledContent(" o".green()))? + .queue(cursor::MoveTo(54, rows - 1))? + .queue(style::PrintStyledContent(" add OSC ".yellow()))? + .flush()?; + Ok(()) + } +} + +#[derive(Debug, Parser)] +#[command(version, about, long_about = None)] +pub struct Cli { + #[arg(long="jack-client-name", default_value="blooper")] + jack_client_name: String, + #[arg(long="jack-audio-in")] + jack_audio_ins: Vec, + #[arg(long="jack-audio-out")] + jack_audio_outs: Vec, + #[arg(long="jack-midi-in")] + jack_midi_ins: Vec, + #[arg(long="jack-midi-out")] + jack_midi_outs: Vec, +} + +enum Command { + Play, + Stop, + Rec, + Dub, + Trim, + Jump, +} diff --git a/src/mixer.rs b/src/mixer.rs new file mode 100644 index 00000000..6d884a2c --- /dev/null +++ b/src/mixer.rs @@ -0,0 +1,177 @@ +use std::error::Error; +use std::io::{stdout, Write}; +use std::thread::spawn; +use std::time::Duration; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{channel, Sender, Receiver} +}; + +pub struct Mixer { + exit: bool, + cols: u16, + rows: u16, + tracks: Vec, + selected_track: usize, + selected_column: usize, +} + +pub struct Track { + name: String, + gain: f64, + level: f64, + pan: f64, + route: String, +} + +impl Mixer { + + pub fn new () -> Self { + Self { + exit: false, + cols: 0, + rows: 0, + selected_column: 0, + selected_track: 1, + tracks: vec! [ + Track { + name: "Track 1".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 1".into() + }, + Track { + name: "Track 2".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 2".into() + }, + Track { + name: "Track 3".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 1".into() + }, + Track { + name: "Track 4".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Bus 2".into() + }, + Track { + name: "Bus 1".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Mix".into() + }, + Track { + name: "Bus 2".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Mix".into() + }, + Track { + name: "Mix".into(), gain: 0.0, level: 0.0, pan: 0.0, route: "Output".into() + }, + ] + } + } + + pub fn run_tui () -> Result<(), Box> { + let mut app = Self::new(); + let sleep = std::time::Duration::from_millis(16); + let mut stdout = std::io::stdout(); + crossterm::terminal::enable_raw_mode()?; + let (tx, input) = channel::(); + let exited = Arc::new(AtomicBool::new(false)); + // Spawn the input thread + let exit_input_thread = exited.clone(); + spawn(move || { + loop { + // Exit if flag is set + if exit_input_thread.fetch_and(true, Ordering::Relaxed) { + break + } + // Listen for events and send them to the main thread + if crossterm::event::poll(Duration::from_millis(100)).is_ok() { + if tx.send(crossterm::event::read().unwrap()).is_err() { + break + } + } + } + }); + loop { + app.render(&mut stdout)?; + app.handle(input.recv()?)?; + if app.exit { + crossterm::terminal::disable_raw_mode()?; + break + } + } + Ok(()) + } + + fn handle (&mut self, event: crossterm::event::Event) -> Result<(), Box> { + + use crossterm::event::{Event, KeyCode, KeyModifiers}; + if let Event::Key(event) = event { + match event.code { + KeyCode::Char('c') => { + if event.modifiers == KeyModifiers::CONTROL { + self.exit = true; + } + }, + KeyCode::Down => { + self.selected_track = (self.selected_track + 1) % self.tracks.len(); + println!("{}", self.selected_track); + } + KeyCode::Up => { + if self.selected_track == 0 { + self.selected_track = self.tracks.len() - 1; + } else { + self.selected_track = self.selected_track - 1; + } + println!("{}", self.selected_track); + } + _ => { + println!("{event:?}"); + } + } + } + Ok(()) + } + + fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box> { + use crossterm::{*, style::{*, Stylize}}; + let (cols, rows) = terminal::size()?; + if true || cols != self.cols || rows != self.rows { // TODO perf + self.cols = cols; + self.rows = rows; + stdout + .queue(terminal::Clear(terminal::ClearType::All))? + .queue(cursor::Hide)? + + .queue(cursor::MoveTo(1, 0))? + .queue(PrintStyledContent("[Arrows]".yellow().bold()))? + .queue(cursor::MoveTo(1, 1))? + .queue(PrintStyledContent("Navigate".yellow()))? + + .queue(cursor::MoveTo(11, 0))? + .queue(PrintStyledContent("[+/-]".yellow().bold()))? + .queue(cursor::MoveTo(11, 1))? + .queue(PrintStyledContent("Adjust value".yellow()))? + + .queue(cursor::MoveTo(25, 0))? + .queue(PrintStyledContent("[Ins/Del]".yellow().bold()))? + .queue(cursor::MoveTo(25, 1))? + .queue(PrintStyledContent("Add/remove track".yellow()))? + + .queue(cursor::MoveTo(0, 3))?.queue(Print( + " Name Gain Pre Level Pan Post Route"))?; + + for (i, track) in self.tracks.iter().enumerate() { + let row = 4 + i as u16; + let mut content = format!( + " {:7} █ {:.1}dB █ [ ] █ {:.1}dB C █ [ ] {:7} ", + track.name, + track.gain, + track.level, + track.route, + ).bold(); + if i == self.selected_track { + content = content.reverse(); + } + stdout + .queue(cursor::MoveTo(0, row))? + .queue(PrintStyledContent(content))?; + } + + stdout + .flush()?; + } + Ok(()) + } +} diff --git a/src/mixer/tui.rs b/src/mixer/tui.rs new file mode 100644 index 00000000..25ce10bd --- /dev/null +++ b/src/mixer/tui.rs @@ -0,0 +1,39 @@ +use super::Mixer; + +impl Input, bool> for Mixer { + fn handle (&mut self, engine: &mut TUI) -> Result> { + Ok(None) + } +} + +impl Output, [u16;2]> for Mixer { + fn render (&self, envine: &mut TUI) -> Result> { + + let tracks_table = Columns::new() + .add(titles) + .add(input_meters) + .add(gains) + .add(gain_meters) + .add(pres) + .add(pre_meters) + .add(levels) + .add(pans) + .add(pan_meters) + .add(posts) + .add(routes) + + Rows::new() + .add(Columns::new() + .add(Rows::new() + .add("[Arrows]".bold()) + .add("Navigate")) + .add(Rows::new() + .add("[+/-]".bold()) + .add("Adjust")) + .add(Rows::new() + .add("[Ins/Del]".bold()) + .add("Add/remove track"))) + .add(tracks_table) + .render(engine) + } +} diff --git a/src/sequence.rs b/src/sequence.rs new file mode 100644 index 00000000..17e0c371 --- /dev/null +++ b/src/sequence.rs @@ -0,0 +1,79 @@ +pub mod audio; +pub mod midi; +pub mod osc; +pub mod time; + +pub type Frame = usize; + +pub enum Time { + Fixed(Frame), + Synced(usize), +} + +//enum Event { + //Trigger, + //Gate, + //MIDI(MIDIEvent), + //Audio, + //OSC, + //Text, + //Sequence +//} + +//struct Clip { + //name: String, + //length: u64, + //start: u64, + //end: u64, + //clips: Sequence>, + //markers: Sequence>, + //audio: Sequence>, + //midi: Sequence>, + //osc: Sequence>, +//} + +//enum ClipData { + //Trigger, + //Gate, + //MIDI, + //Audio, + //OSC, + //Text, + //Clip +//} + +//impl Clip { + //fn new (name: &str, length: u64) -> Self { + //Self { + //name: name.into(), + //length, + //start: 0, + //end: length, + //clips: Sequence::new(), + //markers: Sequence::new(), + //audio: Sequence::new(), + //midi: Sequence::new(), + //osc: Sequence::new(), + //} + //} +//} + +//struct Sequence { + //events: Vec>, + //next: usize, +//} + +//impl Sequence { + //fn new () -> Self { + //Self { events: vec![], next: 0 } + //} +//} + +//struct Event { + //time: u64, + //data: T, +//} + +//struct Marker { + //name: String, +//} diff --git a/src/sequence/audio.rs b/src/sequence/audio.rs new file mode 100644 index 00000000..ec76ec67 --- /dev/null +++ b/src/sequence/audio.rs @@ -0,0 +1,4 @@ +pub struct Sample { + samples: Vec>, + cuepoints: Vec>>, +} diff --git a/src/sequence/midi.rs b/src/sequence/midi.rs new file mode 100644 index 00000000..5de39da2 --- /dev/null +++ b/src/sequence/midi.rs @@ -0,0 +1,114 @@ +use crate::sequence::{Frame, Time}; + +/// Pulses per quarter note +pub const PPQ: usize = 96; + +pub struct Message { + bytes: Vec +} + +pub struct MIDISequence { + name: String, + length: usize, + events: Vec<(Frame, MIDIEvent)>, + notes: Vec, +} + +impl MIDISequence { + pub fn new (name: &str, length: usize) -> Self { + Self { + name: name.to_string(), + length, + events: vec![], + notes: vec![], + } + } + pub fn add (&mut self, time: usize, event: MIDIEvent) -> &mut Self { + let mut sort = false; + match &event { + MIDIEvent::NoteOn(pitch, _velocity) => { + if !self.notes.contains(pitch) { + self.notes.push(*pitch); + sort = true; + } + } + } + if sort { + self.notes.sort(); + } + self.events.push((time, event)); + self + } + pub fn render (&self, stdout: &mut std::io::Stdout, resolution: usize) + -> Result<(), Box> + { + use crossterm::{*, style::Stylize}; + let (col, row) = cursor::position()?; + let unit = PPQ / resolution; + let length = self.length / unit; + let mut header = String::from(" "); + for i in 0..length { + if i % 8 == 0 { + header.push('┍'); + } else { + header.push('━'); + } + } + header.push('┑'); + let mut tracks: Vec<(String, String)> = vec![]; + for note in self.notes.iter().rev() { + let mut row_header = format!(" {note:3} "); + let mut row = String::new(); + for beat in 0..length { + let mut active = false; + for (frame, event) in self.events.iter() { + match event { + MIDIEvent::NoteOn(pitch, _) => { + if pitch == note + && *frame >= beat * unit + && *frame < (beat + 1) * unit + { + active = true; + continue + } + } + } + } + if active { + row.push('⯀') + } else if beat == 0 { + row.push('│'); + } else if beat % 8 == 0 { + row.push('┆'); + } else { + row.push('·'); + } + } + tracks.push((row_header, row)); + } + stdout.queue(style::PrintStyledContent(header.grey()))?; + for (row_header, row) in tracks.into_iter() { + stdout + .queue(cursor::MoveDown(1))? + .queue(cursor::MoveToColumn(col))? + .queue(style::PrintStyledContent(row_header.grey()))? + .queue(style::PrintStyledContent(row.clone().white()))? + .queue(style::PrintStyledContent(row.clone().yellow()))? + .queue(style::PrintStyledContent(row.white()))?; + } + //stdout + //.queue(cursor::MoveDown(1))? + //.queue(cursor::MoveToColumn(col))? + //.queue(style::PrintStyledContent(footer.grey()))?; + //.queue(style::PrintStyledContent("················".grey()))? + //.queue(style::PrintStyledContent("│".yellow()))? + //.queue(cursor::MoveDown(1))? + //.queue(cursor::MoveLeft(18))? + //.queue(style::PrintStyledContent("└────────────────┘".yellow()))?; + Ok(()) + } +} + +pub enum MIDIEvent { + NoteOn(u8, u8) +} diff --git a/src/sequence/osc.rs b/src/sequence/osc.rs new file mode 100644 index 00000000..32dbf39d --- /dev/null +++ b/src/sequence/osc.rs @@ -0,0 +1,4 @@ +pub struct Command { + name: String, + args: Vec, +} diff --git a/src/sequence/time.rs b/src/sequence/time.rs new file mode 100644 index 00000000..e69de29b diff --git a/src/transport.rs b/src/transport.rs new file mode 100644 index 00000000..ed5920f8 --- /dev/null +++ b/src/transport.rs @@ -0,0 +1,58 @@ +use std::error::Error; +use std::io::Write; + +pub struct Transport { + cols: u16, + rows: u16, +} + +impl Transport { + pub fn run_tui () -> Result<(), Box> { + let mut app = Self { cols: 0, rows: 0 }; + let sleep = std::time::Duration::from_millis(16); + let mut stdout = std::io::stdout(); + loop { + app.render(&mut stdout)?; + std::thread::sleep(sleep); + } + } + fn render (&mut self, stdout: &mut std::io::Stdout) -> Result<(), Box> { + use crossterm::{*, style::{*, Stylize}}; + let (cols, rows) = terminal::size()?; + if cols != self.cols || rows != self.rows { + self.cols = cols; + self.rows = rows; + stdout + .queue(terminal::Clear(terminal::ClearType::All))? + .queue(cursor::Hide)? + + .queue(cursor::MoveTo(1, 0))? + .queue(PrintStyledContent("[Home]".yellow().bold()))? + .queue(cursor::MoveTo(1, 1))? + .queue(PrintStyledContent("⏹ Stop and rewind".yellow().bold()))? + + .queue(cursor::MoveTo(20, 0))? + .queue(PrintStyledContent("[Enter]".yellow().bold()))? + .queue(cursor::MoveTo(20, 1))? + .queue(PrintStyledContent("⏮ Play from start".yellow().bold()))? + + .queue(cursor::MoveTo(40, 0))? + .queue(PrintStyledContent("[Space]".yellow().bold()))? + .queue(cursor::MoveTo(40, 1))? + .queue(PrintStyledContent("⯈ Play from cursor".yellow().bold()))? + + .queue(cursor::MoveTo(1, 3))?.queue(Print("Rate: "))? + .queue(cursor::MoveTo(7, 3))?.queue(PrintStyledContent("48000Hz".white().bold()))? + .queue(cursor::MoveTo(20, 3))?.queue(Print("BPM: "))? + .queue(cursor::MoveTo(25, 3))?.queue(PrintStyledContent("120.34".white().bold()))? + .queue(cursor::MoveTo(35, 3))?.queue(Print("Signature: "))? + .queue(cursor::MoveTo(46, 3))?.queue(PrintStyledContent("4 / 4".white().bold()))? + .queue(cursor::MoveTo(1, 4))?.queue(Print("Time: "))? + .queue(cursor::MoveTo(7, 4))?.queue(PrintStyledContent("1m 23.456s".white().bold()))? + .queue(cursor::MoveTo(20, 4))?.queue(Print("Beat: "))? + .queue(cursor::MoveTo(26, 4))?.queue(PrintStyledContent("30x 3/4".white().bold()))? + .flush()?; + } + Ok(()) + } +}