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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
//! Macros
//!
//
// NOTE: Use full paths everywhere. Don't assume anything will be in scope.

#[allow(unused_imports)] // for doc comments
use crate::{
    c_api::{NCRESULT_ERR, NCRESULT_OK},
    Nc, NcDirect, NcError, NcIntResultApi, NcPlane, NcResult, NcVisual, NcVisualOptions,
};

// Sleep, Render & Flush Macros ------------------------------------------------

/// Sleeps for `$s` seconds + `$ms` milliseconds
/// + `$us` microseconds + `$ns` nanoseconds
#[macro_export]
macro_rules! sleep {
    ($s:expr) => {
        std::thread::sleep(std::time::Duration::from_secs($s));
    };

    ($s:expr, $ms:expr) => {
        std::thread::sleep(std::time::Duration::from_millis($s * 1000 + $ms));
    };
    ($s:expr, $ms:expr, $us:expr) => {
        std::thread::sleep(std::time::Duration::from_micros(
            $s * 1_000_000 + $ms * 1_000 + $us,
        ));
    };
    ($s:expr, $ms:expr, $us:expr, $ns:expr) => {
        std::thread::sleep(std::time::Duration::from_nanos(
            $s * 1_000_000_000 + $ms * 1_000_000 + $us * 1_000 + $ns,
        ));
    };
}

/// [`Nc::render`][Nc#method.render]\(`$nc`\)? + [`sleep!`]`[$sleep_args]`.
///
/// Renders the `$nc` [`Nc`]'s standard pile, and then,
/// if there's no error, calls the `sleep` macro with the rest of the arguments.
///
/// Returns [`NcResult`].
#[macro_export]
macro_rules! nc_render_sleep {
    ($nc:expr, $( $sleep_args:expr),+ ) => {
        crate::Nc::render($nc)?;
        sleep![$( $sleep_args ),+];
    };
    ($nc:expr, $( $sleep_args:expr),+ ,) => {
        rsleep![$nc, $( $sleep_args ),* ]
    };
}

/// [`NcPlane::render`][NcPlane#method.render]\(`$p`\)? +
/// [`NcPlane::rasterize`][NcPlane#method.rasterize]\(`$p`\)? +
/// [`sleep!`]`[$sleep_args]`.
///
/// Renders and rasterizes the `$p` [`NcPlane`] pile and then, if there are
/// no errors, calls the sleep macro with the rest of the arguments.
///
/// Returns [`NcResult`].
#[macro_export]
macro_rules! pile_render_sleep {
    ($p:expr, $( $sleep_args:expr),+ ) => {
        crate::NcPlane::render($p)?;
        crate::NcPlane::rasterize($p)?;
        sleep![$( $sleep_args ),+];
    };
    ($nc:expr, $( $sleep_args:expr),+ ,) => {
        rsleep![$nc, $( $sleep_args ),* ]
    };
}

/// [`NcVisual::blit`][NcVisual#method.blit]\(`$v`, `$nc`, `$vo`\)? +
/// [`Nc::render`][Nc#method.render]\(`$nc`\)? + [`sleep!`]`[$sleep_args]`.
///
/// Renders and rasterizes the `$v` [`NcVisual`] with its `$vo`
/// [`NcVisualOptions`], the $nc` [`Nc`]'s standard pile, and then, if there are
/// no errors, calls the `sleep` macro with the rest of the arguments.
///
/// Returns [`NcResult`].
#[macro_export]
macro_rules! visual_render_sleep {
    ($v: expr, $vo: expr, $nc:expr, $( $sleep_args:expr),+ ) => {
        unsafe { crate::NcVisual::blit($v, $nc, Some($vo))? };
        crate::Nc::render($nc)?;
        sleep![$( $sleep_args ),+];
    };
    ($nc:expr, $( $sleep_args:expr),+ ,) => {
        rsleep![$nc, $( $sleep_args ),* ]
    };
}

// String & Print Macros -------------------------------------------------------

/// Converts an `&str` into `*const c_char`.
///
/// See [`Cstring`].
#[macro_export]
#[doc(hidden)]
macro_rules! cstring {
    ($s:expr) => {
        // NOTE: The returned pointer will be valid for as long as self is
        // CHECK does this live long enough in all circumstances?
        std::ffi::CString::new($s).unwrap().as_ptr()
    };
}

