aexlo 0.3.0

Run After Effects plugins without Adobe dependencies.
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! `AEGP Layer Mask Suite` v7 (`AEGP_MaskSuite6`) and v6 (`AEGP_MaskSuite5`),
//! and `AEGP Mask Outline Suite` v5 (`AEGP_MaskOutlineSuite3`) and v3
//! (`AEGP_MaskOutlineSuite2`): read access to the masks an embedder puts on the
//! effect's layer with
//! [`PluginInstance::set_mask_paths`](crate::PluginInstance::set_mask_paths),
//! the same ones the "PF Path Query Suite" serves.
//!
//! An `AEGP_MaskRefH` names a mask by its index on the layer, so a ref taken
//! before the embedder replaces the masks reads the mask now at that index, or
//! fails if there is none. A mask's outline reaches the plugin as the value of
//! its `AEGP_MaskStream_OUTLINE` stream ([`super::stream`]): an
//! `AEGP_MaskOutlineValH` holding a copy of the path, freed with the stream
//! value. Masks are static here, so times are ignored, and nothing can change
//! them: every setter, and creating, deleting or duplicating a mask, is
//! declined.
//!
//! Both handle kinds are kept in a list of the ones handed out: a plugin that
//! bails out of a failed call may pass an uninitialised handle, which is
//! refused instead of read or freed.

use crate::PluginInstance;
use crate::core::diagnostics::diag;
use crate::mask::MaskPath;
use crate::sys::*;
use std::sync::{Mutex, MutexGuard, PoisonError};

/// Addresses of the boxes of one handle kind that are handed out and not yet
/// disposed.
struct Handed(Mutex<Vec<usize>>);

impl Handed {
	const fn new() -> Self {
		Self(Mutex::new(Vec::new()))
	}

	fn lock(&self) -> MutexGuard<'_, Vec<usize>> {
		self.0.lock().unwrap_or_else(PoisonError::into_inner)
	}

	fn hand_out<T>(&self, value: T) -> *mut T {
		let ptr = Box::into_raw(Box::new(value));
		self.lock().push(ptr as usize);
		ptr
	}

	/// The box at `ptr`, if it was handed out and not taken back.
	fn get<'a, T>(&self, ptr: *const T) -> Option<&'a T> {
		if !self.lock().contains(&(ptr as usize)) {
			return None;
		}
		// SAFETY: a listed address is a live `Box<T>` from `hand_out`, freed only
		// by `take_back`.
		unsafe { ptr.as_ref() }
	}

	/// Take back and free the box at `ptr`; `false` if it is not handed out.
	fn take_back<T>(&self, ptr: *mut T) -> bool {
		{
			let mut handed = self.lock();
			let Some(at) = handed.iter().position(|&p| p == ptr as usize) else {
				return false;
			};
			handed.swap_remove(at);
		}
		// SAFETY: it was listed, so it is a `Box<T>` from `hand_out`, and it is
		// no longer listed.
		drop(unsafe { Box::from_raw(ptr) });
		true
	}
}

/// What an `AEGP_MaskRefH` points at.
#[derive(Clone, Copy)]
pub(crate) struct MaskRef {
	pub(crate) effect_ref: PF_ProgPtr,
	pub(crate) index: usize,
}

/// What an `AEGP_MaskOutlineValH` points at.
struct Outline {
	path: MaskPath,
}

static MASK_REFS: Handed = Handed::new();
static OUTLINES: Handed = Handed::new();

/// The masks on the layer of the instance behind `effect_ref`.
fn masks<'a>(effect_ref: PF_ProgPtr) -> Option<&'a [MaskPath]> {
	let instance = PluginInstance::get_instance_ptr(effect_ref)?;
	// SAFETY: a non-null effect ref that reached a suite call is the live instance.
	Some(unsafe { instance.as_ref() }.mask_paths())
}

/// The mask ref behind `mask_refH`, if aexlo handed it out.
pub(crate) fn mask_ref(mask_refH: AEGP_MaskRefH) -> Option<MaskRef> {
	MASK_REFS.get(mask_refH as *const MaskRef).copied()
}

