Skip to content
adlioPublic

About

Build instantly responsive Alfred workflows with Rust.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

alfrusco

Crates.io Documentation CI codecov License: MIT

A Rust library for building Alfred workflows. It handles Alfred's JSON protocol, provides builder patterns for creating items, and includes support for background jobs, clipboard operations, and logging.

Features

  • Builder patterns for creating Alfred items
  • Async/await support
  • Background jobs that don't block Alfred's UI
  • Rich text and Markdown clipboard operations
  • Fuzzy search and sorting
  • Access to workflow directories and configuration
  • Structured logging
  • URL items with clipboard modifiers
  • Typed output for the Script Filter, Grid View, Text View and Run Script / JSON Utility
  • Alfred 6 Script Filter keys (strictmods, iconresize, icon resize)
  • Typed builders for Alfred 6 Alfred UI ui.json files (alfrusco::ui)
  • Testing utilities

Installation

Add alfrusco to your Cargo.toml:

[dependencies]
alfrusco = "0.5"

# For async workflows
tokio = { version = "1", features = ["full"] }

# For command-line argument parsing (recommended)
clap = { version = "4", features = ["derive", "env"] }

Quick Start

Basic Synchronous Workflow

use alfrusco::{execute, Item, Runnable, Workflow};
use alfrusco::config::AlfredEnvProvider;
use clap::Parser;

#[derive(Parser)]
struct MyWorkflow {
    query: Vec<String>,
}

impl Runnable for MyWorkflow {
    type Error = alfrusco::Error;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        let query = self.query.join(" ");

        workflow.append_item(
            Item::new(format!("Hello, {}!", query))
                .subtitle("This is a basic Alfred workflow")
                .arg(&query)
                .valid(true)
        );

        Ok(())
    }
}

fn main() {
    let _ = alfrusco::init_logging(&AlfredEnvProvider);
    let command = MyWorkflow::parse();
    execute(&AlfredEnvProvider, command, &mut std::io::stdout());
}

Async Workflow with HTTP Requests

use alfrusco::{execute_async, AsyncRunnable, Item, Workflow, WorkflowError};
use alfrusco::config::AlfredEnvProvider;
use clap::Parser;
use serde::Deserialize;

#[derive(Parser)]
struct ApiWorkflow {
    query: Vec<String>,
}

#[derive(Deserialize)]
struct ApiResponse {
    results: Vec<ApiResult>,
}

#[derive(Deserialize)]
struct ApiResult {
    title: String,
    description: String,
    url: String,
}

#[async_trait::async_trait]
impl AsyncRunnable for ApiWorkflow {
    type Error = Box<dyn WorkflowError>;

    async fn run_async(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        let query = self.query.join(" ");
        workflow.set_filter_keyword(query.clone());

        let url = format!("https://api.example.com/search?q={}", query);
        let response: ApiResponse = reqwest::get(&url)
            .await?
            .json()
            .await?;

        let items: Vec<Item> = response.results
            .into_iter()
            .map(|result| {
                Item::new(&result.title)
                    .subtitle(&result.description)
                    .arg(&result.url)
                    .quicklook_url(&result.url)
                    .valid(true)
            })
            .collect();

        workflow.append_items(items);
        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let _ = alfrusco::init_logging(&AlfredEnvProvider);
    let command = ApiWorkflow::parse();
    execute_async(&AlfredEnvProvider, command, &mut std::io::stdout()).await;
}

Core Concepts

Items

Items represent choices in the Alfred selection UI:

use alfrusco::Item;

let item = Item::new("My Title")
    .subtitle("Additional information")
    .arg("argument-passed-to-action")
    .uid("unique-identifier")
    .valid(true)
    .icon_from_image("/path/to/icon.png")
    .copy_text("Text copied with Cmd+C")
    .large_type_text("Text shown in large type with Cmd+L")
    .quicklook_url("https://example.com")
    .var("CUSTOM_VAR", "value")
    .autocomplete("text for tab completion");

Workflow Configuration

Alfrusco handles Alfred's environment variables through configuration providers:

use alfrusco::config::{AlfredEnvProvider, TestingProvider};

// For production (reads from Alfred environment variables)
let provider = AlfredEnvProvider;

// For testing (uses temporary directories)
let temp_dir = tempfile::tempdir().unwrap();
let provider = TestingProvider(temp_dir.path().to_path_buf());

Error Handling

Custom error types integrate with Alfred:

use alfrusco::{WorkflowError, Item};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum MyWorkflowError {
    #[error("Network request failed: {0}")]
    Network(#[from] reqwest::Error),
    #[error("Invalid input: {0}")]
    InvalidInput(String),
}

impl WorkflowError for MyWorkflowError {}

// Errors become Alfred items automatically
impl Runnable for MyWorkflow {
    type Error = MyWorkflowError;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        Err(MyWorkflowError::InvalidInput("Missing required field".to_string()))
    }
}

Advanced Features

Background Jobs

Run tasks without blocking Alfred's UI:

use std::process::Command;
use std::time::Duration;

impl Runnable for MyWorkflow {
    type Error = alfrusco::Error;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        let cache_file = workflow.cache_dir().join("releases.json");

