Skip to content

Commit

Permalink
type channels with an enum rather than a dyn trait
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpasmantier committed Oct 20, 2024
1 parent db3aa1a commit 10f3025
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 46 deletions.
4 changes: 2 additions & 2 deletions crates/television/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use color_eyre::Result;
use tokio::sync::{mpsc, Mutex};
use tracing::{debug, info};

use crate::channels::CliTvChannel;
use crate::channels::{AvailableChannel, CliTvChannel};
use crate::television::Television;
use crate::{
action::Action,
Expand Down Expand Up @@ -84,7 +84,7 @@ pub struct App {

impl App {
pub fn new(
channel: CliTvChannel,
channel: AvailableChannel,
tick_rate: f64,
frame_rate: f64,
) -> Result<Self> {
Expand Down
5 changes: 3 additions & 2 deletions crates/television/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub mod channels;
mod env;
mod files;
mod git_repos;
mod stdin;
pub mod stdin;
mod text;

/// The interface that all television channels must implement.
Expand Down Expand Up @@ -97,14 +97,15 @@ pub enum AvailableChannel {
Text(text::Channel),
Stdin(stdin::Channel),
Alias(alias::Channel),
Channel(channels::SelectionChannel),
}

/// NOTE: this could be generated by a derive macro
impl TryFrom<&Entry> for AvailableChannel {
type Error = String;

fn try_from(entry: &Entry) -> Result<Self, Self::Error> {
match entry.name.as_ref() {
match entry.name.to_ascii_lowercase().as_ref() {
"env" => Ok(AvailableChannel::Env(env::Channel::default())),
"files" => Ok(AvailableChannel::Files(files::Channel::default())),
"gitrepos" => {
Expand Down
13 changes: 7 additions & 6 deletions crates/television/channels/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use nucleo::{
};

use crate::{
channels::{CliTvChannel, TelevisionChannel},
channels::{AvailableChannel, CliTvChannel, TelevisionChannel},
entry::Entry,
fuzzy::MATCHER,
previewers::PreviewType,
Expand All @@ -24,8 +24,6 @@ pub struct SelectionChannel {

const NUM_THREADS: usize = 1;

const CHANNEL_BLACKLIST: [CliTvChannel; 1] = [CliTvChannel::Stdin];

impl SelectionChannel {
pub fn new() -> Self {
let matcher = Nucleo::new(
Expand All @@ -36,9 +34,6 @@ impl SelectionChannel {
);
let injector = matcher.injector();
for variant in CliTvChannel::value_variants() {
if CHANNEL_BLACKLIST.contains(variant) {
continue;
}
let _ = injector.push(*variant, |e, cols| {
cols[0] = (*e).to_string().into();
});
Expand All @@ -55,6 +50,12 @@ impl SelectionChannel {
const MATCHER_TICK_TIMEOUT: u64 = 2;
}

impl Default for SelectionChannel {
fn default() -> Self {
Self::new()
}
}

const TV_ICON: FileIcon = FileIcon {
icon: '📺',
color: "#ffffff",
Expand Down
7 changes: 4 additions & 3 deletions crates/television/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::io::{stdout, IsTerminal, Write};

use channels::AvailableChannel;
use clap::Parser;
use color_eyre::Result;
use tracing::{debug, info};

use crate::app::App;
use crate::channels::CliTvChannel;
use crate::channels::stdin::Channel as StdinChannel;
use crate::cli::Cli;

mod action;
Expand Down Expand Up @@ -36,10 +37,10 @@ async fn main() -> Result<()> {
{
if is_readable_stdin() {
debug!("Using stdin channel");
CliTvChannel::Stdin
AvailableChannel::Stdin(StdinChannel::default())
} else {
debug!("Using {:?} channel", args.channel);
args.channel
args.channel.to_channel()
}
},
args.tick_rate,
Expand Down
22 changes: 12 additions & 10 deletions crates/television/television.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,16 @@ pub struct Television {

impl Television {
#[must_use]
pub fn new(cli_channel: CliTvChannel) -> Self {
let mut tv_channel = cli_channel.to_channel();
tv_channel.find(EMPTY_STRING);
pub fn new(mut channel: AvailableChannel) -> Self {
channel.find(EMPTY_STRING);

let spinner = Spinner::default();
let spinner_state = SpinnerState::from(&spinner);

Self {
action_tx: None,
config: Config::default(),
channel: tv_channel,
channel,
current_pattern: EMPTY_STRING.to_string(),
mode: Mode::Channel,
input: Input::new(EMPTY_STRING.to_string()),
Expand All @@ -99,7 +98,7 @@ impl Television {
}
}

pub fn change_channel(&mut self, channel: Box<dyn TelevisionChannel>) {
pub fn change_channel(&mut self, channel: AvailableChannel) {
self.reset_preview_scroll();
self.reset_results_selection();
self.current_pattern = EMPTY_STRING.to_string();
Expand Down Expand Up @@ -296,7 +295,8 @@ impl Television {
Action::ScrollPreviewHalfPageUp => self.scroll_preview_up(20),
Action::ToChannelSelection => {
self.mode = Mode::ChannelSelection;
let selection_channel = Box::new(SelectionChannel::new());
let selection_channel =
AvailableChannel::Channel(SelectionChannel::new());
self.change_channel(selection_channel);
}
Action::SelectEntry => {
Expand All @@ -308,10 +308,12 @@ impl Television {
.unwrap()
.send(Action::SelectAndExit)?,
Mode::ChannelSelection => {
self.mode = Mode::Channel;
let new_channel =
AvailableChannel::from_entry(&entry)?;
self.change_channel(new_channel);
if let Ok(new_channel) =
AvailableChannel::try_from(&entry)
{
self.mode = Mode::Channel;
self.change_channel(new_channel);
}
}
}
}
Expand Down
56 changes: 33 additions & 23 deletions crates/television_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ pub fn cli_channel_derive(input: TokenStream) -> TokenStream {
impl_cli_channel(&ast)
}

const VARIANT_BLACKLIST: [&str; 2] = ["Stdin", "Channel"];

fn impl_cli_channel(ast: &syn::DeriveInput) -> TokenStream {
// check that the struct is an enum
let variants = if let syn::Data::Enum(data_enum) = &ast.data {
Expand All @@ -26,12 +28,15 @@ fn impl_cli_channel(ast: &syn::DeriveInput) -> TokenStream {
);

// create the CliTvChannel enum
let cli_enum_variants = variants.iter().map(|variant| {
let variant_name = &variant.ident;
quote! {
#variant_name
}
});
let cli_enum_variants = variants
.iter()
.filter(|v| !VARIANT_BLACKLIST.contains(&v.ident.to_string().as_str()))
.map(|variant| {
let variant_name = &variant.ident;
quote! {
#variant_name
}
});
let cli_enum = quote! {
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
Expand All @@ -46,7 +51,9 @@ fn impl_cli_channel(ast: &syn::DeriveInput) -> TokenStream {
};

// Generate the match arms for the `to_channel` method
let arms = variants.iter().map(|variant| {
let arms = variants.iter().filter(
|variant| !VARIANT_BLACKLIST.contains(&variant.ident.to_string().as_str()),
).map(|variant| {
let variant_name = &variant.ident;

// Get the inner type of the variant, assuming it is the first field of the variant
Expand Down Expand Up @@ -94,28 +101,31 @@ pub fn tv_channel_derive(input: TokenStream) -> TokenStream {
}

fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
// check that the struct is an enum
// Ensure the struct is an enum
let variants = if let syn::Data::Enum(data_enum) = &ast.data {
&data_enum.variants
} else {
panic!("#[derive(TvChannel)] is only defined for enums");
};

// check that the enum has at least one variant
// Ensure the enum has at least one variant
assert!(
!variants.is_empty(),
"#[derive(TvChannel)] requires at least one variant"
);

let enum_name = &ast.ident;

let variant_names: Vec<_> = variants.iter().map(|v| &v.ident).collect();

// Generate the trait implementation for the TelevisionChannel trait
// FIXME: fix this
let trait_impl = quote! {
impl TelevisionChannel for AvailableChannel {
impl TelevisionChannel for #enum_name {
fn find(&mut self, pattern: &str) {
match self {
#(
AvailableChannel::#variants(_) => {
self.find(pattern);
#enum_name::#variant_names(ref mut channel) => {
channel.find(pattern);
}
)*
}
Expand All @@ -124,8 +134,8 @@ fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
fn results(&mut self, num_entries: u32, offset: u32) -> Vec<Entry> {
match self {
#(
AvailableChannel::#variants(_) => {
self.results(num_entries, offset)
#enum_name::#variant_names(ref mut channel) => {
channel.results(num_entries, offset)
}
)*
}
Expand All @@ -134,8 +144,8 @@ fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
fn get_result(&self, index: u32) -> Option<Entry> {
match self {
#(
AvailableChannel::#variants(_) => {
self.get_result(index)
#enum_name::#variant_names(ref channel) => {
channel.get_result(index)
}
)*
}
Expand All @@ -144,8 +154,8 @@ fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
fn result_count(&self) -> u32 {
match self {
#(
AvailableChannel::#variants(_) => {
self.result_count()
#enum_name::#variant_names(ref channel) => {
channel.result_count()
}
)*
}
Expand All @@ -154,8 +164,8 @@ fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
fn total_count(&self) -> u32 {
match self {
#(
AvailableChannel::#variants(_) => {
self.total_count()
#enum_name::#variant_names(ref channel) => {
channel.total_count()
}
)*
}
Expand All @@ -164,8 +174,8 @@ fn impl_tv_channel(ast: &syn::DeriveInput) -> TokenStream {
fn running(&self) -> bool {
match self {
#(
AvailableChannel::#variants(_) => {
self.running()
#enum_name::#variant_names(ref channel) => {
channel.running()
}
)*
}
Expand Down

0 comments on commit 10f3025

Please sign in to comment.