camlet 1.0.0

Library for writing plug-ins for the camlet webcam application
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
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
#![deny(missing_docs)]
//! Crate for making plug-ins for the webcam application camlet.
//!
//! See <https://camlet.pommicket.com/doc/quickstart_rust.html> for a guide on how to use this library.

use fmt::Write as FmtWrite;
use io::{BufReader, prelude::*};
use std::collections::HashMap;
use std::fs::File;
use std::mem::take;
use std::os::fd::FromRawFd;
use std::process::ExitCode;
use std::time::Duration;
use std::{fmt, io};

#[derive(Debug)]
enum IError {
	IO(io::Error),
	InvalidLineFormat(Box<str>),
	NoInit,
	CantHandleVersion(u32),
}

type Socket = BufReader<File>;

/// Some kind of error
///
/// e.g. camlet process was killed.
/// The details of the error are opaque for now.
#[derive(Debug)]
pub struct Error(IError);

impl From<IError> for Error {
	fn from(value: IError) -> Self {
		Self(value)
	}
}

impl From<io::Error> for Error {
	fn from(value: io::Error) -> Self {
		Self(IError::IO(value))
	}
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match &self.0 {
			IError::IO(e) => write!(f, "{e}"),
			IError::NoInit => write!(f, "First command should be init."),
			IError::InvalidLineFormat(line) => {
				write!(f, "Protocol error: invalid line format: {line}")
			}
			IError::CantHandleVersion(version) => {
				write!(f, "Can't handle camlet version {version}")
			}
		}
	}
}

impl std::error::Error for Error {
	fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
		if let Error(IError::IO(io)) = self {
			return Some(io);
		}
		None
	}
}
type Result<T> = std::result::Result<T, Error>;

/// A value which can be passed through a shader uniform
///
/// Note that matrices are interpreted as `[[f32; ROWS]; COLUMNS]` (i.e.
/// an array of columns, not an array of rows), for consistency with GLSL.
pub trait UniformValue {
	/// Convert it to camlet's uniform syntax.
	fn to_raw(&self, into: &mut String);
}

impl UniformValue for i32 {
	fn to_raw(&self, into: &mut String) {
		into.push_str(self.format_into(&mut core::fmt::NumBuffer::new()));
	}
}
impl UniformValue for f32 {
	fn to_raw(&self, into: &mut String) {
		// important not to use the default {}, since that
		// formats 0.0 as just 0 (which will be interpreted as an int by camlet)
		write!(into, "{:e}", self).unwrap()
	}
}
impl UniformValue for u32 {
	fn to_raw(&self, into: &mut String) {
		into.push_str(self.format_into(&mut core::fmt::NumBuffer::new()));
	}
}

macro_rules! impl_vector_uniforms {
	($t:ty, $sep:literal) => {
		impl UniformValue for [$t; 2] {
			fn to_raw(&self, into: &mut String) {
				self[0].to_raw(into);
				into.push($sep);
				self[1].to_raw(into);
			}
		}
		impl UniformValue for [$t; 3] {
			fn to_raw(&self, into: &mut String) {
				self[0].to_raw(into);
				into.push($sep);
				self[1].to_raw(into);
				into.push($sep);
				self[2].to_raw(into);
			}
		}
		impl UniformValue for [$t; 4] {
			fn to_raw(&self, into: &mut String) {
				self[0].to_raw(into);
				into.push($sep);
				self[1].to_raw(into);
				into.push($sep);
				self[2].to_raw(into);
				into.push($sep);
				self[3].to_raw(into);
			}
		}
	};
}

impl_vector_uniforms!(i32, ',');
impl_vector_uniforms!(u32, ',');
impl_vector_uniforms!(f32, ',');
// Matrices
impl_vector_uniforms!([f32; 2], ';');
impl_vector_uniforms!([f32; 3], ';');
impl_vector_uniforms!([f32; 4], ';');

/// A shader for camlet
#[derive(Debug, Clone)]
pub struct Shader {
	code: String,
	bound_textures: String,
	uniforms: String,
}

impl Shader {
	/// Create shader from GLSL code string
	pub fn new(code: &str) -> Self {
		Shader {
			code: code.into(),
			bound_textures: String::new(),
			uniforms: String::new(),
		}
	}
	/// Create shader from path to GLSL code
	pub fn from_path<P: AsRef<std::path::Path>>(path: P) -> io::Result<Self> {
		Ok(Self {
			code: std::fs::read_to_string(path)?,
			bound_textures: String::new(),
			uniforms: String::new(),
		})
	}
	/// Set bound textures for shader
	pub fn bind_textures<I: IntoIterator<Item = (u8, u32)>>(&mut self, textures: I) -> &mut Self {
		self.bound_textures.clear();
		for x in textures {
			let (slot, texture) = x;
			if !self.bound_textures.is_empty() {
				self.bound_textures.push(',');
			}
			write!(self.bound_textures, "{slot}:{texture}").unwrap();
		}
		self
	}
	/// Set a non-array shader uniform
	pub fn set_uniform<U: UniformValue>(&mut self, name: &str, value: U) -> &mut Self {
		self.uniforms.push_str(name);
		self.uniforms.push_str(" = ");
		value.to_raw(&mut self.uniforms);
		self.uniforms.push('\n');
		self
	}
	/// Set an array shader uniform
	pub fn set_uniform_array<U: UniformValue>(
		&mut self,
		name: &str,
		value: impl IntoIterator<Item = U>,
	) -> &mut Self {
		self.uniforms.push_str(name);
		self.uniforms.push_str(" = ");
		let mut first = true;
		for item in value {
			if !first {
				self.uniforms.push('|');
			}
			first = false;
			item.to_raw(&mut self.uniforms);
		}
		self.uniforms.push('\n');
		self
	}
}