        let mut cmd = Command::new("sh");
        cmd.arg("-c")
            .arg(format!(
                "curl -s https://api.github.com/repos/rust-lang/rust/releases/latest > {}",
                cache_file.display()
            ));

        // Run in background, refresh every 30 seconds
        workflow.run_in_background(
            "github-releases",
            Duration::from_secs(30),
            cmd
        );
        // While the job is stale/running, a status row with live progress is
        // pinned to the bottom of the results (stable uid, exempt from
        // filtering) and a 1-second rerun is scheduled so results refresh
        // when the job completes. The row never displaces or reshuffles the
        // selectable items above it.

        if cache_file.exists() {
            if let Ok(data) = std::fs::read_to_string(&cache_file) {
                if let Ok(release) = serde_json::from_str::<serde_json::Value>(&data) {
                    if let Some(tag) = release["tag_name"].as_str() {
                        workflow.append_item(
                            Item::new(format!("Latest Rust: {}", tag))
                                .subtitle("Click to view release notes")
                                .arg(release["html_url"].as_str().unwrap_or(""))
                                .valid(true)
                        );
                    }
                }
            }
        }

        Ok(())
    }
}

Background jobs track their status and show messages like "Last succeeded 2 minutes ago, running for 3s". Failed jobs are retried automatically.

URL Items

URL items include modifiers for copying links in different formats:

use alfrusco::URLItem;

let url_item = URLItem::new("Rust Documentation", "https://doc.rust-lang.org/")
    .subtitle("The Rust Programming Language Documentation")
    .short_title("Rust Docs")
    .long_title("The Rust Programming Language Official Documentation")
    .icon_for_filetype("public.html")
    .copy_text("doc.rust-lang.org");

let item: Item = url_item.into();

Modifier keys:

  • Cmd: Copy as Markdown link
  • Alt: Copy as rich text link
  • Cmd+Shift: Copy as Markdown with short title
  • Alt+Shift: Copy as rich text with short title
  • Cmd+Ctrl: Copy as Markdown with long title
  • Alt+Ctrl: Copy as rich text with long title

File Results and Universal Actions

Mark an item's arg as a file path so Universal Actions, the File Buffer and Quick Look work on it, and choose exactly what Universal Actions receive:

use alfrusco::{Icon, Item, ItemType, UniversalAction};

let item = Item::new("Desktop")
    .arg("~/Desktop")
    .item_type(ItemType::File) // or ItemType::FileSkipCheck
    .icon(Icon::for_file("~/Desktop"))
    .universal_action(
        UniversalAction::new()
            .file("~/Desktop")
            .url("https://www.alfredapp.com")
            .text(["one", "two"]),
    );

// Or let Alfred infer each value's type:
let item = Item::new("Alfred").action(["https://www.alfredapp.com", "Alfred"]);

Session Variables

Session variables pass to the rest of the workflow stream and come back into the script when it reruns in the same session, which makes them a way to keep state between reruns. An item variable of the same name overrides it when that item is actioned.

workflow.var("page", "2");

Alfred 6 Keys

Alfred 6 added strictmods, iconresize and a per-icon resize to the Script Filter JSON. Use workflow.config.alfred_major_version() to check which version is running before relying on these features.

use alfrusco::{Icon, IconResize, Item};

// Undefined modifier combinations act as `valid: false` instead of running
// the default action.
workflow.strict_mods(true);

// How every result's icon fills its space (fit, fill, stretch or centre)...
workflow.icon_resize(IconResize::Fit);

// ...and a per-icon override.
let item = Item::new("Photo").icon(Icon::from_image("./photo.png").resize(IconResize::Fill));

Grid View

The Grid View reads the same JSON as a Script Filter. Use preselect to open it with an item highlighted:

workflow.preselect("desktopfolder"); // the item's uid

Text View

Write TextView from a script that populates Alfred's Text View:

