1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
//! Proc macros for use in the main Penrose crate
use penrose_keysyms::XKeySym;
use proc_macro::TokenStream;
use strum::IntoEnumIterator;
use syn::{
    parenthesized,
    parse::{Parse, ParseStream, Result},
    parse_macro_input,
    punctuated::Punctuated,
    LitStr, Token,
};

use std::collections::HashSet;

const VALID_MODIFIERS: [&str; 4] = ["A", "M", "S", "C"];

struct Binding {
    raw: String,
    mods: Vec<String>,
    keyname: Option<String>,
}

struct BindingsInput(Vec<Binding>);

impl Parse for BindingsInput {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut bindings = as_bindings(comma_sep_strs(input)?);

        let templated_content;
        parenthesized!(templated_content in input);

        while !templated_content.is_empty() {
            let content;
            parenthesized!(content in templated_content);
            bindings.extend(expand_templates(
                comma_sep_strs(&content)?,
                comma_sep_strs(&content)?,
            ));
        }

        Ok(Self(bindings))
    }
}

fn comma_sep_strs(input: ParseStream) -> Result<Vec<String>> {
    let content;
    parenthesized!(content in input);
    Ok(Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?
        .iter()
        .map(LitStr::value)
        .collect())
}

fn as_bindings(raw: Vec<String>) -> Vec<Binding> {
    raw.iter()
        .map(|s| {
            let mut parts: Vec<&str> = s.split('-').collect();
            let (keyname, mods) = if parts.len() <= 1 {
                (None, vec![s.clone()])
            } else {
                (
                    parts.pop().map(String::from),
                    parts.into_iter().map(String::from).collect(),
                )
            };

            Binding {
                raw: s.clone(),
                keyname,
                mods,
            }
        })
        .collect()
}

fn expand_templates(templates: Vec<String>, keynames: Vec<String>) -> Vec<Binding> {
    templates
        .iter()
        .flat_map(|t| {
            let mut parts: Vec<&str> = t.split('-').collect();
            if parts.pop() != Some("{}") {
                panic!(
                    "'{}' is an invalid template: expected '<Modifiers>-{{}}'",
                    t
                )
            };
            keynames
                .iter()
                .map(|k| Binding {
                    raw: format!("{}-{}", parts.join("-"), k),
                    mods: parts.iter().map(|m| m.to_string()).collect(),
                    keyname: Some(k.into()),
                })
                .collect::<Vec<Binding>>()
        })
        .collect()
}

fn has_valid_modifiers(binding: &Binding) -> bool {
    !binding.mods.is_empty()
        && binding
            .mods
            .iter()
            .all(|s| VALID_MODIFIERS.contains(&s.as_ref()))
}

fn is_valid_keyname(binding: &Binding, names: &[String]) -> bool {
    if let Some(ref k) = binding.keyname {
        names.contains(&k)
    } else {
        false
    }
}

fn report_error(msg: impl AsRef<str>, b: &Binding) {
    panic!(
        "'{}' is an invalid key binding: {}\n\
        Key bindings should be of the form <modifiers>-<key name> e.g:  M-j, M-S-slash, M-C-Up",
        b.raw,
        msg.as_ref()
    )
}

/// This is an internal macro that is used as part of `gen_keybindings` to validate user provided
/// key bindings at compile time using xmodmap.
///
/// It is not intended for use outside of that context and may be modified and updated without
/// announcing breaking API changes.
///
/// ```no_run
/// validate_user_bindings!(
///     ( "M-a", ... )
///     (
///         ( ( "M-{}", "M-S-{}" ) ( "1", "2", "3" ) )
///         ...
///     )
/// );
/// ```
#[proc_macro]
pub fn validate_user_bindings(input: TokenStream) -> TokenStream {
    let BindingsInput(mut bindings) = parse_macro_input!(input as BindingsInput);
    let names: Vec<String> = XKeySym::iter().map(|x| x.as_ref().to_string()).collect();
    let mut seen = HashSet::new();

    for b in bindings.iter_mut() {
        if seen.contains(&b.raw) {
            panic!("'{}' is bound as a keybinding more than once", b.raw);
        } else {
            seen.insert(&b.raw);
        }

        if b.keyname.is_none() {
            report_error("no key name specified", b)
        }

        if !is_valid_keyname(b, &names) {
            report_error(
                format!(
                    "'{}' is not a known key: run 'xmodmap -pke' to see valid key names",
                    b.keyname.take().unwrap()
                ),
                b,
            )
        }

        if !has_valid_modifiers(b) {
            report_error(
                format!(
                    "'{}' is an invalid modifer set: valid modifiers are {:?}",
                    b.mods.join("-"),
                    VALID_MODIFIERS
                ),
                b,
            );
        }
    }

    // If everything is fine then just consume the input
    TokenStream::new()
}