/// A command from camlet to the plug-in.
#[derive(Debug)]
pub struct Command {
	name: String,
	arguments: HashMap<String, String>,
	response: HashMap<String, String>,
}

impl Command {
	/// Get a raw argument value.
	///
	/// Use this at your own risk, prefer the methods for specific command types.
	pub fn get(&self, name: &str) -> Option<&str> {
		self.arguments.get(name).map(|s| s.as_ref())
	}
	fn has(&self, name: &str) -> bool {
		self.arguments.contains_key(name)
	}
	fn get_required(&self, name: &str) -> &str {
		match self.get(name) {
			Some(val) => val,
			None => {
				panic!(
					"didn't find required argument {name} to {} command",
					self.name
				)
			}
		}
	}
	fn get_required_u32(&self, name: &str) -> u32 {
		let value = self.get_required(name);
		match value.parse() {
			Ok(val) => val,
			Err(_) => {
				panic!(
					"argument {name} to {} command was not an unsigned integer: {value}",
					self.name
				)
			}
		}
	}
	fn get_required_i32(&self, name: &str) -> i32 {
		let value = self.get_required(name);
		match value.parse() {
			Ok(val) => val,
			Err(_) => {
				panic!(
					"argument {name} to {} command was not an integer: {value}",
					self.name
				)
			}
		}
	}
	fn get_required_f64(&self, name: &str) -> f64 {
		let value = self.get_required(name);
		match value.parse() {
			Ok(val) => val,
			Err(_) => {
				panic!(
					"argument {name} to {} command was not a number: {value}",
					self.name
				)
			}
		}
	}
	/// Set raw response value.
	///
	/// Use this at your own risk, prefer the methods for specific command types.
	pub fn set<N: Into<String>, V: Into<String>>(&mut self, name: N, value: V) {
		self.response.insert(name.into(), value.into());
	}
	fn respond(&self, file: &mut File) -> Result<()> {
		let mut response = format!("ack {}\n", self.name);
		for (argument, value) in self.response.iter() {
			response.push_str(argument);
			response.push_str(":\n");
			for line in value.split('\n') {
				response.push('>');
				response.push_str(line);
				response.push('\n');
			}
		}
		response.push('\n');
		file.write_all(response.as_bytes())?;
		Ok(())
	}
	fn clear_shader(&mut self, prefix: &str) {
		self.response
			.insert(format!("{prefix}_shader"), String::new());
	}
	fn set_shader(&mut self, prefix: &str, shader: Shader) {
		let Shader {
			code,
			bound_textures,
			uniforms,
		} = shader;
		self.response.insert(format!("{prefix}_shader"), code);
		self.response
			.insert(format!("{prefix}_bound_textures"), bound_textures);
		self.response.insert(format!("{prefix}_uniforms"), uniforms);
	}
}

/// `init` command — sent when the plug-in is loaded.
#[derive(Debug)]
pub struct CommandInit(Command);

impl CommandInit {
	/// Major version of camlet
	pub fn version_major(&self) -> u32 {
		self.0.get_required_u32("version_major")
	}
	/// Minor version of camlet
	pub fn version_minor(&self) -> u32 {
		self.0.get_required_u32("version_minor")
	}
	/// Patch version of camlet
	pub fn version_patch(&self) -> u32 {
		self.0.get_required_u32("version_patch")
	}

	fn check_setting(&self, identifier: &str, name: &str) {
		if identifier.is_empty() || identifier.len() > 30 {
			panic!("Setting identifier must be 1-30 bytes long.");
		}
		if identifier.contains([' ', '\n']) {
			panic!("Setting identifier must not contain spaces or newlines.");
		}
		if identifier.starts_with('_') {
			panic!("Setting identifier must not start with underscore.");
		}
		if name.starts_with(';') {
			panic!("Setting name must not contain semicolon");
		}
	}

	/// Define a keyboard shortcut setting.
	///
	/// The identifier is a unique string which allows for renaming it without resetting the value
	pub fn define_keyboard_setting(&mut self, identifier: &str, name: &str, default_value: &str) {
		self.check_setting(identifier, name);
		self.0.set(
			format!("setting_{identifier}"),
			format!("keyboard;{name};{default_value}"),
		);
	}

	/// Define a file setting.
	///
	/// The identifier is a unique string which allows for renaming it without resetting the value
	pub fn define_file_setting(&mut self, identifier: &str, name: &str, default_value: &str) {
		self.check_setting(identifier, name);
		self.0.set(
			format!("setting_{identifier}"),
			format!("file;{name};{default_value}"),
		);
	}

	/// Define a directory setting.
	///
	/// The identifier is a unique string which allows for renaming it without resetting the value
	pub fn define_directory_setting(&mut self, identifier: &str, name: &str, default_value: &str) {
		self.check_setting(identifier, name);
		self.0.set(
			format!("setting_{identifier}"),
			format!("directory;{name};{default_value}"),
		);
	}

	/// Define a number setting.
	///
	/// The identifier is a unique string which allows for renaming it without resetting the value
	pub fn define_number_setting(
		&mut self,
		identifier: &str,
		name: &str,
		min: f64,
		max: f64,
		step: f64,
		default_value: f64,
	) {
		self.check_setting(identifier, name);
		if !(default_value >= min && default_value <= max) {
			panic!("number setting default value must be between minimum and maximum");
		}
		if !min.is_finite() || !max.is_finite() || !step.is_finite() || !default_value.is_finite() {
			panic!("number setting minimum, maximum, step, and default value must all be finite");
		}
		self.0.set(
			format!("setting_{identifier}"),
			format!("number,{min},{max},{step};{name};{default_value}"),
		);
	}

	/// Define a "select" setting (allows user to select from a fixed list of options).
	///
	/// The identifier is a unique string which allows for renaming it without resetting the value.
	pub fn define_select_setting<S: AsRef<str>, I: IntoIterator<Item = S>>(
		&mut self,
		identifier: &str,
		name: &str,
		options: I,
		default_value: &str,
	) {
		self.check_setting(identifier, name);
		let mut value = String::from("select;");
		let mut first = true;
		let mut found = false;
		for option in options {
			if option.as_ref() == default_value {
				found = true;
			}
			if !first {
				value.push(',');
			}
			value.push_str(option.as_ref());
			first = false;
		}
		if !found {
			panic!("default value for select setting must be one of the options.");
		}
		value.push(';');
		value.push_str(name);
		value.push(';');
		value.push_str(default_value);
		self.0.set(format!("setting_{identifier}"), value);
	}
}

/// `quit` command — sent when camlet quits.
#[derive(Debug)]
pub struct CommandQuit(Command);

/// `_key_down` command — sent whenever the user presses a key.
#[derive(Debug)]
pub struct CommandKeyDown(Command);

impl CommandKeyDown {
	/// Number identifying the key
	///
	/// This is unique to the key “label”, i.e. if the user changes keyboard layout,
	/// this value can change for the same physical key.
	pub fn key(&self) -> u32 {
		self.0.get_required_u32("key")
	}

	/// Number identifying the physical key location
	///
	/// If the user changes keyboard layout, this value will not change for the same physical key.
	/// In almost all cases, you should prefer [Self::key] over this.
	pub fn scancode(&self) -> u32 {
		self.0.get_required_u32("scancode")
	}

	/// Human-readable string identifying the key
	pub fn name(&self) -> &str {
		self.0.get_required("name")
	}

	/// Whether this key press was due to key repeat.
	pub fn repeat(&self) -> bool {
		self.0.has("repeat")
	}

	/// String identifying the key combination that was pressed.
	///
	/// This can be compared against the value of keyboard settings.
	pub fn combo(&self) -> &str {
		self.0.get_required("combo")
	}

	/// String identifying which modifier keys are held down.
	///
	/// This contains some letters out of acgsACGS, where
	/// Lowercase = left, uppercase = right, a/A = Alt, c/C = Ctrl,
	/// g/G = GUI (“Windows®” key), s/S = Shift.
	pub fn modifiers(&self) -> &str {
		self.0.get_required("modifiers")
	}
}

/// `_key_up` command — sent whenever the user releases a key.
#[derive(Debug)]
pub struct CommandKeyUp(Command);

impl CommandKeyUp {
	/// Number identifying the key
	///
	/// This is unique to the key “label”, i.e. if the user changes keyboard layout,
	/// this value can change for the same physical key.
	pub fn key(&self) -> u32 {
		self.0.get_required_u32("key")
	}

	/// Number identifying the physical key location
	///
	/// If the user changes keyboard layout, this value will not change for the same physical key.
	/// In almost all cases, you should prefer [Self::key] over this.
	pub fn scancode(&self) -> u32 {
		self.0.get_required_u32("scancode")
	}

	/// Human-readable string identifying the key
	pub fn name(&self) -> &str {
		self.0.get_required("name")
	}
}

/// `_camera_connected` command — sent whenever a new camera is connected.
#[derive(Debug)]
pub struct CommandCameraConnected(Command);

impl CommandCameraConnected {
	/// Human-readable name of the camera (not necessarily unique)
	pub fn name(&self) -> &str {
		self.0.get_required("name")
	}

	/// Opaque string which stays the same for this physical camera.
	///
	/// Stays the same even when it’s unplugged and reconnected, etc.
	/// However, it’s possible, though very unlikely, for two cameras to have
	/// the same hardware_id (e.g. if manufacturer does not give a serial number,
	/// and the names and supported formats of the devices are the same, etc.).
	pub fn hardware_id(&self) -> &str {
		self.0.get_required("hardware_id")
	}

	/// Unique identifier for currently-connected cameras.
	///
	/// May change if a camera is unplugged and reconnected,
	/// but guaranteed to be unique for two cameras that are connected at the same time.
	pub fn device_path(&self) -> &str {
		self.0.get_required("device_path")
	}
}

/// `_camera_disconnected` command — sent whenever a camera is disconnected.
#[derive(Debug)]
pub struct CommandCameraDisconnected(Command);
impl CommandCameraDisconnected {
	/// Path to the device file, previously given by [CommandCameraConnected::device_path].
	pub fn device_path(&self) -> &str {
		self.0.get_required("device_path")
	}
}

/// Format for downloading textures with [CommandFrame::download_texture].
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum DownloadFormat {
	/// JPEG format.
	Jpeg {
		/// JPEG quality, from 1 to 100.
		quality: u8,
	},
	/// PNG format.
	Png,
	/// Raw format.
	///
	/// This will be 4 bytes of little-endian width, 4 bytes of little-endian height,
	/// the literal byte 3, then width × height × 3 bytes of RGB888 data.
	/// (Currently only 3 channels is supported).
	Raw,
}

impl DownloadFormat {
	fn to_raw(self, buffer: &mut [u8; 16]) -> &str {
		match self {
			Self::Jpeg { quality } => {
				if !(1..=100).contains(&quality) {
					panic!("JPEG quality must be between 1 and 100: {quality}")
				}
				write!(&mut buffer[..], "jpg,{quality}").unwrap();
				let len = buffer.iter().position(|&x| x == 0).unwrap();
				std::str::from_utf8(&buffer[..len]).unwrap()
			}
			Self::Png => "png",
			Self::Raw => "raw",
		}
	}
}

/// `frame` command — sent whenever a new frame is rendered.
#[derive(Debug)]
pub struct CommandFrame(Command);

impl CommandFrame {
	/// Returns true if the menu is open.
	pub fn is_menu_open(&self) -> bool {
		self.0.has("menu_open")
	}

	/// Width of the image produced by the camera.
	pub fn camera_width(&self) -> u32 {
		self.0.get_required_u32("camera_width")
	}

	/// Height of the image produced by the camera.
	pub fn camera_height(&self) -> u32 {
		self.0.get_required_u32("camera_height")
	}

	/// Width of the displayed camera feed.
	///
	/// This is different from [Self::camera_width], since the
	/// picture is scaled to match the size of the window.
	/// Does not include any letterboxing added by camlet.
	pub fn picture_width(&self) -> u32 {
		self.0.get_required_u32("picture_width")
	}

	/// Height of the displayed camera feed.
	///
	/// This is different from [Self::camera_height], since the
	/// picture is scaled to match the size of the window.
	/// Does not include any letterboxing added by camlet.
	pub fn picture_height(&self) -> u32 {
		self.0.get_required_u32("picture_height")
	}

	/// Width of the camlet window.
	///
	/// This includes letterboxing (black bars), if there is any.
	pub fn window_width(&self) -> u32 {
		self.0.get_required_u32("window_width")
	}

	/// Height of the camlet window.
	///
	/// This includes letterboxing (black bars), if there is any.
	pub fn window_height(&self) -> u32 {
		self.0.get_required_u32("window_height")
	}

	/// Returns true if the camera has delivered a new picture since the previous frame command.
	pub fn has_new_camera_frame(&self) -> bool {
		self.0.has("new_camera_frame")
	}

	/// Returns the [CommandCameraConnected::device_path] of the active camera, or `None` if no camera is connected.
	pub fn active_camera(&self) -> Option<&str> {
		self.0.get("active_camera")
	}

	/// Returns true if camlet is in photo mode.
	pub fn is_photo_mode(&self) -> bool {
		self.0.get_required("mode") == "photo"
	}

	/// Returns true if camlet is in video mode.
	pub fn is_video_mode(&self) -> bool {
		self.0.get_required("mode") == "video"
	}

	/// Set the camera shader for this plug-in to `shader`.
	pub fn set_camera_shader(&mut self, shader: Shader) {
		self.0.set_shader("camera", shader)
	}

	/// Clear the camera shader for this plug-in.
	pub fn clear_camera_shader(&mut self) {
		self.0.clear_shader("camera")
	}

	/// Set the overlay shader for this plug-in to `shader`.
	pub fn set_overlay_shader(&mut self, shader: Shader) {
		self.0.set_shader("overlay", shader)
	}

	/// Clear the overlay shader for this plug-in.
	pub fn clear_overlay_shader(&mut self) {
		self.0.clear_shader("camera")
	}

	/// Take a photo
	pub fn take_photo(&mut self) {
		self.0.set("take_photo", "");
	}

	/// Start a video recording.
	///
	/// If there is a video recording currently ongoing, it will be stopped.
	/// This does nothing if the menu is open.
	pub fn start_video(&mut self) {
		self.0.set("start_video", "");
	}

	/// Stop recording video.
	pub fn stop_video(&mut self) {
		self.0.set("stop_video", "");
	}

	/// Put camlet in photo mode.
	pub fn photo_mode(&mut self) {
		self.0.set("set_mode", "photo");
	}

	/// Put camlet in video mode.
	pub fn video_mode(&mut self) {
		self.0.set("set_mode", "video");
	}

	/// Switch to a new camera based on its [CommandCameraConnected::device_path].
	pub fn switch_camera(&mut self, device_path: &str) {
		self.0.set("switch_camera", device_path);
	}

	/// Render some text to a texture.
	///
	/// The texture will be given to you with a [CommandGrabbed] command.
	///
	/// Currently the font size of the text cannot be controlled, this might be added eventually.
	pub fn render_text(&mut self, text: &str) {
		self.0.set("render_text", text);
	}

	/// Upload a texture from a file path.
	///
	/// The file will be automatically detected as either PNG, JPEG,
	/// or the “raw” format of 4-byte little-endian width, 4-byte
	/// little-endian height, 1-byte number of color channels
	/// (must be 1, 2, 3, or 4) followed by width × height × channels bytes
	/// of 8-bit-per-channel data. The texture will be given in a [CommandGrabbed].
	pub fn upload_texture(&mut self, path: &str) {
		self.0.set("upload_texture", path);
	}

	/// Download a texture to a file path.
	pub fn download_texture(&mut self, path: &str, texture: u32, format: DownloadFormat) {
		self.0.set(
			"download_texture",
			format!(
				"{texture},{};{path}",
				format.to_raw(&mut Default::default())
			),
		);
	}

	/// Grab the unprocessed camera feed as a texture.
	///
	/// The texture will be given in a [CommandGrabbed].
	pub fn grab_camera(&mut self) {
		self.0.set("grab_camera", "");
	}

	/// Grab the camera feed after processing through all camera shaders as a texture.
	///
	/// The texture will be given in a [CommandGrabbed].
	pub fn grab_processed(&mut self) {
		self.0.set("grab_processed", "");
	}

	/// Release a texture previously provided by [CommandGrabbed].
	///
	/// These will not actually be released until the frame is done rendering,
	/// so it’s okay to still use the textures one last time in shaders for this frame.
	///
	/// If `texture` is 0, this does nothing.
	pub fn release(&mut self, texture: u32) {
		if texture == 0 {
			return;
		}
		use std::collections::hash_map::Entry;
		match self.0.response.entry("release".into()) {
			Entry::Vacant(v) => {
				v.insert(format!("{texture}"));
			}
			Entry::Occupied(mut o) => {
				o.get_mut().push_str(&format!(",{texture}"));
			}
		}
	}

	/// x position of mouse relative to the top-left of the window.
	pub fn window_mouse_x(&self) -> u32 {
		self.0.get_required_u32("window_mouse_x")
	}

	/// y position of mouse relative to the top-left of the window.
	pub fn window_mouse_y(&self) -> u32 {
		self.0.get_required_u32("window_mouse_y")
	}

	/// x position of mouse relative to the top-left of the displayed camera feed.
	pub fn picture_mouse_x(&self) -> i32 {
		self.0.get_required_i32("picture_mouse_x")
	}

	/// y position of mouse relative to the top-left of the displayed camera feed.
	pub fn picture_mouse_y(&self) -> i32 {
		self.0.get_required_i32("picture_mouse_y")
	}

	/// Amount of time left for photo countdown timer.
	pub fn timer(&self) -> Option<Duration> {
		Some(Duration::from_secs_f64(self.0.get("timer")?.parse().ok()?))
	}

	/// Cancel photo countdown timer.
	pub fn cancel_timer(&mut self) {
		self.0.set("cancel_timer", "");
	}
}

/// `_grabbed` command — sent when a texture is “grabbed”
///
/// Note that you may get the same texture twice from this command.
/// For example, if there are no camera shaders, then the “unprocessed”
/// frame is the same as the “processed” frame, so the same texture
/// will be given for both. So make sure you don’t end up releasing the same texture twice.
#[derive(Debug)]
pub struct CommandGrabbed(Command);

/// Source of a texture for [CommandGrabbed].
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum TextureSource {
	/// Texture from [CommandFrame::grab_camera].
	Camera,
	/// Texture from [CommandFrame::grab_processed].
	Processed,
	/// Texture from [CommandFrame::upload_texture].
	Upload,
	/// Texture from [CommandFrame::render_text].
	Text,
	/// Texture from a future camlet feature.
	Other,
}

impl CommandGrabbed {
	/// The OpenGL texture object.
	pub fn texture(&self) -> u32 {
		self.0.get_required_u32("texture")
	}

	/// The source of this texture. See [TextureSource] for more details.
	pub fn source(&self) -> TextureSource {
		match self.0.get_required("source") {
			"camera" => TextureSource::Camera,
			"processed" => TextureSource::Processed,
			"upload" => TextureSource::Upload,
			"text" => TextureSource::Text,
			_ => TextureSource::Other,
		}
	}

	/// Dimensions of the text, as a [Vec] of (*x*, *y*, *width*, *height*) in 0-1 texture coordinates.
	///
	/// There is one entry for each (newline-separated) line of text passed to [CommandFrame::render_text].
	///
	/// If [Self::source()] is not [TextureSource::Text] then this will return an empty [Vec].
	pub fn text_dimensions(&self) -> Vec<(f32, f32, f32, f32)> {
		let Some(raw) = self.0.get("text_dimensions") else {
			assert_ne!(
				self.source(),
				TextureSource::Text,
				"text_dimensions should always be passed for source = text."
			);
			return vec![];
		};
		let mut dimensions = vec![];
		for line in raw.split('\n') {
			let mut dim = [0.0f32; 4];
			let mut dim_iter = dim.iter_mut();
			for part in line.split(',') {
				let d = dim_iter.next().expect(
					"Each line of text_dimensions should only have 4 comma-separated parts.",
				);
				*d = part
					.parse()
					.expect("text_dimensions should consist of floats.");
			}
			assert!(
				dim_iter.next().is_none(),
				"Each line of text_dimensions should have exactly 4 comma-separated parts."
			);
			let [x, y, width, height] = dim;
			dimensions.push((x, y, width, height));
		}
		dimensions
	}
}

/// `_mouse_down` command — Sent whenever a mouse button is pressed.
#[derive(Debug)]
pub struct CommandMouseDown(Command);

impl CommandMouseDown {
	/// x position of the mouse relative to window (0 = left)
	pub fn window_x(&self) -> u32 {
		self.0.get_required_u32("window_x")
	}

	/// y position of the mouse relative to window (0 = top)
	pub fn window_y(&self) -> u32 {
		self.0.get_required_u32("window_y")
	}

	/// x position of the mouse relative to displayed camera feed (0 = left)
	pub fn picture_x(&self) -> i32 {
		self.0.get_required_i32("picture_x")
	}

	/// y position of the mouse relative to displayed camera feed (0 = top)
	pub fn picture_y(&self) -> i32 {
		self.0.get_required_i32("picture_y")
	}

	/// Mouse button that was pressed
	///
	/// Currently the buttons are 'L' for Left, 'M' for Middle, 'R' for Right,
	/// 'X' for X1, and 'Y' for X2.
	pub fn button(&self) -> char {
		self.0
			.get_required("button")
			.chars()
			.next()
			.expect("button must be exactly 1 character.")
	}

	/// Number of clicks of the mouse button
	///
	/// 1 = single click, 2 = double click, etc.
	pub fn clicks(&self) -> u32 {
		self.0.get_required_u32("clicks")
	}
}

/// `_mouse_up` command — Sent whenever a mouse button is released.
#[derive(Debug)]
pub struct CommandMouseUp(Command);

impl CommandMouseUp {
	/// x position of the mouse relative to window (0 = left)
	pub fn window_x(&self) -> u32 {
		self.0.get_required_u32("window_x")
	}

	/// y position of the mouse relative to window (0 = top)
	pub fn window_y(&self) -> u32 {
		self.0.get_required_u32("window_y")
	}

	/// x position of the mouse relative to displayed camera feed (0 = left)
	pub fn picture_x(&self) -> i32 {
		self.0.get_required_i32("picture_x")
	}

	/// y position of the mouse relative to displayed camera feed (0 = top)
	pub fn picture_y(&self) -> i32 {
		self.0.get_required_i32("picture_y")
	}

	/// Mouse button that was released
	///
	/// Currently the buttons are 'L' for Left, 'M' for Middle, 'R' for Right,
	/// 'X' for X1, and 'Y' for X2.
	pub fn button(&self) -> char {
		self.0
			.get_required("button")
			.chars()
			.next()
			.expect("button must be exactly 1 character.")
	}
}

/// `_mouse_scroll` command — Sent whenever the mouse is scrolled.
#[derive(Debug)]
pub struct CommandMouseScroll(Command);
impl CommandMouseScroll {
	/// Logical horizontal scrolling amount.
	///
	/// For "natural"/"flipped" scrolling this is the negative of [Self::physical_x],
	/// otherwise it is equal to [Self::physical_x].
	pub fn logical_x(&self) -> i32 {
		self.0.get_required_i32("logical_x")
	}

	/// Logical vertical scrolling amount.
	///
	/// For "natural"/"flipped" scrolling this is the negative of [Self::physical_y],
	/// otherwise it is equal to [Self::physical_y].
	pub fn logical_y(&self) -> i32 {
		self.0.get_required_i32("logical_y")
	}

	/// Physical horizontal scrolling amount (negative = leftwards, positive = rightwards).
	pub fn physical_x(&self) -> i32 {
		self.0.get_required_i32("physical_x")
	}

	/// Physical vertical scrolling amount (negative = upwards, positive = downwards).
	pub fn physical_y(&self) -> i32 {
		self.0.get_required_i32("physical_y")
	}

	/// x position of the mouse relative to window (0 = left)
	pub fn window_x(&self) -> u32 {
		self.0.get_required_u32("window_x")
	}

	/// y position of the mouse relative to window (0 = top)
	pub fn window_y(&self) -> u32 {
		self.0.get_required_u32("window_y")
	}

	/// x position of the mouse relative to displayed camera feed (0 = left)
	pub fn picture_x(&self) -> i32 {
		self.0.get_required_i32("picture_x")
	}

	/// y position of the mouse relative to displayed camera feed (0 = top)
	pub fn picture_y(&self) -> i32 {
		self.0.get_required_i32("picture_y")
	}
}

/// `_setting` command — sent when a setting value is set/changed.
///
/// This is sent once for each setting upon initialization, then
/// again whenever the user changes a setting.
#[derive(Debug)]
pub struct CommandSetting(Command);

impl CommandSetting {
	/// Identifier of the setting that was changed.
	pub fn id(&self) -> &str {
		self.0.get_required("id")
	}

	/// New value for the setting.
	pub fn value(&self) -> &str {
		self.0.get_required("value")
	}

	/// If true, this is the last setting.
	///
	/// This is only ever true during initialization,
	/// not when the user changes a setting through the menu.
	pub fn done(&self) -> bool {
		self.0.has("done")
	}
}

/// `photo` command — sent when a photo is about to be taken.
#[derive(Debug)]
pub struct CommandPhoto(Command);

/// File format for photo
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum PhotoFormat {
	/// PNG file
	Png,
	/// JPG file
	Jpeg {
		/// JPEG quality, from 1 to 100
		quality: u8,
	},
	/// A photo format added to camlet in the future.
	Other,
}

impl CommandPhoto {
	/// The path where the image will be saved if the photo is taken.
	pub fn path(&self) -> &str {
		self.0.get_required("path")
	}

	/// File format of the photo that will be taken.
	pub fn format(&self) -> PhotoFormat {
		match self.0.get_required("format") {
			"png" => PhotoFormat::Png,
			"jpg" => PhotoFormat::Jpeg {
				quality: self
					.0
					.get_required_u32("quality")
					.try_into()
					.expect("quality should fit in u8"),
			},
			_ => PhotoFormat::Other,
		}
	}

	/// Width of the image file that will be saved, in pixels.
	pub fn width(&self) -> u32 {
		self.0.get_required_u32("width")
	}

	/// Height of the image file that will be saved, in pixels.
	pub fn height(&self) -> u32 {
		self.0.get_required_u32("height")
	}

	/// Cancel the photo from being taken.
	pub fn cancel(&mut self) {
		self.0.set("cancel", "");
	}

	/// If called, no flash will be displayed.
	pub fn disable_flash(&mut self) {
		self.0.set("no_flash", "");
	}

	/// Set camera shader that will be used for the photo and subsequent frames.
	///
	/// If you want to apply this just for the photo, be sure to set it back to its old value
	/// with [CommandFrame::set_camera_shader].
	pub fn set_camera_shader(&mut self, shader: Shader) {
		self.0.set_shader("camera", shader);
	}

	/// Remove camera shader for the photo and subsequent frames.
	///
	/// If you want to go back to having a shader again after the photo,
	/// be sure to set it back to its old value with [CommandFrame::set_camera_shader].
	pub fn clear_camera_shader(&mut self) {
		self.0.clear_shader("camera");
	}
}

/// `_photo_ok` command — Sent when a photo is saved to disk.
#[derive(Debug)]
#[allow(dead_code)]
pub struct CommandPhotoOk(Command);

/// `_photo_error` command — Sent when a photo fails to be taken.
///
/// This may be due to [CommandPhoto::cancel] being called, either by this or another plug-in,
/// or due to an I/O error, etc.
#[derive(Debug)]
#[allow(dead_code)]
pub struct CommandPhotoError(Command);

/// `video_start` command — Sent when a video recording is about to start.
#[derive(Debug)]
pub struct CommandVideoStart(Command);

impl CommandVideoStart {
	/// The path where the video will be saved.
	pub fn path(&self) -> &str {
		self.0.get_required("path")
	}

	/// Width of the video file that will be created, in pixels.
	pub fn width(&self) -> u32 {
		self.0.get_required_u32("width")
	}

	/// Height of the video file that will be created, in pixels.
	pub fn height(&self) -> u32 {
		self.0.get_required_u32("height")
	}

	/// The framerate of the video, in frames per second.
	pub fn framerate(&self) -> f64 {
		self.0.get_required_f64("framerate")
	}

	/// If called, the video recording will be cancelled.
	pub fn cancel(&mut self) {
		self.0.set("cancel", "");
	}
}

/// `_video_started` command — Sent when a video recording is started.
#[derive(Debug)]
#[allow(dead_code)]
pub struct CommandVideoStarted(Command);

/// `_video_stop` command — Sent when a video recording is stopped.
#[derive(Debug)]
#[allow(dead_code)]
pub struct CommandVideoStop(Command);

/// A camlet plug-in
#[allow(unused_variables)]
pub trait Plugin {
	/// Called to initialize the plug-in.
	fn init(command: &mut CommandInit) -> std::result::Result<Self, Box<dyn std::error::Error>>
	where
		Self: Sized;
	/// Called when a [CommandSetting] is sent to the plug-in.
	fn setting(&mut self, command: &mut CommandSetting) {}
	/// Called when a [CommandQuit] is sent to the plug-in.
	fn quit(&mut self, command: &mut CommandQuit) {}
	/// Called when a [CommandKeyDown] is sent to the plug-in.
	fn key_down(&mut self, command: &mut CommandKeyDown) {}
	/// Called when a [CommandKeyUp] is sent to the plug-in.
	fn key_up(&mut self, command: &mut CommandKeyUp) {}
	/// Called when a [CommandCameraConnected] is sent to the plug-in.
	fn camera_connected(&mut self, command: &mut CommandCameraConnected) {}
	/// Called when a [CommandCameraDisconnected] is sent to the plug-in.
	fn camera_disconnected(&mut self, command: &mut CommandCameraDisconnected) {}
	/// Called when a [CommandFrame] is sent to the plug-in.
	fn frame(&mut self, command: &mut CommandFrame) {}
	/// Called when a [CommandGrabbed] is sent to the plug-in.
	fn grabbed(&mut self, command: &mut CommandGrabbed) {}
	/// Called when a [CommandMouseDown] is sent to the plug-in.
	fn mouse_down(&mut self, command: &mut CommandMouseDown) {}
	/// Called when a [CommandMouseUp] is sent to the plug-in.
	fn mouse_up(&mut self, command: &mut CommandMouseUp) {}
	/// Called when a [CommandMouseScroll] is sent to the plug-in.
	fn mouse_scroll(&mut self, command: &mut CommandMouseScroll) {}
	/// Called when a [CommandPhoto] is sent to the plug-in.
	fn photo(&mut self, command: &mut CommandPhoto) {}
	/// Called when a [CommandPhotoOk] is sent to the plug-in.
	fn photo_ok(&mut self, command: &mut CommandPhotoOk) {}
	/// Called when a [CommandPhotoError] is sent to the plug-in.
	fn photo_error(&mut self, command: &mut CommandPhotoError) {}
	/// Called when a [CommandVideoStart] is sent to the plug-in.
	fn video_start(&mut self, command: &mut CommandVideoStart) {}
	/// Called when a [CommandVideoStarted] is sent to the plug-in.
	fn video_started(&mut self, command: &mut CommandVideoStarted) {}
	/// Called when a [CommandVideoStop] is sent to the plug-in.
	fn video_stop(&mut self, command: &mut CommandVideoStop) {}
	/// Called whenever any command is sent to camlet.
	///
	/// Use at your own risk - prefer the more specific methods.
	/// If you use this you **must** check the result of [CommandInit::version_major]
	/// and [CommandInit::version_minor] yourself, since this library might be updated
	/// without a major version change to handle new major camlet versions.
	/// Note that if there is a specific method for a command, this will still be called
	/// after it.
	fn command(&mut self, command: &mut Command) {}
}

fn handle_specific_command(plugin: &mut dyn Plugin, command: Command) -> Command {
	macro_rules! handle {
		($method:ident, $type:ident) => {{
			let mut specific = $type(command);
			// Catch it if we forget to #[derive(Debug)] for a command type
			let _: &dyn fmt::Debug = &specific;
			plugin.$method(&mut specific);
			return specific.0;
		}};
	}
	match command.name.as_str() {
		"_camera_connected" => handle!(camera_connected, CommandCameraConnected),
		"_camera_disconnected" => handle!(camera_disconnected, CommandCameraDisconnected),
		"frame" => handle!(frame, CommandFrame),
		"_grabbed" => handle!(grabbed, CommandGrabbed),
		"_key_down" => handle!(key_down, CommandKeyDown),
		"_key_up" => handle!(key_up, CommandKeyUp),
		"_mouse_down" => handle!(mouse_down, CommandMouseDown),
		"_mouse_scroll" => handle!(mouse_scroll, CommandMouseScroll),
		"_mouse_up" => handle!(mouse_up, CommandMouseUp),
		"photo" => handle!(photo, CommandPhoto),
		"_photo_error" => handle!(photo_error, CommandPhotoError),
		"_photo_ok" => handle!(photo_ok, CommandPhotoOk),
		"_quit" => handle!(quit, CommandQuit),
		"_setting" => handle!(setting, CommandSetting),
		"video_start" => handle!(video_start, CommandVideoStart),
		"_video_started" => handle!(video_started, CommandVideoStarted),
		"_video_stop" => handle!(video_stop, CommandVideoStop),
		_ => (),
	}
	command
}

fn receive_command(socket: &mut Socket) -> Result<Command> {
	let mut name = String::new();
	socket.read_line(&mut name)?;
	if name.ends_with('\n') {
		name.pop();
	}
	let mut line = String::new();
	let mut first_line_of_argument_value = false;
	let mut arguments = HashMap::new();
	let mut argument_name = String::new();
	let mut argument_value = String::new();
	loop {
		line.clear();
		socket.read_line(&mut line)?;
		if line.ends_with('\n') {
			line.pop();
		}
		if line.is_empty() {
			break;
		}
		if let Some(line) = line.strip_prefix('>') {
			if !first_line_of_argument_value {
				argument_value.push('\n');
			}
			first_line_of_argument_value = false;
			argument_value.push_str(line);
		} else if let Some(arg) = line.strip_suffix(':') {
			if arg.is_empty() {
				Err(IError::InvalidLineFormat(line.clone().into()))?
			}
			if !argument_name.is_empty() {
				arguments.insert(argument_name, take(&mut argument_value));
			}
			first_line_of_argument_value = true;
			argument_name = arg.into();
		} else {
			Err(IError::InvalidLineFormat(line.clone().into()))?
		}
	}
	if !argument_name.is_empty() {
		arguments.insert(argument_name, argument_value);
	}
	Ok(Command {
		name,
		arguments,
		response: Default::default(),
	})
}

fn run_with_plugin(plugin: &mut dyn Plugin, socket: &mut BufReader<File>) -> Result<()> {
	loop {
		let mut command = receive_command(socket)?;
		plugin.command(&mut command);
		let command = handle_specific_command(plugin, command);
		if !command.name.starts_with('_') {
			command.respond(socket.get_mut())?;
		}
		if command.name == "_quit" {
			break;
		}
	}
	Ok(())
}

/// Run a plug-in, returning a result for custom error handling.
pub fn try_run<P: Plugin>() -> Result<()> {
	let file = unsafe { std::fs::File::from_raw_fd(3) };
	let mut socket = BufReader::new(file);
	let command = receive_command(&mut socket)?;
	if command.name != "init" {
		Err(IError::NoInit)?;
	}
	let mut command_init = CommandInit(command);
	let vmajor = command_init.version_major();
	if vmajor != 1 {
		Err(IError::CantHandleVersion(vmajor))?;
	}
	let mut plugin = match P::init(&mut command_init) {
		Ok(plugin) => plugin,
		Err(e) => {
			command_init.0.set("error", format!("{e}"));
			return command_init.0.respond(socket.get_mut());
		}
	};
	command_init.0.set("ok", "");
	command_init.0.respond(socket.get_mut())?;
	run_with_plugin(&mut plugin, &mut socket)
}

/// Run a plug-in, printing errors to standard error, and returning an [ExitCode] which you can return from main.
pub fn run<P: Plugin>() -> ExitCode {
	match try_run::<P>() {
		Err(e) => {
			eprintln!("Error: {e}");
			ExitCode::FAILURE
		}
		Ok(()) => ExitCode::SUCCESS,
	}
}