aexlo 0.1.0

Run After Effects plugins without Adobe dependencies.
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
use crate::core::diagnostics::*;
use crate::suites::macros::stub_log;
use after_effects_sys::*;
use std::os::raw::c_void;
#[cfg(windows)]
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::{AtomicI32, Ordering};

/// Encode a path as a null-terminated UTF-16 string, the representation
/// `get_platform_data` hands back for `PF_PlatData_*_FILE_PATH_W` queries.
fn encode_path_utf16(path: &std::path::Path) -> Vec<u16> {
	#[cfg(windows)]
	{
		use std::os::windows::ffi::OsStrExt;
		path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
	}
	#[cfg(not(windows))]
	{
		path.to_string_lossy()
			.encode_utf16()
			.chain(std::iter::once(0))
			.collect()
	}
}

/// The pre-CS6 selectors return an A_char buffer in the host's legacy
/// multibyte encoding, not UTF-16. Include the trailing NUL in the result.
fn encode_path_legacy(path: &std::path::Path) -> Option<Vec<u8>> {
	#[cfg(windows)]
	{
		use std::os::windows::ffi::OsStrExt;
		#[link(name = "kernel32")]
		unsafe extern "system" {
			fn WideCharToMultiByte(
				code_page: u32,
				flags: u32,
				wide: *const u16,
				wide_len: i32,
				bytes: *mut u8,
				bytes_len: i32,
				default_char: *const u8,
				used_default: *mut i32,
			) -> i32;
			fn MultiByteToWideChar(
				code_page: u32,
				flags: u32,
				bytes: *const u8,
				bytes_len: i32,
				wide: *mut u16,
				wide_len: i32,
			) -> i32;
		}
		// Adobe's SDK specifies the Windows OEM code page for legacy strings.
		let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
		if wide[..wide.len() - 1].contains(&0) {
			return None;
		}
		// SAFETY: `wide` is NUL-terminated (`-1` length) and the output buffer is null with size 0, which asks for the needed size.
		let needed = unsafe {
			WideCharToMultiByte(
				1,
				0,
				wide.as_ptr(),
				-1,
				std::ptr::null_mut(),
				0,
				std::ptr::null(),
				std::ptr::null_mut(),
			)
		};
		if needed <= 0 || needed > 260 {
			return None;
		}
		let mut bytes = vec![0; needed as usize];
		// SAFETY: `bytes` holds exactly `needed` bytes, the size the previous call asked for.
		let written = unsafe {
			WideCharToMultiByte(
				1,
				0,
				wide.as_ptr(),
				-1,
				bytes.as_mut_ptr(),
				needed,
				std::ptr::null(),
				std::ptr::null_mut(),
			)
		};
		if written != needed {
			return None;
		}
		// Reject substitutions and best-fit mappings: returning a different path
		// as success is worse than reporting that the legacy encoding cannot hold it.
		let mut round_trip = vec![0; wide.len()];
		// SAFETY: `bytes` is NUL-terminated (`-1` length) and `round_trip` holds `round_trip.len()` units.
		let decoded = unsafe {
			MultiByteToWideChar(
				1,
				0,
				bytes.as_ptr(),
				-1,
				round_trip.as_mut_ptr(),
				round_trip.len() as i32,
			)
		};
		if decoded != wide.len() as i32 || round_trip != wide {
			return None;
		}
		Some(bytes)
	}
	#[cfg(not(windows))]
	{
		use std::os::unix::ffi::OsStrExt;
		let bytes = path.as_os_str().as_bytes();
		if bytes.len() >= 260 || bytes.contains(&0) {
			return None;
		}
		Some(bytes.iter().copied().chain(std::iter::once(0)).collect())
	}
}

// ============================================================================
// Stub Functions (Generated by macro)
// ============================================================================

stub_log!(blend_stub,
	_effect_ref: PF_ProgPtr,
	_src1: *const PF_EffectWorld,
	_src2: *const PF_EffectWorld,
	_ratio: PF_Fixed,
	_dst: *mut PF_EffectWorld
);

stub_log!(convolve_stub,
	_effect_ref: PF_ProgPtr,
	_src: *mut PF_EffectWorld,
	_area: *const PF_Rect,
	_flags: PF_KernelFlags,
	_kernel_size: A_long,
	_a_kernel: *mut c_void,
	_r_kernel: *mut c_void,
	_g_kernel: *mut c_void,
	_b_kernel: *mut c_void,
	_dst: *mut PF_EffectWorld
);

unsafe extern "C" fn copy_sys(
	_effect_ref: PF_ProgPtr,
	src: *mut PF_EffectWorld,
	dst: *mut PF_EffectWorld,
	_src_rect: *mut PF_Rect,
	_dst_rect: *mut PF_Rect,
) -> PF_Err {
	crate::core::ffi::guard("copy_sys", || {
		//== Validation ==//
		if src.is_null() {
			log::warn!("copy: src pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		if dst.is_null() {
			log::warn!("copy: dst pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		//== Implementation ==//
		// Copy src into dst row by row: the worlds may have different strides, and
		// each row only owns `rowbytes` bytes, so copying more (or advancing by
		// anything but the stride) reads/writes out of bounds.
		// SAFETY: `src` and `dst` are non-null (checked above) and point at the plugin's worlds for this call.
		let src_ref = &unsafe { *src };
		// SAFETY: As above, for `dst`.
		let dst_ref = &mut unsafe { *dst };

		if !src_ref.data.is_null() && !dst_ref.data.is_null() {
			let rows = src_ref.height.min(dst_ref.height).max(0) as usize;
			let src_stride = src_ref.rowbytes.max(0) as usize;
			let dst_stride = dst_ref.rowbytes.max(0) as usize;
			let bytes_per_row = src_stride.min(dst_stride);

			for row in 0..rows {
				// SAFETY: `row < rows`, and `rows` and both strides come from the worlds, so each row start stays inside its buffer.
				let src_ptr = unsafe { (src_ref.data as *const u8).add(row * src_stride) };
				// SAFETY: As above, for the destination world.
				let dst_ptr = unsafe { (dst_ref.data as *mut u8).add(row * dst_stride) };

				// SAFETY: Each row owns at least `bytes_per_row` bytes in both worlds, and `src` and `dst` are distinct buffers.
				unsafe { std::ptr::copy_nonoverlapping(src_ptr, dst_ptr, bytes_per_row) };
			}
		}

		diag!("UtilityCallbacks/copy",
			"effect_ref" => _effect_ref as usize,
			"src" => format!("{:?}", src),
			"dst" => format!("{:?}", dst),
			"src_rect" => format!("{:?}", _src_rect),
			"dst_rect" => format!("{:?}", _dst_rect),
		);

		PF_Err_NONE as PF_Err
	})
}

stub_log!(gaussian_kernel_stub,
	_effect_ref: PF_ProgPtr,
	_kRadius: A_FpLong,
	_flags: PF_KernelFlags,
	_multiplier: A_FpLong,
	_diameter: *mut A_long,
	_kernel: *mut c_void
);

// `PF_Err_NONE` is `u32` on macOS and `i32` elsewhere, so `as i32` is redundant
// here (Windows/Linux) but required on macOS. Silence the platform-specific lint.
#[allow(clippy::unnecessary_cast)]
unsafe extern "C" fn iterate_stub(
	in_data: *mut PF_InData,
	progress_base: A_long,
	progress_final: A_long,
	src: *mut PF_EffectWorld,
	area: *const PF_Rect,
	refcon: *mut c_void,
	pix_fn: ::std::option::Option<
		unsafe extern "C" fn(
			refcon: *mut c_void,
			x: A_long,
			y: A_long,
			in_: *mut PF_Pixel,
			out: *mut PF_Pixel,
		) -> PF_Err,
	>,
	dst: *mut PF_EffectWorld,
) -> PF_Err {
	crate::core::ffi::guard("iterate_stub", || {
		#[cfg(not(feature = "diagnostics"))]
		let _ = (in_data, progress_base, progress_final);

		#[cfg(feature = "diagnostics")]
		DiagnosticBuilder::new()
			.set_name("UtilityCallbacks/iterate")
			.add_arg("in_data", format!("{:?}", in_data))
			.add_arg("progress_base", progress_base)
			.add_arg("progress_final", progress_final)
			.add_arg("src", format!("{:?}", src))
			.add_arg(
				"area",
				if !area.is_null() {
					format!("{:?}", area)
				} else {
					"(null)".to_string()
				},
			)
			.add_arg("refcon", format!("{:?}", refcon))
			.add_arg("pix_fn", if pix_fn.is_some() { "Some" } else { "None" })
			.add_arg("dst", format!("{:?}", dst))
			.emit();

		if dst.is_null() {
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		// A null `src` is legal: the SDK's `iterate` then walks `dst` only, which is
		// how generator effects (no input layer) invoke it. Fall back to `dst` as the
		// source so the bounds and the per-pixel `in`/`out` pointers coincide, matching
		// AE's dst-only iteration -- rather than rejecting it as a bad parameter.
		let src = if src.is_null() { dst } else { src };

		// SAFETY: `dst` is non-null (checked above), and `src` is either non-null or `dst`.
		let src_world = unsafe { &*src };
		// SAFETY: As above, for `dst`.
		let dst_world = unsafe { &*dst };

		if src_world.data.is_null() || dst_world.data.is_null() {
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		let mut rect = if !area.is_null() {
			// SAFETY: `area` is non-null in this branch and points at the plugin's rect.
			unsafe { *area }
		} else {
			PF_Rect {
				left: 0,
				top: 0,
				right: dst_world.width,
				bottom: dst_world.height,
			}
		};

		rect.left = rect.left.max(0);
		rect.top = rect.top.max(0);
		rect.right = rect.right.min(src_world.width);
		rect.bottom = rect.bottom.min(src_world.height);
		rect.right = rect.right.min(dst_world.width);
		rect.bottom = rect.bottom.min(dst_world.height);

		let start_x = rect.left;
		let start_y = rect.top;
		let end_x = rect.right;
		let end_y = rect.bottom;

		let width = (end_x - start_x).max(0);
		let height = (end_y - start_y).max(0);

		if width == 0 || height == 0 {
			return PF_Err_NONE as PF_Err;
		}

		let src_base_addr = src_world.data as usize;
		let src_rowbytes = src_world.rowbytes as isize;
		let dst_base_addr = dst_world.data as usize;
		let dst_rowbytes = dst_world.rowbytes as isize;
		let pixel_size = std::mem::size_of::<PF_Pixel>();

		debug_assert!(
			src_world.rowbytes >= (src_world.width * pixel_size as i32),
			"Source rowbytes smaller than width * pixel_size"
		);

		let refcon_addr = refcon as usize;
		let error_capsule = AtomicI32::new(PF_Err_NONE as i32);

		if let Some(func) = pix_fn {
			crate::suites::iterate::for_each_index(0..height, |y_offset| {
				if error_capsule.load(Ordering::Relaxed) != PF_Err_NONE as i32 {
					return;
				}

				let current_y = start_y + y_offset;
				let src_row_ptr = (src_base_addr as *const u8).wrapping_offset((current_y as isize) * src_rowbytes);
				let dst_row_ptr = (dst_base_addr as *mut u8).wrapping_offset((current_y as isize) * dst_rowbytes);
				let refcon_ptr = refcon_addr as *mut c_void;

				for x_offset in 0..width {
					let current_x = start_x + x_offset;
					let src_pixel = src_row_ptr.wrapping_add((current_x as usize) * pixel_size) as *mut PF_Pixel;
					let dst_pixel = dst_row_ptr.wrapping_add((current_x as usize) * pixel_size) as *mut PF_Pixel;

					// SAFETY: `func` is the plugin's pixel callback; `src_pixel`/`dst_pixel` are inside the rect clamped to both worlds above.
					let err = unsafe { func(refcon_ptr, current_x, current_y, src_pixel, dst_pixel) };
					if err != PF_Err_NONE as i32 {
						error_capsule.store(err, Ordering::Relaxed);
						return;
					}
				}
			});
		}

		error_capsule.load(Ordering::Relaxed) as PF_Err
	})
}

stub_log!(get_callback_addr_stub,
	_effect_ref: PF_ProgPtr,
	_quality: PF_Quality,
	_mode_flags: PF_ModeFlags,
	_which_callback: PF_CallbackID,
	_fn_ptr: *mut PF_CallbackFunc
);

unsafe extern "C" fn app_stub(_effect_ref: PF_ProgPtr, _selector: A_long, _args: ...) -> PF_Err {
	crate::core::ffi::guard("app_stub", || {
		log::warn!("STUB: app called");
		PF_Err_NONE as PF_Err
	})
}

// ============================================================================
// Implemented Functions
// ============================================================================

/// PF_PlatDataID constants
const PF_PLAT_DATA_EXE_FILE_PATH_W: PF_PlatDataID = 7;
const PF_PLAT_DATA_RES_FILE_PATH_W: PF_PlatDataID = 8;

unsafe extern "C" fn get_platform_data_impl(effect_ref: PF_ProgPtr, which: PF_PlatDataID, data: *mut c_void) -> PF_Err {
	crate::core::ffi::guard("get_platform_data_impl", || {
		#[cfg(feature = "diagnostics")]
		DiagnosticBuilder::new()
			.set_name("get_platform_data")
			.add_arg("which", which)
			.add_arg("data", format!("{:?}", data))
			.emit();

		if data.is_null() {
			log::warn!("get_platform_data: data pointer is null");
			return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
		}

		match which {
			0 => {
				// PF_PlatData_MAIN_WND. Effects parent their own editor windows here.
				#[cfg(windows)]
				{
					let hwnd = host_window();
					if hwnd.is_null() {
						return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
					}
					// SAFETY: `data` is non-null (checked above) and the SDK makes it a `void**` out-slot for `PF_PlatData_MAIN_WND`.
					unsafe { *(data as *mut *mut c_void) = hwnd };
					PF_Err_NONE as PF_Err
				}
				#[cfg(not(windows))]
				{
					let _ = data;
					PF_Err_BAD_CALLBACK_PARAM as PF_Err
				}
			}
			1 | 2 => {
				// The host currently does not load separate localized resource files,
				// so both legacy selectors refer to the loaded plugin binary.
				let Some(instance) = crate::PluginInstance::get_instance_ptr(effect_ref) else {
					return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
				};
				// SAFETY: `effect_ref` is the `PluginInstance` aexlo handed the plugin in `in_data`, and the plugin calls back during one of that instance's commands (see `PluginInstance::get_instance_ptr`).
				let Some(path) = (unsafe { instance.as_ref() }).resolved_binary_path() else {
					return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
				};
				let Some(bytes) = encode_path_legacy(path) else {
					return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
				};
				// SAFETY: `data` is non-null (checked above), and the SDK sizes it for `AEFX_MAX_PATH` bytes; `encode_path_legacy` fails beyond that.
				unsafe {
					std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::<u8>(), bytes.len());
				}
				PF_Err_NONE as PF_Err
			}
			PF_PLAT_DATA_EXE_FILE_PATH_W | PF_PLAT_DATA_RES_FILE_PATH_W => {
				// The path is per instance (recovered via effect_ref), so loading a
				// second plugin can't clobber the first one's answer.
				let Some(instance) = crate::PluginInstance::get_instance_ptr(effect_ref) else {
					log::warn!("get_platform_data: no instance for effect_ref");
					return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
				};
				// SAFETY: `effect_ref` is the `PluginInstance` aexlo handed the plugin in `in_data`, and the plugin calls back during one of that instance's commands (see `PluginInstance::get_instance_ptr`).
				let Some(path) = unsafe { instance.as_ref() }.resolved_binary_path() else {
					log::warn!("get_platform_data: plugin path not set (in-process entry point?)");
					return PF_Err_BAD_CALLBACK_PARAM as PF_Err;
				};

				// Copy the UTF-16 path into the output buffer (max AEFX_MAX_PATH = 260)
				let wide = encode_path_utf16(path);
				let dst = data as *mut u16;
				const AEFX_MAX_PATH: usize = 260;
				let copy_len = wide.len().min(AEFX_MAX_PATH);
				// SAFETY: `data` is non-null (checked above), and the SDK sizes it for `AEFX_MAX_PATH` UTF-16 units; `copy_len` is clamped to that.
				unsafe {
					std::ptr::copy_nonoverlapping(wide.as_ptr(), dst, copy_len);
					// Ensure null termination if truncated
					if wide.len() > AEFX_MAX_PATH {
						*dst.add(AEFX_MAX_PATH - 1) = 0;
					}
				}
				log::debug!("get_platform_data: returned plugin path (len={})", copy_len);
				PF_Err_NONE as PF_Err
			}
			_ => {
				log::warn!("get_platform_data: unsupported which={}", which);
				PF_Err_NONE as PF_Err // Return OK for unsupported, as AE does
			}
		}
	})
}

/// HWND a GUI host wants plugins to treat as After Effects' main window.
/// Zero means "create the fallback window below".
#[cfg(windows)]
static MAIN_WINDOW: AtomicIsize = AtomicIsize::new(0);

/// Tell plugins which window is `PF_PlatData_MAIN_WND`.
///
/// An owned editor stays hidden for as long as its owner is hidden, so a
/// windowed host passes its own visible HWND. `null` clears the override.
#[cfg(windows)]
pub(crate) fn set_main_window(hwnd: *mut c_void) {
	MAIN_WINDOW.store(hwnd as isize, Ordering::Relaxed);
}

/// Top-level window used as `PF_PlatData_MAIN_WND`. Created on the calling
/// thread, which is also the thread that later dispatches its messages.
#[cfg(windows)]
fn host_window() -> *mut c_void {
	let chosen = MAIN_WINDOW.load(Ordering::Relaxed);
	if chosen != 0 {
		return chosen as *mut c_void;
	}
	static WINDOW: std::sync::OnceLock<isize> = std::sync::OnceLock::new();
	// SAFETY: `create_host_window` has no preconditions; it runs once, on the thread that will pump its messages.
	let hwnd = *WINDOW.get_or_init(|| unsafe { create_host_window() });
	hwnd as *mut c_void
}

#[cfg(windows)]
unsafe fn create_host_window() -> isize {
	#[repr(C)]
	struct WndClass {
		style: u32,
		wnd_proc: unsafe extern "system" fn(*mut c_void, u32, usize, isize) -> isize,
		class_extra: i32,
		window_extra: i32,
		instance: *mut c_void,
		icon: *mut c_void,
		cursor: *mut c_void,
		background: *mut c_void,
		menu_name: *const u16,
		class_name: *const u16,
	}
	#[link(name = "user32")]
	unsafe extern "system" {
		fn RegisterClassW(class: *const WndClass) -> u16;
		fn CreateWindowExW(
			ex_style: u32,
			class_name: *const u16,
			window_name: *const u16,
			style: u32,
			x: i32,
			y: i32,
			width: i32,
			height: i32,
			parent: *mut c_void,
			menu: *mut c_void,
			instance: *mut c_void,
			param: *mut c_void,
		) -> *mut c_void;
		fn DefWindowProcW(hwnd: *mut c_void, msg: u32, wparam: usize, lparam: isize) -> isize;
		fn ShowWindow(hwnd: *mut c_void, cmd: i32) -> i32;
	}
	#[link(name = "kernel32")]
	unsafe extern "system" {
		fn GetModuleHandleW(module: *const u16) -> *mut c_void;
	}
	unsafe extern "system" fn wnd_proc(hwnd: *mut c_void, msg: u32, wparam: usize, lparam: isize) -> isize {
		// SAFETY: Windows calls this with the arguments of a message for `hwnd`, which are forwarded unchanged.
		unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
	}

	let class_name: Vec<u16> = "aexlo_host".encode_utf16().chain(std::iter::once(0)).collect();
	let title: Vec<u16> = "aexlo".encode_utf16().chain(std::iter::once(0)).collect();
	// SAFETY: a null module name asks for the handle of the current executable.
	let instance = unsafe { GetModuleHandleW(std::ptr::null()) };
	let class = WndClass {
		style: 0,
		wnd_proc,
		class_extra: 0,
		window_extra: 0,
		instance,
		icon: std::ptr::null_mut(),
		cursor: std::ptr::null_mut(),
		background: 6isize as *mut c_void, // COLOR_WINDOW + 1
		menu_name: std::ptr::null(),
		class_name: class_name.as_ptr(),
	};
	// SAFETY: `class` and the `class_name` buffer it points to outlive the call.
	unsafe { RegisterClassW(&class) };
	// SAFETY: `class_name` and `title` are NUL-terminated UTF-16 buffers that outlive the call; the null parent, menu and param are allowed.
	let hwnd = unsafe {
		CreateWindowExW(
			0,
			class_name.as_ptr(),
			title.as_ptr(),
			0x00CF_0000,
			0x8000_0000u32 as i32,
			0x8000_0000u32 as i32,
			960,
			640,
			std::ptr::null_mut(),
			std::ptr::null_mut(),
			instance,
			std::ptr::null_mut(),
		)
	};
	if hwnd.is_null() {
		log::warn!("get_platform_data: failed to create the host window");
		return 0;
	}
	// Must be visible. Windows hides an owned popup while its owner is hidden,
	// which is what made plugin editors look like a click that did nothing.
	// SAFETY: `hwnd` is the window created above (checked non-null); 5 is `SW_SHOW`.
	unsafe { ShowWindow(hwnd, 5) };
	hwnd as isize
}

// ============================================================================
// Factory Function
// ============================================================================

/// Creates a `_PF_UtilCallbacks` instance with all callbacks populated.
pub fn create_utility_callbacks() -> Box<_PF_UtilCallbacks> {
	Box::new(_PF_UtilCallbacks {
		begin_sampling: Some(crate::suites::sampling::begin_sampling_sys),
		subpixel_sample: Some(crate::suites::sampling::subpixel_sample_8_sys),
		area_sample: Some(crate::suites::sampling::area_sample_8_sys),
		get_batch_func_is_deprecated: std::ptr::null_mut(),
		end_sampling: Some(crate::suites::sampling::end_sampling_sys),
		composite_rect: Some(crate::suites::transform::composite_rect_sys),
		blend: Some(blend_stub),
		convolve: Some(convolve_stub),
		copy: Some(copy_sys),
		fill: Some(crate::suites::fill_matte::fill_8_sys),
		gaussian_kernel: Some(gaussian_kernel_stub),
		iterate: Some(iterate_stub),
		premultiply: Some(crate::suites::fill_matte::premultiply_sys),
		premultiply_color: Some(crate::suites::fill_matte::premultiply_color_8_sys),
		new_world: Some(crate::suites::world::new_world_util),
		dispose_world: Some(crate::suites::world::dispose_world_sys),
		iterate_origin: Some(crate::suites::iterate::iterate_origin_8_sys),
		iterate_lut: Some(crate::suites::iterate::iterate_lut_sys),
		transfer_rect: Some(crate::suites::transform::transfer_rect_sys),
		transform_world: Some(crate::suites::transform::transform_world_sys),
		host_new_handle: Some(crate::suites::handle::host_new_handle_impl),
		host_lock_handle: Some(crate::suites::handle::host_lock_handle_impl),
		host_unlock_handle: Some(crate::suites::handle::host_unlock_handle_impl),
		host_dispose_handle: Some(crate::suites::handle::host_dispose_handle_impl),
		get_callback_addr: Some(get_callback_addr_stub),
		app: Some(app_stub),
		ansi: crate::suites::SUITE_CONTAINER.ansi, // Use existing ANSI callbacks
		// The legacy colorCB block has the same layout as PF_ColorCallbacksSuite1,
		// so it shares the suite's 8-bpc implementations.
		colorCB: PF_ColorCallbacks {
			RGBtoHLS: Some(crate::suites::color_callbacks::rgb_to_hls_8_sys),
			HLStoRGB: Some(crate::suites::color_callbacks::hls_to_rgb_8_sys),
			RGBtoYIQ: Some(crate::suites::color_callbacks::rgb_to_yiq_8_sys),
			YIQtoRGB: Some(crate::suites::color_callbacks::yiq_to_rgb_8_sys),
			Luminance: Some(crate::suites::color_callbacks::luminance_8_sys),
			Hue: Some(crate::suites::color_callbacks::hue_8_sys),
			Lightness: Some(crate::suites::color_callbacks::lightness_8_sys),
			Saturation: Some(crate::suites::color_callbacks::saturation_8_sys),
		},
		get_platform_data: Some(get_platform_data_impl),
		host_get_handle_size: Some(crate::suites::handle::host_get_handle_size_impl),
		iterate_origin_non_clip_src: Some(crate::suites::iterate::iterate_origin_non_clip_src_8_sys),
		iterate_generic: Some(crate::suites::iterate::iterate_generic_sys),
		host_resize_handle: Some(crate::suites::handle::host_resize_handle_impl),
		subpixel_sample16: Some(crate::suites::sampling::subpixel_sample_16_sys),
		area_sample16: Some(crate::suites::sampling::area_sample_16_sys),
		fill16: Some(crate::suites::fill_matte::fill_16_sys),
		premultiply_color16: Some(crate::suites::fill_matte::premultiply_color_16_sys),
		iterate16: Some(crate::suites::iterate::iterate_16_sys),
		iterate_origin16: Some(crate::suites::iterate::iterate_origin_16_sys),
		iterate_origin_non_clip_src16: Some(crate::suites::iterate::iterate_origin_non_clip_src_16_sys),
		get_pixel_data8: Some(crate::suites::pixel_data::get_pixel_data_8_sys),
		get_pixel_data16: Some(crate::suites::pixel_data::get_pixel_data_16_sys),
		reserved: [0; 1],
	})
}

#[cfg(test)]
mod tests {
	use crate::pixel::{Depth8, Layer};

	use super::*;

	#[test]
	fn legacy_path_is_nul_terminated_and_bounded() {
		let encoded = encode_path_legacy(std::path::Path::new("C:/Plugins/Glow.aex")).unwrap();
		assert_eq!(encoded, b"C:/Plugins/Glow.aex\0");
		assert_eq!(
			encode_path_legacy(std::path::Path::new(&"a".repeat(259)))
				.unwrap()
				.len(),
			260
		);
		assert!(encode_path_legacy(std::path::Path::new(&"a".repeat(260))).is_none());
	}

	#[test]
	fn legacy_path_rejects_null_output() {
		let result = unsafe { get_platform_data_impl(std::ptr::null_mut(), 2, std::ptr::null_mut()) };
		assert_eq!(result, PF_Err_BAD_CALLBACK_PARAM as PF_Err);
	}

	#[test]
	fn test_copy() {
		//== Create dummy worlds ==//
		let mut src_layer = Layer::<Depth8>::black(4, 4);
		let mut dst_layer = Layer::<Depth8>::blank(4, 4);

		let mut src_world = src_layer.as_sys();
		let mut dst_world = dst_layer.as_sys();

		//== Call ==//
		let result = unsafe {
			copy_sys(
				std::ptr::null_mut(),
				&mut src_world,
				&mut dst_world,
				std::ptr::null_mut(),
				std::ptr::null_mut(),
			)
		};

		assert_eq!(result, PF_Err_NONE as PF_Err);

		// Verify that the destination world now contains the copied pixels
		for x in 0..64 {
			let src_pixel = unsafe { *(src_world.data as *const i8).add(x) };
			let dst_pixel = unsafe { *(dst_world.data as *const i8).add(x) };
			assert_eq!(src_pixel, dst_pixel, "Pixel mismatch at index {}", x);
		}
	}
}