/// The mask `mask_refH` names, if it is still on the layer.
fn mask<'a>(mask_refH: AEGP_MaskRefH) -> Option<&'a MaskPath> {
	let mask = mask_ref(mask_refH)?;
	masks(mask.effect_ref)?.get(mask.index)
}

/// A new outline value holding a copy of the mask at `index`, or null.
pub(crate) fn new_outline(effect_ref: PF_ProgPtr, index: usize) -> AEGP_MaskOutlineValH {
	match masks(effect_ref).and_then(|masks| masks.get(index)) {
		Some(path) => OUTLINES.hand_out(Outline { path: path.clone() }) as AEGP_MaskOutlineValH,
		None => std::ptr::null_mut(),
	}
}

/// An outline value holding `path`, as [`new_outline`] makes one.
#[cfg(test)]
pub(crate) fn outline_of(path: MaskPath) -> AEGP_MaskOutlineValH {
	OUTLINES.hand_out(Outline { path }) as AEGP_MaskOutlineValH
}

/// Free an outline from [`new_outline`]; anything else is left alone.
pub(crate) fn dispose_outline(outlineH: AEGP_MaskOutlineValH) -> bool {
	OUTLINES.take_back(outlineH as *mut Outline)
}

fn outline<'a>(outlineH: AEGP_MaskOutlineValH) -> Option<&'a MaskPath> {
	OUTLINES.get(outlineH as *const Outline).map(|o| &o.path)
}

/// Whether `index` is a mask on the layer of `effect_ref`.
pub(crate) fn has_mask(effect_ref: PF_ProgPtr, index: usize) -> bool {
	masks(effect_ref).is_some_and(|masks| index < masks.len())
}

fn declined(name: &'static str) -> A_Err {
	crate::observe::unsupported(
		crate::observe::UnsupportedKind::Declined,
		name,
		"aexlo's masks are read-only",
	);
	A_Err_GENERIC
}

/// Write `value` through `out`, or refuse a null `out`.
fn answer<T>(out: *mut T, value: T) -> A_Err {
	match unsafe { out.as_mut() } {
		Some(out) => {
			*out = value;
			PF_Err_NONE
		}
		None => PF_Err_BAD_CALLBACK_PARAM,
	}
}

/// Answer `out` from the mask `mask_refH` names.
fn from_mask<T>(mask_refH: AEGP_MaskRefH, out: *mut T, value: impl FnOnce(&MaskPath) -> T) -> A_Err {
	match mask(mask_refH) {
		Some(mask) => answer(out, value(mask)),
		None => PF_Err_BAD_CALLBACK_PARAM,
	}
}

// ============================================================================
// AEGP Layer Mask Suite
// ============================================================================

unsafe extern "C" fn get_layer_num_masks(aegp_layerH: AEGP_LayerH, num_masksPL: *mut A_long) -> A_Err {
	crate::core::ffi::guard("AEGP_GetLayerNumMasks", || {
		diag!("AEGP_MaskSuite/AEGP_GetLayerNumMasks", "aegp_layerH" => format!("{:#x}", aegp_layerH as usize));
		// Layer handles are the effect's `PF_ProgPtr` (see `layer::layer_handle`).
		let Some(masks) = masks(aegp_layerH as PF_ProgPtr) else {
			return PF_Err_BAD_CALLBACK_PARAM;
		};
		answer(num_masksPL, masks.len() as A_long)
	})
}

unsafe extern "C" fn get_layer_mask_by_index(
	aegp_layerH: AEGP_LayerH,
	mask_indexL: AEGP_MaskIndex,
	maskPH: *mut AEGP_MaskRefH,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetLayerMaskByIndex", || {
		diag!("AEGP_MaskSuite/AEGP_GetLayerMaskByIndex",
			"aegp_layerH" => format!("{:#x}", aegp_layerH as usize),
			"mask_indexL" => mask_indexL,
		);
		let Some(out) = (unsafe { maskPH.as_mut() }) else {
			return PF_Err_BAD_CALLBACK_PARAM;
		};
		*out = std::ptr::null_mut();
		let effect_ref = aegp_layerH as PF_ProgPtr;
		if masks(effect_ref).is_none() {
			return PF_Err_BAD_CALLBACK_PARAM;
		}
		let Some(index) = usize::try_from(mask_indexL).ok().filter(|&i| has_mask(effect_ref, i)) else {
			return PF_Err_INVALID_INDEX;
		};
		*out = MASK_REFS.hand_out(MaskRef { effect_ref, index }) as AEGP_MaskRefH;
		PF_Err_NONE
	})
}