use std::time::Duration;
use alfrusco::{ScrollMode, TextView, TextViewMode};

let mut view = TextView::new("**Status:** syncing…");
view.footer("Last sync 2 minutes ago")
    .mode(TextViewMode::Append)
    .scroll(ScrollMode::End)
    .rerun(Duration::from_secs(1))
    .var("cursor", "42");
view.write(std::io::stdout())?;

Run Script Output

A Run Script action can write alfredworkflow JSON to set the next object's argument, override its configuration and set variables (the same format as the JSON Utility). Alfred clears the argument when arg is left out, so set it whenever the next object needs one:

use alfrusco::JsonConfig;

let mut output = JsonConfig::new();
output
    .arg("https://www.alfredapp.com")
    .config("browser", "com.apple.Safari")
    .var("fruit", "banana");
output.write(std::io::stdout())?;

Alfred UI (ui.json)

Alfred 6 can show native windows described by a ui.json file inside a .alfredui folder, opened by the Alfred UI workflow object. The alfrusco::ui module builds that file from typed Rust: windows, layouts, every component, events, actions, JSON action commands, colours and placeholders.

use alfrusco::ui::*;

let search = TextField::new()
    .id("query")
    .placeholder("Search fruit")
    .focus(true)
    .region(Region::Top)
    .on(Trigger::Changed, Action::function("fruit", function::FILTER_DATA))
    .on(
        Trigger::Actioned,
        JsonAction::new().finish(Finish::new().args(Placeholder::value("fruit", "selected.name.text"))),
    );

let fruit = DataView::new(
    Cell::new(Label::empty().id("name"))
        .height(28)
        .selected("name", "colour", Colour::alfred_selected_result_text()),
    Data::rows(["Apple", "Banana", "Cherry"].map(|name| Row::new().value("name", "text", name)))
        .filter(Filter::new("name.text", Placeholder::value("query", "text"))),
)
.id("fruit")
.region(Region::Centre);

let ui = Ui::new(Window::new(View::border().spacing(8).child(search).child(fruit)).padding(8));
std::fs::create_dir_all("fruit.alfredui")?;
ui.write_pretty(std::fs::File::create("fruit.alfredui/ui.json")?)?;

Alfred UI still renames properties between builds, so every struct has a set(key, value) escape hatch that writes any key as is (replacing the typed property of the same name), and Component::raw(json) accepts a component this crate doesn't model yet.

Alfred UI script backends

A UI's script actions and pulse run a program from the .alfredui folder and apply the JSON actions it prints. Implement UiRunnable and call execute_ui from main:

use alfrusco::ui::{execute_ui, UiContext, UiResponse, UiRunnable};

struct Backend;

impl UiRunnable for Backend {
    type Error = alfrusco::Error;

    fn run(self, ctx: &UiContext, response: &mut UiResponse) -> Result<(), Self::Error> {
        if ctx.arg(0) == Some("rename") {
            let title = ctx.resolved_arg(1).unwrap_or("Untitled");
            response.update("title", "text", title).update("status", "text", "Saved");
        }
        Ok(())
    }
}

fn main() {
    execute_ui(&UiContext::from_env(), Backend, &mut std::io::stdout());
}

UiContext reads what Alfred 6 passes: the action's args as arguments, variablesconfig entries as environment variables, and alfred_ui_source (the component whose event fired; absent for the pulse). execute_ui always writes exactly one JSON object and never exits non-zero (except that a panic can't be caught in a binary built with panic = "abort"), because Alfred drops empty output, plain text and the output of a failed script without telling the user. An error or panic becomes a notification instead. Whether Alfred UI delivers notifications hasn't been confirmed yet, so override UiRunnable::error_response to show errors in the window as well.

For tests:

  • UiContext::new().with_arg(..).with_var(..).run(backend) runs a backend in-process and returns its UiResponse.
  • UiPackage::open("tasks.alfredui")?.problems() reports missing files and scripts, scripts without the exec bit, ids that actions and {value:} placeholders target but no component has, missing template parameters, and unknown keys and types, all of which Alfred ignores silently. An unknown JSON action command is an error when it's within two edits of a real one (updat) and a warning otherwise, so a command added with set still passes.
  • package.run_script("scripts/backend", &ctx) runs a script the way Alfred does (cwd = the .alfredui folder, stdin at EOF, only the given variables) and checks its output.
  • The simulator knows the Alfred UI object: results that open it route to ActionResult::OpenedUi, and Simulator::route_finish (for JSON actions) or route_response (for a UiResponse) follows a finish to the next object. Alfred passes finish output on only when the UI opens inside Alfred (launch mode 0); the audit warns about connections from an externally launched UI.