/// Converts an `&str` into `*mut c_char`.
///
/// See [`Cstring`].
#[macro_export]
#[doc(hidden)]
macro_rules! cstring_mut {
    ($s:expr) => {
        // we can't use this without taking the responsibility of deallocating:
        std::ffi::CString::new($s).unwrap().into_raw()

        // another option:
        // unsafe { crate::c_api::libc::strdup(crate::cstring![$s]) }
    };
}

/// Converts a `*const c_char` into an `&str`.
#[macro_export]
#[doc(hidden)]
macro_rules! rstring {
    ($s:expr) => {
        unsafe { std::ffi::CStr::from_ptr($s).to_str().unwrap() }
        // possible alternative:
        // unsafe { std::ffi::CStr::from_ptr($s).to_string_lossy() }
    };
}

/// Converts a `*const c_char` into a `String`, freeing the original alloc.
#[macro_export]
#[doc(hidden)]
macro_rules! rstring_free {
    ($s:expr) => {{
        #[allow(unused_unsafe)]
        let nc_string = unsafe { $s };
        let string = crate::rstring![nc_string].to_string();
        unsafe { crate::c_api::libc::free(nc_string as *mut core::ffi::c_void) };
        string
    }};
}

/// Wrapper around [`libc::printf`][c_api::libc::printf].
#[macro_export]
#[doc(hidden)]
macro_rules! printf {
    ($s:expr) => {
        unsafe { crate::c_api::libc::printf(cstring![$s]) }
    };
    ($s:expr $(, $opt:expr)*) => {
        unsafe { crate::c_api::libc::printf(cstring![$s], $($opt),*) }
    };
}

/// Wrapper around [`NcPlane.putstr`][NcPlane#method.putstr],
/// rendering and rasterizing the plane afterwards.
///
/// Returns an `NcResult` with the number of columns advanced,
/// without including newlines.
///
/// # Example
/// ```ignore
/// # use libnotcurses_sys::*;
/// # fn main() -> NcResult<()> {
/// let nc = unsafe { Nc::new_cli()? };
/// let splane = unsafe { nc.stdplane() };
/// splane.set_scrolling(true);
/// putstr!(splane, "hello ")?;
/// putstr!(splane, " world\n")?;
/// putstr!(splane, "formatted text: {:?}\n", (0, 1.0, "two") )?;
/// # unsafe { nc.stop()? };
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! putstr {
    ($plane:ident, $text:literal) => {
        {
            let res = $plane.putstr($text)?;
            $plane.render()?;
            $plane.rasterize()?;
            Ok(res)
        }
    };
    ($plane:ident, $text:literal, $($args:tt)*) => {
        {
            let res = $plane.putstr(&format![$text, $($args)*])?;
            $plane.render()?;
            $plane.rasterize()?;
            Ok(res)
        }
    };
}

/// Wrapper around [`NcPlane.putstrln`][NcPlane#method.putstrln].
/// rendering and rasterizing the plane afterwards.
///
/// Returns an `NcResult` with the number of columns advanced,
/// without including newlines.
///
/// # Example
/// ```ignore
/// # use libnotcurses_sys::*;
/// # fn main() -> NcResult<()> {
/// let nc = unsafe { Nc::new_cli()? };
/// let splane = nc.stdplane();
/// splane.set_scrolling(true);
/// putstrln!(splane, "hello world")?;
/// putstrln!(splane, "formatted text: {:?}", (0, 1.0, "two") )?;
/// # unsafe { nc.stop()? };
/// # Ok(())
/// # }
/// ```
#[macro_export]
macro_rules! putstrln {
    ($plane:ident) => {
        {
            let res = $plane.putln()?;
            $plane.render()?;
            $plane.rasterize()?;
            Ok(res)
        }
    };
    ($plane:ident, $text:literal) => {
        {
            let res = $plane.putstrln($text)?;
            $plane.render()?;
            $plane.rasterize()?;
            Ok(res)
        }
    };
    ($plane:ident, $text:literal, $($args:tt)*) => {
        {
            let res = $plane.putstrln(&format![$text, $($args)*])?;
            $plane.render()?;
            $plane.rasterize()?;
            Ok(res)
        }
    };
}

// Error Wrappers Macros -------------------------------------------------------