unsafe extern "C" fn dispose_mask(mask_refH: AEGP_MaskRefH) -> A_Err {
	crate::core::ffi::guard("AEGP_DisposeMask", || {
		diag!("AEGP_MaskSuite/AEGP_DisposeMask", "mask_refH" => format!("{:#x}", mask_refH as usize));
		if !MASK_REFS.take_back(mask_refH as *mut MaskRef) {
			log::warn!("AEGP_MaskSuite/AEGP_DisposeMask: {mask_refH:?} was not handed out, or was disposed");
			return PF_Err_BAD_CALLBACK_PARAM;
		}
		PF_Err_NONE
	})
}

unsafe extern "C" fn get_mask_invert(mask_refH: AEGP_MaskRefH, invertPB: *mut A_Boolean) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskInvert", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskInvert", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, invertPB, |m| m.inverted as A_Boolean)
	})
}

unsafe extern "C" fn get_mask_mode(mask_refH: AEGP_MaskRefH, modeP: *mut PF_MaskMode) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskMode", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskMode", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, modeP, |m| m.mode.to_sys())
	})
}

/// Masks follow the layer's motion blur switch.
unsafe extern "C" fn get_mask_motion_blur_state(mask_refH: AEGP_MaskRefH, blur_stateP: *mut AEGP_MaskMBlur) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskMotionBlurState", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskMotionBlurState", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, blur_stateP, |_| AEGP_MaskMBlur_SAME_AS_LAYER)
	})
}

/// After Effects' default falloff.
unsafe extern "C" fn get_mask_feather_falloff(
	mask_refH: AEGP_MaskRefH,
	feather_falloffP: *mut AEGP_MaskFeatherFalloff,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskFeatherFalloff", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskFeatherFalloff", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, feather_falloffP, |_| AEGP_MaskFeatherFalloff_SMOOTH)
	})
}

/// The id a `PF_Param_PATH` parameter refers to the mask by.
unsafe extern "C" fn get_mask_id(mask_refH: AEGP_MaskRefH, id_valP: *mut AEGP_MaskIDVal) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskID", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskID", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, id_valP, |m| m.id as AEGP_MaskIDVal)
	})
}

/// After Effects' first mask colour, a light blue.
const MASK_COLOR: AEGP_ColorVal = AEGP_ColorVal {
	alphaF: 1.0,
	redF: 0.69,
	greenF: 0.78,
	blueF: 0.98,
};

unsafe extern "C" fn get_mask_color(mask_refH: AEGP_MaskRefH, colorP: *mut AEGP_ColorVal) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskColor", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskColor", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, colorP, |_| MASK_COLOR)
	})
}

unsafe extern "C" fn get_mask_lock_state(mask_refH: AEGP_MaskRefH, is_lockedPB: *mut A_Boolean) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskLockState", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskLockState", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, is_lockedPB, |_| 0)
	})
}

unsafe extern "C" fn get_mask_is_roto_bezier(mask_refH: AEGP_MaskRefH, is_roto_bezierPB: *mut A_Boolean) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskIsRotoBezier", || {
		diag!("AEGP_MaskSuite/AEGP_GetMaskIsRotoBezier", "mask_refH" => format!("{:#x}", mask_refH as usize));
		from_mask(mask_refH, is_roto_bezierPB, |_| 0)
	})
}

/// A setter, or a call that adds or removes masks: declined.
macro_rules! declined {
	($name:ident, $function:literal, ($($arg:ident: $ty:ty),*)) => {
		unsafe extern "C" fn $name($($arg: $ty),*) -> A_Err {
			crate::core::ffi::guard($function, || {
				$(let _ = $arg;)*
				diag!(concat!("AEGP_MaskSuite/", $function));
				declined(concat!("AEGP_MaskSuite/", $function))
			})
		}
	};
}

declined!(set_mask_invert, "AEGP_SetMaskInvert", (mask_refH: AEGP_MaskRefH, invertB: A_Boolean));
declined!(set_mask_mode, "AEGP_SetMaskMode", (maskH: AEGP_MaskRefH, mode: PF_MaskMode));
declined!(set_mask_motion_blur_state, "AEGP_SetMaskMotionBlurState", (mask_refH: AEGP_MaskRefH, blur_state: AEGP_MaskMBlur));
declined!(set_mask_feather_falloff, "AEGP_SetMaskFeatherFalloff", (mask_refH: AEGP_MaskRefH, falloff: AEGP_MaskFeatherFalloff));
declined!(create_new_mask, "AEGP_CreateNewMask", (layerH: AEGP_LayerH, mask_refPH: *mut AEGP_MaskRefH, mask_indexPL0: *mut A_long));
declined!(delete_mask_from_layer, "AEGP_DeleteMaskFromLayer", (mask_refH: AEGP_MaskRefH));
declined!(set_mask_color, "AEGP_SetMaskColor", (mask_refH: AEGP_MaskRefH, colorP: *const AEGP_ColorVal));
declined!(set_mask_lock_state, "AEGP_SetMaskLockState", (mask_refH: AEGP_MaskRefH, lockB: A_Boolean));
declined!(set_mask_is_roto_bezier, "AEGP_SetMaskIsRotoBezier", (mask_refH: AEGP_MaskRefH, is_roto_bezierB: A_Boolean));
declined!(duplicate_mask, "AEGP_DuplicateMask", (orig_mask_refH: AEGP_MaskRefH, duplicate_mask_refPH: *mut AEGP_MaskRefH));

/// Wire version 7.
pub(super) const fn mask_suite_6() -> AEGP_MaskSuite6 {
	AEGP_MaskSuite6 {
		AEGP_GetLayerNumMasks: Some(get_layer_num_masks),
		AEGP_GetLayerMaskByIndex: Some(get_layer_mask_by_index),
		AEGP_DisposeMask: Some(dispose_mask),
		AEGP_GetMaskInvert: Some(get_mask_invert),
		AEGP_SetMaskInvert: Some(set_mask_invert),
		AEGP_GetMaskMode: Some(get_mask_mode),
		AEGP_SetMaskMode: Some(set_mask_mode),
		AEGP_GetMaskMotionBlurState: Some(get_mask_motion_blur_state),
		AEGP_SetMaskMotionBlurState: Some(set_mask_motion_blur_state),
		AEGP_GetMaskFeatherFalloff: Some(get_mask_feather_falloff),
		AEGP_SetMaskFeatherFalloff: Some(set_mask_feather_falloff),
		AEGP_GetMaskID: Some(get_mask_id),
		AEGP_CreateNewMask: Some(create_new_mask),
		AEGP_DeleteMaskFromLayer: Some(delete_mask_from_layer),
		AEGP_GetMaskColor: Some(get_mask_color),
		AEGP_SetMaskColor: Some(set_mask_color),
		AEGP_GetMaskLockState: Some(get_mask_lock_state),
		AEGP_SetMaskLockState: Some(set_mask_lock_state),
		AEGP_GetMaskIsRotoBezier: Some(get_mask_is_roto_bezier),
		AEGP_SetMaskIsRotoBezier: Some(set_mask_is_roto_bezier),
		AEGP_DuplicateMask: Some(duplicate_mask),
	}
}