The alfrusco::ui docs list exactly what Alfred 6.0.3 was observed to pass and expect, and what is still unknown.

Filtering and Sorting

Enable fuzzy search:

impl Runnable for SearchWorkflow {
    type Error = alfrusco::Error;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        let query = self.query.join(" ");
        workflow.set_filter_keyword(query);

        workflow.append_items(vec![
            Item::new("Apple").subtitle("Fruit"),
            Item::new("Banana").subtitle("Yellow fruit"),
            Item::new("Carrot").subtitle("Orange vegetable"),
        ]);

        Ok(())
    }
}

Boosting Item Priority

Use boost to influence ranking:

use alfrusco::{Item, BOOST_HIGH, BOOST_MODERATE};

workflow.append_items(vec![
    Item::new("Preferred Result")
        .subtitle("This ranks higher")
        .boost(BOOST_HIGH),
    Item::new("Normal Result")
        .subtitle("Standard ranking"),
    Item::new("Slightly Preferred")
        .subtitle("Moderate boost")
        .boost(BOOST_MODERATE),
]);

Boost constants:

  • BOOST_SLIGHT (25)
  • BOOST_LOW (50)
  • BOOST_MODERATE (75)
  • BOOST_HIGH (100)
  • BOOST_HIGHER (150)
  • BOOST_HIGHEST (200)

Boost only affects non-sticky items. Use .sticky(true) for items that should always appear first.

Pinning Items

Two flags exempt an item from fuzzy filtering and give it a fixed position:

  • .sticky(true) — pinned to the top, before all filtered results. Use for headers and "Back" navigation rows.
  • .pin_to_bottom(true) — pinned to the bottom, after all filtered results. Use for status/footer rows (e.g. background job progress) that should stay visible without reshuffling or displacing the selectable results above them.
workflow.append_items(vec![
    Item::new("‹ Back").sticky(true),
    Item::new("Result A"),
    Item::new("Result B"),
    Item::new("Syncing…")
        .subtitle("Background refresh in progress")
        .valid(false)
        .pin_to_bottom(true),
]);

Pinned items keep the order they were added within their zone. If both flags are set, sticky wins. Give pinned rows a stable uid so Alfred preserves the user's selection across rerun cycles.

Workflow Directories

impl Runnable for MyWorkflow {
    type Error = alfrusco::Error;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        let data_dir = workflow.data_dir();
        let config_file = data_dir.join("config.json");

        let cache_dir = workflow.cache_dir();
        let temp_file = cache_dir.join("temp_data.json");

        std::fs::write(config_file, "{\"setting\": \"value\"}")?;

        Ok(())
    }
}

Response Caching and Rerun

use std::time::Duration;

impl Runnable for MyWorkflow {
    type Error = alfrusco::Error;

    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error> {
        workflow.cache(Duration::from_secs(300), true);
        workflow.rerun(Duration::from_secs(30));
        workflow.skip_knowledge(true);

        workflow.append_item(Item::new("Cached result"));
        Ok(())
    }
}

Testing

#[cfg(test)]
mod tests {
    use super::*;
    use alfrusco::config::TestingProvider;
    use tempfile::tempdir;

    #[test]
    fn test_my_workflow() {
        let workflow = MyWorkflow {
            query: vec!["test".to_string()],
        };

        let temp_dir = tempdir().unwrap();
        let provider = TestingProvider(temp_dir.path().to_path_buf());

        let mut buffer = Vec::new();
        alfrusco::execute(&provider, workflow, &mut buffer);

        let output = String::from_utf8(buffer).unwrap();
        assert!(output.contains("Hello, test!"));
    }

    #[tokio::test]
    async fn test_async_workflow() {
        let workflow = AsyncWorkflow {
            query: vec!["async".to_string()],
        };

        let temp_dir = tempdir().unwrap();
        let provider = TestingProvider(temp_dir.path().to_path_buf());

        let mut buffer = Vec::new();
        alfrusco::execute_async(&provider, workflow, &mut buffer).await;

        let output = String::from_utf8(buffer).unwrap();
        assert!(output.contains("async"));
    }
}

Testing Workflow Navigation (Simulator)

For testing that actioning items produces correct navigation outcomes (drill-in, URL open, dead-ends), use the simulator module. It parses your real info.plist and walks the graph without needing the Alfred UI:

use alfrusco::simulator::{ActionResult, Simulator};
use alfrusco::{Item, Runnable, Workflow};

struct MyMenuWorkflow { category: Option<String> }

impl Runnable for MyMenuWorkflow {
    type Error = alfrusco::Error;
    fn run(self, wf: &mut Workflow) -> Result<(), Self::Error> {
        match self.category.as_deref() {
            Some("fruits") => {
                wf.append_item(Item::new("Apple").arg("https://example.com/apple").valid(true));
            }
            _ => {
                wf.append_item(Item::new("Fruits").arg("fruits").var("category", "fruits").valid(true));
            }
        }
        Ok(())
    }
}

#[test]
fn test_navigation_drill_in() {
    // Point at your workflow directory (with info.plist)
    let sim = Simulator::for_workflow_dir("workflow")
        .unwrap()
        .source_filter("SF-MAIN-001");

    // Run in-process — no compiled binary or deployment needed
    let screen = sim.run_in_process(MyMenuWorkflow { category: None }).unwrap();
    screen.assert_renders();

    // Verify the action routes to a sub-filter (drill-in)
    let action = screen.action_first().unwrap();
    action.assert_drills_in();
}

#[test]
fn test_navigation_opens_url() {
    let sim = Simulator::for_workflow_dir("workflow")
        .unwrap()
        .source_filter("SF-SUB-001");

    let screen = sim.run_in_process(MyMenuWorkflow { category: Some("fruits".into()) }).unwrap();
    let action = screen.action_first().unwrap();
    action.assert_opens_url();
}

The alfrusco-simulator CLI can also be used for ad-hoc auditing:

# Audit a workflow graph for navigation defects
alfrusco-simulator audit ./workflow

# Walk a workflow and show items with routing
alfrusco-simulator walk ./workflow --binary target/debug/myworkflow
alfrusco-simulator walk ./workflow --binary target/debug/myworkflow --source-filter SF-SUB-001 fruits

How the Audit Models Routing

The dynamic audit (audit --binary) faithfully models Alfred's routing semantics. When a user actions an item, Alfred routes through the workflow graph using conditionals and connections. The audit classifies each outcome and only flags genuine dead-ends — never legitimate terminal actions.

Conditional routing (matchmode evaluation)

At each Conditional node, the item's arg is evaluated against conditions in order:

Matchmode Name Semantics
0 Is Exact equality (empty pattern → "is empty")
1 IsNot Not equal (empty pattern → "is not empty")
2 Contains Substring match
3 DoesNotContain No substring match
4 StartsWith Prefix match
5 EndsWith Suffix match
6 MatchesRegex Regular expression match

The first matching condition's output port determines which connection to follow. If no condition matches, the else branch is taken.

External Trigger re-entry (drill-in via triggers)

A CallExternalTrigger output resolves to its matching ExternalTrigger input (by trigger ID) and continues traversal from there. The chain:

item → Conditional → CallExternalTrigger → ExternalTrigger → Script Filter

classifies as DrilledIn — a legitimate drill-in navigation, not a dead-end.

Terminal classification

Outcome Meaning Audit result
DrilledIn Reached another Script Filter ✅ OK
TypedAutocomplete valid:false + autocomplete ✅ OK
RanScript Reached a Run Script (act-and-exit) ✅ OK
OpenedUrl Reached Open URL (act-and-exit) ✅ OK
DeadEnd Dangling/unconnected branch output ❌ ERROR

Only DeadEnd is an error. This occurs when the matched conditional branch connects to a non-existent object or has no connection at all — actioning the item silently does nothing. Items that route to Run Script or Open URL are intentional act-and-exit patterns (e.g. copy to clipboard, open a URL, run a mutation) and are never flagged.

Examples

The examples/ directory contains runnable examples. They require Alfred environment variables:

# Using the run script
./run-example.sh static_output
./run-example.sh success --message "Custom message"
./run-example.sh random_user search_term
./run-example.sh url_items
./run-example.sh sleep --duration-in-seconds 10
./run-example.sh error --file-path nonexistent.txt

# Using Make
make examples-help
make example-static_output

# Manual setup
export alfred_workflow_bundleid="com.example.test"
export alfred_workflow_cache="/tmp/cache"
export alfred_workflow_data="/tmp/data"
export alfred_version="5.0"
export alfred_version_build="2058"
export alfred_workflow_name="Test Workflow"
cargo run --example static_output

API Reference