/// Returns an `Ok($ok)`,
/// or an `Err(`[`NcError`]`)` if `$res` < [`NCRESULT_OK`].
///
/// In other words:
/// Returns Ok(`$ok`) if `$res` >= [NCRESULT_OK], otherwise returns
/// Err([NcError]::[new][NcError#method.new](`$res`, `$msg`)).
///
/// `$ok` & `$msg` are optional. By default they will be the unit
/// type `()`, and an empty `&str` `""`, respectively.
#[macro_export]
#[doc(hidden)]
macro_rules! error {
    ($res:expr, $msg:expr, $ok:expr) => {{
        let res = $res;
        if res >= crate::c_api::NCRESULT_OK {
            return Ok($ok);
        } else {
            return Err(crate::NcError::with_msg(res, $msg));
        }
    }};
    ($res:expr, $msg:expr) => {
        error![$res, $msg, ()]
    };
    ($res:expr) => {
        error![$res, "", ()]
    };
}

/// Returns an `Ok(&T)` from a `*const T` pointer,
/// or an `Err(`[`NcError`]`)` if the pointer is null.
///
/// In other words:
/// Returns Ok(&*`$ptr`) if `!$ptr.is_null()`, otherwise returns
/// Err([NcError]]::[new][NcError#method.new]([NCRESULT_ERR], `$msg`)).
///
/// `$msg` is optional. By default it will be an empty `&str` `""`.
#[macro_export]
#[doc(hidden)]
macro_rules! error_ref {
    ($ptr:expr, $msg:expr, $ok:expr) => {{
        let ptr = $ptr; // avoid calling a function multiple times
        if ptr.is_null() {
            return Err(crate::NcError::with_msg(crate::c_api::NCRESULT_ERR, $msg));
        } else {
            #[allow(unused_unsafe)]
            return Ok(unsafe { $ok });
        }
    }};
    ($ptr:expr, $msg:expr) => {{
        let ptr = $ptr;
        error_ref![$ptr, $msg, unsafe { &*ptr }];
    }};
    ($ptr:expr) => {{
        let ptr = $ptr;
        error_ref![$ptr, "", unsafe { &*ptr }];
    }};
}

/// Returns an `Ok(&mut T)` from a `*mut T` pointer,
/// or an `Err(`[`NcError`]`)` if the pointer is null.
///
/// In other words:
/// Returns Ok(&mut *`$ptr`) if `!$ptr._is_null()`, otherwise returns
/// Err([NcError]]::[new][NcError#method.new]([NCRESULT_ERR], `$msg`)).
///
/// `$msg` is optional. By default it will be an empty `&str` `""`.
#[macro_export]
#[doc(hidden)]
macro_rules! error_ref_mut {
    ($ptr:expr, $msg:expr, $ok:expr) => {{
        let ptr = $ptr; // avoid calling a function multiple times
        if ptr.is_null() {
            return Err(crate::NcError::with_msg(crate::c_api::NCRESULT_ERR, $msg));
        } else {
            #[allow(unused_unsafe)]
            return Ok(unsafe { $ok });
        }
    }};
    ($ptr:expr, $msg:expr) => {{
        let ptr = $ptr;
        error_ref_mut![ptr, $msg, unsafe { &mut *ptr }];
    }};
    ($ptr:expr) => {{
        let ptr = $ptr;
        error_ref_mut![ptr, "", unsafe { &mut *ptr }];
    }};
}

/// Returns an `Ok(String)` from a `*const` pointer to a C string,
/// or an `Err(`[`NcError`]`)` if the pointer is null.
///
/// In other words:
/// Returns Ok((&*`$str`).to_string()) if `!$str.is_null()`, otherwise returns
/// Err([NcError]]::[new][NcError#method.new]([NCRESULT_ERR], `$msg`)).
///
/// `$msg` is optional. By default it will be an empty `&str` `""`.
#[macro_export]
#[doc(hidden)]
macro_rules! error_str {
    ($str:expr, $msg:expr) => {
        if !$str.is_null() {
            #[allow(unused_unsafe)]
            return Ok(unsafe { crate::rstring!($str).to_string() });
        } else {
            return Err(crate::NcError::with_msg(crate::c_api::NCRESULT_ERR, $msg));
        }
    };
    ($str:expr) => {
        error_str![$str, ""];
    };
}

// Implementation Helper Macros ------------------------------------------------

/// Implements methods and constants for an existing type.
//
// Allows to have full doc-comments both in the trait definition
// and in the concrete implementation.
#[macro_export]
#[doc(hidden)]
macro_rules! impl_api {
    ($type:ident, $trait:ident, $($i:item),*) => {
        #[doc = concat!("Enables the [`", stringify!($type), "`] associated methods and constants.")]
        pub trait $trait {
            $($i)*
        }

        impl $trait for $type {
            $($i)*
        }
    };
}