/// Wire version 6: version 7 without the feather falloff calls.
pub(super) const fn mask_suite_5() -> AEGP_MaskSuite5 {
	AEGP_MaskSuite5 {
		AEGP_GetLayerNumMasks: Some(get_layer_num_masks),
		AEGP_GetLayerMaskByIndex: Some(get_layer_mask_by_index),
		AEGP_DisposeMask: Some(dispose_mask),
		AEGP_GetMaskInvert: Some(get_mask_invert),
		AEGP_SetMaskInvert: Some(set_mask_invert),
		AEGP_GetMaskMode: Some(get_mask_mode),
		AEGP_SetMaskMode: Some(set_mask_mode),
		AEGP_GetMaskMotionBlurState: Some(get_mask_motion_blur_state),
		AEGP_SetMaskMotionBlurState: Some(set_mask_motion_blur_state),
		AEGP_GetMaskID: Some(get_mask_id),
		AEGP_CreateNewMask: Some(create_new_mask),
		AEGP_DeleteMaskFromLayer: Some(delete_mask_from_layer),
		AEGP_GetMaskColor: Some(get_mask_color),
		AEGP_SetMaskColor: Some(set_mask_color),
		AEGP_GetMaskLockState: Some(get_mask_lock_state),
		AEGP_SetMaskLockState: Some(set_mask_lock_state),
		AEGP_GetMaskIsRotoBezier: Some(get_mask_is_roto_bezier),
		AEGP_SetMaskIsRotoBezier: Some(set_mask_is_roto_bezier),
		AEGP_DuplicateMask: Some(duplicate_mask),
	}
}

// ============================================================================
// AEGP Mask Outline Suite
// ============================================================================

/// Answer `out` from the outline `outlineH`.
fn from_outline<T>(outlineH: AEGP_MaskOutlineValH, out: *mut T, value: impl FnOnce(&MaskPath) -> T) -> A_Err {
	match outline(outlineH) {
		Some(path) => answer(out, value(path)),
		None => PF_Err_BAD_CALLBACK_PARAM,
	}
}

unsafe extern "C" fn is_mask_outline_open(mask_outlineH: AEGP_MaskOutlineValH, openPB: *mut A_Boolean) -> A_Err {
	crate::core::ffi::guard("AEGP_IsMaskOutlineOpen", || {
		diag!("AEGP_MaskOutlineSuite/AEGP_IsMaskOutlineOpen", "mask_outlineH" => format!("{:#x}", mask_outlineH as usize));
		from_outline(mask_outlineH, openPB, |p| !p.closed as A_Boolean)
	})
}

unsafe extern "C" fn get_mask_outline_num_segments(
	mask_outlineH: AEGP_MaskOutlineValH,
	num_segmentsPL: *mut A_long,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskOutlineNumSegments", || {
		diag!("AEGP_MaskOutlineSuite/AEGP_GetMaskOutlineNumSegments",
			"mask_outlineH" => format!("{:#x}", mask_outlineH as usize),
		);
		from_outline(mask_outlineH, num_segmentsPL, |p| p.segment_count() as A_long)
	})
}

/// Vertex `which_pointL` in `0..=segments`, tangents relative to the vertex;
/// on a closed outline the last index is vertex 0 again.
unsafe extern "C" fn get_mask_outline_vertex_info(
	mask_outlineH: AEGP_MaskOutlineValH,
	which_pointL: AEGP_VertexIndex,
	vertexP: *mut AEGP_MaskVertex,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskOutlineVertexInfo", || {
		diag!("AEGP_MaskOutlineSuite/AEGP_GetMaskOutlineVertexInfo",
			"mask_outlineH" => format!("{:#x}", mask_outlineH as usize),
			"which_pointL" => which_pointL,
		);
		let Some(path) = outline(mask_outlineH) else {
			return PF_Err_BAD_CALLBACK_PARAM;
		};
		let Some(v) = usize::try_from(which_pointL).ok().and_then(|i| path.vertex(i)) else {
			return PF_Err_INVALID_INDEX;
		};
		answer(
			vertexP,
			AEGP_MaskVertex {
				x: v.x,
				y: v.y,
				tan_in_x: v.tan_in_x,
				tan_in_y: v.tan_in_y,
				tan_out_x: v.tan_out_x,
				tan_out_y: v.tan_out_y,
			},
		)
	})
}

/// aexlo's masks have no variable-width feather points.
unsafe extern "C" fn get_mask_outline_num_feathers(
	mask_outlineH: AEGP_MaskOutlineValH,
	num_feathersPL: *mut A_long,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskOutlineNumFeathers", || {
		diag!("AEGP_MaskOutlineSuite/AEGP_GetMaskOutlineNumFeathers",
			"mask_outlineH" => format!("{:#x}", mask_outlineH as usize),
		);
		from_outline(mask_outlineH, num_feathersPL, |_| 0)
	})
}

unsafe extern "C" fn get_mask_outline_feather_info(
	mask_outlineH: AEGP_MaskOutlineValH,
	which_featherL: AEGP_FeatherIndex,
	_featherP: *mut AEGP_MaskFeather,
) -> A_Err {
	crate::core::ffi::guard("AEGP_GetMaskOutlineFeatherInfo", || {
		diag!("AEGP_MaskOutlineSuite/AEGP_GetMaskOutlineFeatherInfo",
			"mask_outlineH" => format!("{:#x}", mask_outlineH as usize),
			"which_featherL" => which_featherL,
		);
		if outline(mask_outlineH).is_none() {
			return PF_Err_BAD_CALLBACK_PARAM;
		}
		PF_Err_INVALID_INDEX
	})
}

/// A call that changes an outline: declined.
macro_rules! declined_outline {
	($name:ident, $function:literal, ($($arg:ident: $ty:ty),*)) => {
		unsafe extern "C" fn $name($($arg: $ty),*) -> A_Err {
			crate::core::ffi::guard($function, || {
				$(let _ = $arg;)*
				diag!(concat!("AEGP_MaskOutlineSuite/", $function));
				declined(concat!("AEGP_MaskOutlineSuite/", $function))
			})
		}
	};
}

declined_outline!(set_mask_outline_open, "AEGP_SetMaskOutlineOpen", (mask_outlineH: AEGP_MaskOutlineValH, openB: A_Boolean));
declined_outline!(set_mask_outline_vertex_info, "AEGP_SetMaskOutlineVertexInfo", (mask_outlineH: AEGP_MaskOutlineValH, which_pointL: AEGP_VertexIndex, vertexP: *const AEGP_MaskVertex));
declined_outline!(create_vertex, "AEGP_CreateVertex", (mask_outlineH: AEGP_MaskOutlineValH, insert_position: AEGP_VertexIndex));
declined_outline!(delete_vertex, "AEGP_DeleteVertex", (mask_outlineH: AEGP_MaskOutlineValH, index: AEGP_VertexIndex));
declined_outline!(set_mask_outline_feather_info, "AEGP_SetMaskOutlineFeatherInfo", (mask_outlineH: AEGP_MaskOutlineValH, which_featherL: AEGP_VertexIndex, featherP: *const AEGP_MaskFeather));
declined_outline!(create_mask_outline_feather, "AEGP_CreateMaskOutlineFeather", (mask_outlineH: AEGP_MaskOutlineValH, featherP0: *const AEGP_MaskFeather, insert_positionP: *mut AEGP_FeatherIndex));
declined_outline!(delete_mask_outline_feather, "AEGP_DeleteMaskOutlineFeather", (mask_outlineH: AEGP_MaskOutlineValH, index: AEGP_FeatherIndex));

/// Wire version 5. Version 3 (`AEGP_MaskOutlineSuite2`) is its first seven
/// entries, so this table serves both.
pub(super) const fn mask_outline_suite_3() -> AEGP_MaskOutlineSuite3 {
	AEGP_MaskOutlineSuite3 {
		AEGP_IsMaskOutlineOpen: Some(is_mask_outline_open),
		AEGP_SetMaskOutlineOpen: Some(set_mask_outline_open),
		AEGP_GetMaskOutlineNumSegments: Some(get_mask_outline_num_segments),
		AEGP_GetMaskOutlineVertexInfo: Some(get_mask_outline_vertex_info),
		AEGP_SetMaskOutlineVertexInfo: Some(set_mask_outline_vertex_info),
		AEGP_CreateVertex: Some(create_vertex),
		AEGP_DeleteVertex: Some(delete_vertex),
		AEGP_GetMaskOutlineNumFeathers: Some(get_mask_outline_num_feathers),
		AEGP_GetMaskOutlineFeatherInfo: Some(get_mask_outline_feather_info),
		AEGP_SetMaskOutlineFeatherInfo: Some(set_mask_outline_feather_info),
		AEGP_CreateMaskOutlineFeather: Some(create_mask_outline_feather),
		AEGP_DeleteMaskOutlineFeather: Some(delete_mask_outline_feather),
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::mask::MaskVertex;

	fn triangle() -> MaskPath {
		MaskPath {
			id: 7,
			vertices: vec![
				MaskVertex {
					tan_out_x: 2.0,
					..MaskVertex::corner(0.0, 0.0)
				},
				MaskVertex::corner(4.0, 0.0),
				MaskVertex::corner(4.0, 4.0),
			],
			closed: true,
			..Default::default()
		}
	}

	#[test]
	fn an_outline_is_read_and_freed_once() {
		let outline = OUTLINES.hand_out(Outline { path: triangle() }) as AEGP_MaskOutlineValH;
		let suite = mask_outline_suite_3();
		unsafe {
			let mut open: A_Boolean = 1;
			assert_eq!(suite.AEGP_IsMaskOutlineOpen.unwrap()(outline, &mut open), PF_Err_NONE);
			assert_eq!(open, 0);
			let mut segments = 0;
			assert_eq!(
				suite.AEGP_GetMaskOutlineNumSegments.unwrap()(outline, &mut segments),
				PF_Err_NONE
			);
			assert_eq!(segments, 3);

			let mut vertex: AEGP_MaskVertex = std::mem::zeroed();
			let info = suite.AEGP_GetMaskOutlineVertexInfo.unwrap();
			assert_eq!(
				info(outline, 3, &mut vertex),
				PF_Err_NONE,
				"closed: the last index wraps"
			);
			assert_eq!((vertex.x, vertex.y, vertex.tan_out_x), (0.0, 0.0, 2.0));
			assert_eq!(info(outline, 4, &mut vertex), PF_Err_INVALID_INDEX);

			let mut feathers = -1;
			assert_eq!(
				suite.AEGP_GetMaskOutlineNumFeathers.unwrap()(outline, &mut feathers),
				PF_Err_NONE
			);
			assert_eq!(feathers, 0);
			assert_eq!(suite.AEGP_SetMaskOutlineOpen.unwrap()(outline, 1), A_Err_GENERIC);
		}
		assert!(dispose_outline(outline));
		assert!(!dispose_outline(outline), "freed once");
		let mut open: A_Boolean = 0;
		assert_eq!(
			unsafe { mask_outline_suite_3().AEGP_IsMaskOutlineOpen.unwrap()(outline, &mut open) },
			PF_Err_BAD_CALLBACK_PARAM
		);
	}

	#[test]
	fn handles_that_were_never_handed_out_are_refused() {
		// What an uninitialised local might hold.
		let garbage = 0xdead_beef_usize;
		let masks = mask_suite_6();
		unsafe {
			assert_eq!(
				masks.AEGP_DisposeMask.unwrap()(garbage as AEGP_MaskRefH),
				PF_Err_BAD_CALLBACK_PARAM
			);
			let mut id = 0;
			assert_eq!(
				masks.AEGP_GetMaskID.unwrap()(garbage as AEGP_MaskRefH, &mut id),
				PF_Err_BAD_CALLBACK_PARAM
			);
			let mut count = 0;
			assert_eq!(
				masks.AEGP_GetLayerNumMasks.unwrap()(std::ptr::null_mut(), &mut count),
				PF_Err_BAD_CALLBACK_PARAM
			);
			let mut segments = 0;
			assert_eq!(
				mask_outline_suite_3().AEGP_GetMaskOutlineNumSegments.unwrap()(
					garbage as AEGP_MaskOutlineValH,
					&mut segments
				),
				PF_Err_BAD_CALLBACK_PARAM
			);
		}
		assert!(!dispose_outline(garbage as AEGP_MaskOutlineValH));
	}

	#[test]
	fn masks_cannot_be_changed() {
		let masks = mask_suite_6();
		unsafe {
			assert_eq!(
				masks.AEGP_SetMaskInvert.unwrap()(std::ptr::null_mut(), 1),
				A_Err_GENERIC
			);
			assert_eq!(
				masks.AEGP_CreateNewMask.unwrap()(std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()),
				A_Err_GENERIC
			);
		}
	}
}