Item

  • new(title) - Create item
  • subtitle(text) - Set subtitle
  • arg(value) / args(values) - Set arguments
  • valid(bool) - Set actionable
  • uid(id) - Set unique identifier
  • icon(icon) / icon_from_image(path) / icon_for_file(path) / icon_for_filetype(type) - Set icons
  • item_type(ItemType) - Treat arg as a file path (File, FileSkipCheck)
  • action(values) / universal_action(UniversalAction) - Set Universal Action content
  • copy_text(text) / large_type_text(text) - Set text operations
  • quicklook_url(url) - Enable Quick Look
  • var(key, value) - Set workflow variables
  • autocomplete(text) - Set tab completion
  • modifier(modifier) - Add modifier actions
  • sticky(bool) - Pin to top
  • pin_to_bottom(bool) - Pin to bottom (filter-exempt status/footer rows)
  • boost(value) - Adjust ranking

URLItem

  • new(title, url) - Create URL item
  • subtitle(text) - Override subtitle
  • short_title(text) / long_title(text) - Alternative titles for modifiers
  • display_title(text) - Override display title
  • copy_text(text) - Set copy text
  • icon_from_image(path) / icon_for_filetype(type) - Set icons

Workflow

  • append_item(item) / append_items(items) - Add items
  • prepend_item(item) / prepend_items(items) - Add items to beginning
  • set_filter_keyword(query) - Enable filtering
  • var(key, value) - Set a session variable
  • preselect(uid) - Grid View: highlight an item on open
  • strict_mods(bool) / icon_resize(IconResize) - Alfred 6 keys
  • data_dir() / cache_dir() - Get directories
  • run_in_background(name, max_age, command) - Run background job

Response

  • cache(duration, loose_reload) - Set caching
  • rerun(interval) - Set refresh interval
  • skip_knowledge(bool) - Control knowledge integration
  • var(key, value) / unset_var(key) - Session variables
  • preselect(uid) - Grid View preselection
  • strict_mods(bool) - Alfred 6: undefined modifiers act as valid: false
  • icon_resize(IconResize) - Alfred 6: icon resizing for every result

Icon

  • from_image(path) / for_file(path) / for_filetype(uti) - Constructors
  • resize(IconResize) - Alfred 6: per-icon resizing (Fit, Fill, Stretch, Centre)

TextView

  • new(response) / response(text) / footer(text) - Content
  • mode(TextViewMode) / scroll(ScrollMode) / input_field(InputFieldMode) - Rerun behaviour
  • action_output(bool) / rerun(interval) / var(key, value) / write(writer)

JsonConfig

  • arg(value) / config(key, value) / var(key, value) / write(writer) - Run Script / JSON Utility output

ui

  • Ui::new(Window) with bundle_id, variable, variable_config, template, colour, pulse, log, debug, write / write_pretty
  • View (stack, border, grid, inline, form, flex) and the components Label, Button, Checkbox, Picker, TextField, PasswordField, TextArea, MarkdownArea, Progress, ImageView, DataView, WebKitView, Template, FileComponent
  • Event, Trigger, Action (log, script, json, function) and the JsonAction commands (update, insert, remove, replace, sheet, finish and the rest)
  • Colour, Font, Image, Constraints, Placeholder
  • Backend: UiRunnable / AsyncUiRunnable, UiContext, UiResponse, execute_ui / execute_ui_async
  • Checks: UiPackage (problems, check_response, run_script), check_actions

Traits

trait Runnable {
    type Error: WorkflowError;
    fn run(self, workflow: &mut Workflow) -> Result<(), Self::Error>;
}

#[async_trait]
trait AsyncRunnable {
    type Error: WorkflowError;
    async fn run_async(self, workflow: &mut Workflow) -> Result<(), Self::Error>;
}

trait WorkflowError: std::error::Error {
    fn error_item(&self) -> Item { /* default implementation */ }
}

Configuration

  • AlfredEnvProvider - Reads from Alfred environment variables
  • TestingProvider - Uses temporary directories

Execution

  • execute(provider, runnable, writer) - Run synchronous workflow
  • execute_async(provider, runnable, writer) - Run async workflow
  • init_logging(provider) - Initialize logging

Development

git clone https://github.com/adlio/alfrusco.git
cd alfrusco
cargo build
cargo test
cargo nextest run  # recommended
cargo tarpaulin --out html  # coverage

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make changes and add tests
  4. Run cargo nextest run, cargo clippy, cargo fmt
  5. Submit a pull request

License

MIT License - see LICENSE.

Support

About

Build instantly responsive Alfred workflows with Rust.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages