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
mod dest_info;
mod media_size;
mod printer_state;
pub use dest_info::DestinationInfo;
pub use media_size::MediaSize;
pub use printer_state::PrinterState;
use crate::bindings;
use crate::constants;
use crate::error::{Error, Result};
use crate::error_helpers::cups_error_to_our_error;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::os::raw::{c_int, c_uint, c_void};
use std::ptr;
pub type DestCallback<T> = dyn FnMut(u32, &Destination, &mut T) -> bool;
/// Represents a printer or class of printers available for printing
#[derive(Debug, Clone)]
pub struct Destination {
/// Name of the destination
pub name: String,
/// Instance name or None for the default instance
pub instance: Option<String>,
/// True if this is the default destination
pub is_default: bool,
/// Options and attributes for this destination
pub options: HashMap<String, String>,
}
impl Destination {
/// Create a new Destination instance from raw cups_dest_t pointer
pub(crate) unsafe fn from_raw(dest_ptr: *const bindings::cups_dest_s) -> Result<Self> {
if dest_ptr.is_null() {
return Err(Error::NullPointer);
}
let dest = unsafe { &*dest_ptr };
// Extract name
let name = if dest.name.is_null() {
return Err(Error::NullPointer);
} else {
unsafe { CStr::from_ptr(dest.name) }
.to_string_lossy()
.into_owned()
};
// Extract instance (if any)
let instance = if dest.instance.is_null() {
None
} else {
Some(
unsafe { CStr::from_ptr(dest.instance) }
.to_string_lossy()
.into_owned(),
)
};
// Extract options
let mut options = HashMap::new();
if !dest.options.is_null() && dest.num_options > 0 {
for i in 0..dest.num_options {
unsafe {
let option = &*(dest.options.offset(i as isize));
if !option.name.is_null() && !option.value.is_null() {
let name = CStr::from_ptr(option.name).to_string_lossy().into_owned();
let value = CStr::from_ptr(option.value).to_string_lossy().into_owned();
options.insert(name, value);
}
}
}
}
Ok(Destination {
name,
instance,
is_default: dest.is_default != 0,
options,
})
}
/// Get the state of this destination
pub fn state(&self) -> PrinterState {
match self.options.get("printer-state") {
Some(state) => PrinterState::from_cups_state(state),
None => PrinterState::Unknown,
}
}
/// Get the reasons for the current state
pub fn state_reasons(&self) -> Vec<String> {
match self.options.get("printer-state-reasons") {
Some(reasons) => reasons.split(',').map(|s| s.trim().to_string()).collect(),
None => Vec::new(),
}
}
/// Get a human-readable description of this destination
pub fn info(&self) -> Option<&String> {
self.options.get("printer-info")
}
/// Get the location of this destination
pub fn location(&self) -> Option<&String> {
self.options.get("printer-location")
}
/// Get the make and model of this destination
pub fn make_and_model(&self) -> Option<&String> {
self.options.get("printer-make-and-model")
}
/// Check if the destination is accepting jobs
pub fn is_accepting_jobs(&self) -> bool {
match self.options.get("printer-is-accepting-jobs") {
Some(value) => value == "true",
None => false,
}
}
/// Get the URI associated with this destination
pub fn uri(&self) -> Option<&String> {
self.options.get("printer-uri-supported")
}
/// Get the device URI for this destination
pub fn device_uri(&self) -> Option<&String> {
self.options.get("device-uri")
}
/// Get the full name of this destination (including instance if any)
pub fn full_name(&self) -> String {
match &self.instance {
Some(inst) => format!("{}/{}", self.name, inst),
None => self.name.clone(),
}
}
/// Get an option value by name
pub fn get_option(&self, name: &str) -> Option<&String> {
self.options.get(name)
}
/// Check if an option is present
pub fn has_option(&self, name: &str) -> bool {
self.options.contains_key(name)
}
/// Get all options
pub fn get_options(&self) -> &HashMap<String, String> {
&self.options
}
/// Get detailed information about this destination
pub fn get_detailed_info(&self, http: *mut bindings::_http_s) -> Result<DestinationInfo> {
let name_c = CString::new(self.name.as_str())?;
let instance_c = match &self.instance {
Some(instance) => Some(CString::new(instance.as_str())?),
None => None,
};
let _instance_ptr = match &instance_c {
Some(s) => s.as_ptr(),
None => ptr::null(),
};
let mut num_options = 0;
let mut options_ptr: *mut bindings::cups_option_s = ptr::null_mut();
for (name, value) in &self.options {
let name_c = CString::new(name.as_str())?;
let value_c = CString::new(value.as_str())?;
unsafe {
num_options = bindings::cupsAddOption(
name_c.as_ptr(),
value_c.as_ptr(),
num_options,
&mut options_ptr,
);
}
}
let dest = bindings::cups_dest_s {
name: name_c.into_raw(),
instance: match instance_c {
Some(s) => s.into_raw(),
None => ptr::null_mut(),
},
is_default: if self.is_default { 1 } else { 0 },
num_options,
options: options_ptr,
};
let dinfo = unsafe {
bindings::cupsCopyDestInfo(
http,
&dest as *const bindings::cups_dest_s as *mut bindings::cups_dest_s,
)
};
unsafe {
if !options_ptr.is_null() {
bindings::cupsFreeOptions(num_options, options_ptr);
}
if !dest.name.is_null() {
let _ = CString::from_raw(dest.name);
}
if !dest.instance.is_null() {
let _ = CString::from_raw(dest.instance);
}
}
if dinfo.is_null() {
return Err(cups_error_to_our_error(
"get destination info",
Some(&self.name),
));
}
unsafe { DestinationInfo::from_raw(dinfo) }
}
/// Check if a specific option and value is supported by this destination
pub fn is_option_supported(&self, http: *mut bindings::_http_s, option: &str) -> bool {
match self.get_detailed_info(http) {
Ok(info) => {
// Create a raw cups_dest_t for this destination
let name_c = match CString::new(self.name.as_str()) {
Ok(s) => s,
Err(_) => return false,
};
let instance_c = match &self.instance {
Some(instance) => match CString::new(instance.as_str()) {
Ok(s) => Some(s),
Err(_) => return false,
},
None => None,
};
let _instance_ptr = match &instance_c {
Some(s) => s.as_ptr(),
None => ptr::null(),
};
let mut num_options = 0;
let mut options_ptr: *mut bindings::cups_option_s = ptr::null_mut();
// Add all options
for (name, value) in &self.options {
let name_c = match CString::new(name.as_str()) {
Ok(s) => s,
Err(_) => continue,
};
let value_c = match CString::new(value.as_str()) {
Ok(s) => s,
Err(_) => continue,
};
unsafe {
num_options = bindings::cupsAddOption(
name_c.as_ptr(),
value_c.as_ptr(),
num_options,
&mut options_ptr,
);
}
}
let dest = bindings::cups_dest_s {
name: name_c.into_raw(),
instance: match instance_c {
Some(s) => s.into_raw(),
None => ptr::null_mut(),
},
is_default: if self.is_default { 1 } else { 0 },
num_options,
options: options_ptr,
};
// Check if the option is supported
let result = info.is_option_supported(
http,
&dest as *const bindings::cups_dest_s as *mut bindings::cups_dest_s,
option,
);
// Free the resources
unsafe {
if !options_ptr.is_null() {
bindings::cupsFreeOptions(num_options, options_ptr);
}
// Need to free the raw strings we created
if !dest.name.is_null() {
let _ = CString::from_raw(dest.name);
}
if !dest.instance.is_null() {
let _ = CString::from_raw(dest.instance);
}
}
result
}
Err(_) => false,
}
}
/// Get a pointer to a raw cups_dest_s for this destination
pub fn as_ptr(&self) -> *mut bindings::cups_dest_s {
// Create a raw cups_dest_t for this destination
let name_c = match CString::new(self.name.as_str()) {
Ok(s) => s,
Err(_) => return ptr::null_mut(),
};
let instance_c = match &self.instance {
Some(instance) => match CString::new(instance.as_str()) {
Ok(s) => Some(s),
Err(_) => return ptr::null_mut(),
},
None => None,
};
let _instance_ptr = match &instance_c {
Some(s) => s.as_ptr(),
None => ptr::null(),
};
let mut num_options = 0;
let mut options_ptr: *mut bindings::cups_option_s = ptr::null_mut();
// Add all options
for (name, value) in &self.options {
let name_c = match CString::new(name.as_str()) {
Ok(s) => s,
Err(_) => continue,
};
let value_c = match CString::new(value.as_str()) {
Ok(s) => s,
Err(_) => continue,
};
unsafe {
num_options = bindings::cupsAddOption(
name_c.as_ptr(),
value_c.as_ptr(),
num_options,
&mut options_ptr,
);
}
}
// Create the raw cups_dest_s struct
let dest = Box::new(bindings::cups_dest_s {
name: name_c.into_raw(),
instance: match instance_c {
Some(s) => s.into_raw(),
None => ptr::null_mut(),
},
is_default: if self.is_default { 1 } else { 0 },
num_options,
options: options_ptr,
});
// Leak the box to keep the memory alive
Box::into_raw(dest)
}
}
/// A collection of CUPS destinations with automatic cleanup
pub struct Destinations {
dests: *mut bindings::cups_dest_s,
num_dests: c_int,
_marker: PhantomData<bindings::cups_dest_s>,
}
impl Destinations {
/// Create a new empty destinations list
pub fn new() -> Self {
Destinations {
dests: ptr::null_mut(),
num_dests: 0,
_marker: PhantomData,
}
}
/// Get all available destinations from the default CUPS server
pub fn get_all() -> Result<Self> {
let mut dests: *mut bindings::cups_dest_s = ptr::null_mut();
let num_dests = unsafe { bindings::cupsGetDests(&mut dests) };
if num_dests <= 0 || dests.is_null() {
return Err(Error::DestinationListFailed);
}
Ok(Destinations {
dests,
num_dests,
_marker: PhantomData,
})
}
/// Get a specific destination by name
pub fn get_destination<S: AsRef<str>>(name: S) -> Result<Destination> {
// Get all destinations first
let all_dests = Self::get_all()?;
// Find the specific destination
let name_c = CString::new(name.as_ref())?;
let dest_ptr = unsafe {
bindings::cupsGetDest(
name_c.as_ptr(),
ptr::null(),
all_dests.num_dests,
all_dests.dests,
)
};
if dest_ptr.is_null() {
return Err(Error::DestinationNotFound(name.as_ref().to_string()));
}
// Convert to our Destination type
unsafe { Destination::from_raw(dest_ptr) }
}
/// Get the default destination
pub fn get_default() -> Result<Destination> {
// Get all destinations first
let all_dests = Self::get_all()?;
for i in 0..all_dests.num_dests as isize {
unsafe {
let dest = &*(all_dests.dests.offset(i));
if dest.is_default != 0 {
return Destination::from_raw(all_dests.dests.offset(i));
}
}
}
Err(Error::DestinationNotFound("Default printer".to_string()))
}
/// Convert to a Vec of Destination objects
pub fn to_vec(&self) -> Result<Vec<Destination>> {
let mut destinations = Vec::with_capacity(self.num_dests as usize);
for i in 0..self.num_dests as isize {
unsafe {
match Destination::from_raw(self.dests.offset(i)) {
Ok(dest) => destinations.push(dest),
Err(e) => {
eprintln!("Warning: Failed to parse destination at index {}: {}", i, e)
}
}
}
}
Ok(destinations)
}
/// Get the number of destinations
pub fn len(&self) -> usize {
self.num_dests as usize
}
/// Check if there are no destinations
pub fn is_empty(&self) -> bool {
self.num_dests == 0
}
/// Get raw pointer to destinations array (for advanced usage)
pub fn as_ptr(&self) -> *mut bindings::cups_dest_s {
self.dests
}
/// Get number of destinations
pub fn count(&self) -> c_int {
self.num_dests
}
/// Add a destination to the list of destinations
///
/// If the named destination already exists, the destination list is returned unchanged.
/// Adding a new instance of a destination creates a copy of that destination's options.
///
/// # Arguments
/// - `name`: Destination name
/// - `instance`: Instance name or None for none/primary
///
/// # Returns
/// - `Ok(())`: Destination added successfully
/// - `Err(Error)`: Failed to add destination
pub fn add_destination(&mut self, name: &str, instance: Option<&str>) -> Result<()> {
let name_c = CString::new(name)?;
let instance_c = instance.map(|i| CString::new(i)).transpose()?;
let instance_ptr = instance_c.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
let new_num_dests = unsafe {
bindings::cupsAddDest(
name_c.as_ptr(),
instance_ptr,
self.num_dests,
&mut self.dests,
)
};
if new_num_dests > self.num_dests {
self.num_dests = new_num_dests;
Ok(())
} else {
// Destination already exists or error occurred
Ok(()) // CUPS API treats existing destinations as success
}
}
/// Remove a destination from the destination list
///
/// Removing a destination/instance does not delete the class or printer queue,
/// merely the lpoptions for that destination/instance.
///
/// # Arguments
/// - `name`: Destination name
/// - `instance`: Instance name or None
///
/// # Returns
/// - `Ok(true)`: Destination was found and removed
/// - `Ok(false)`: Destination was not found
/// - `Err(Error)`: Failed to remove destination
pub fn remove_destination(&mut self, name: &str, instance: Option<&str>) -> Result<bool> {
let name_c = CString::new(name)?;
let instance_c = instance.map(|i| CString::new(i)).transpose()?;
let instance_ptr = instance_c.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
let old_count = self.num_dests;
let new_num_dests = unsafe {
bindings::cupsRemoveDest(
name_c.as_ptr(),
instance_ptr,
self.num_dests,
&mut self.dests,
)
};
self.num_dests = new_num_dests;
Ok(new_num_dests < old_count)
}
/// Set the default destination
///
/// This marks one of the destinations in the list as the default destination.
///
/// # Arguments
/// - `name`: Destination name
/// - `instance`: Instance name or None
///
/// # Returns
/// - `Ok(())`: Default destination set successfully
/// - `Err(Error)`: Failed to set default destination
pub fn set_default_destination(&mut self, name: &str, instance: Option<&str>) -> Result<()> {
let name_c = CString::new(name)?;
let instance_c = instance.map(|i| CString::new(i)).transpose()?;
let instance_ptr = instance_c.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
unsafe {
bindings::cupsSetDefaultDest(
name_c.as_ptr(),
instance_ptr,
self.num_dests,
self.dests,
);
}
Ok(())
}
/// Save the list of destinations to the user's lpoptions file
///
/// This saves the current destination list and their options to the user's
/// lpoptions file for persistence across sessions.
///
/// # Returns
/// - `Ok(())`: Destinations saved successfully
/// - `Err(Error)`: Failed to save destinations
pub fn save_to_lpoptions(&self) -> Result<()> {
let result = unsafe {
bindings::cupsSetDests2(
ptr::null_mut(), // Use CUPS_HTTP_DEFAULT
self.num_dests,
self.dests,
)
};
if result == 0 {
Ok(())
} else {
Err(Error::ConfigurationError(
"Failed to save destinations to lpoptions".to_string(),
))
}
}
/// Find a destination by name and instance
///
/// # Arguments
/// - `name`: Destination name to search for
/// - `instance`: Instance name or None
///
/// # Returns
/// - `Some(Destination)`: Found destination
/// - `None`: Destination not found
pub fn find_destination(&self, name: &str, instance: Option<&str>) -> Option<Destination> {
let name_c = match CString::new(name) {
Ok(n) => n,
Err(_) => return None,
};
let instance_c = instance.and_then(|i| CString::new(i).ok());
let instance_ptr = instance_c.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
let dest_ptr = unsafe {
bindings::cupsGetDest(
name_c.as_ptr(),
instance_ptr,
self.num_dests,
self.dests,
)
};
if dest_ptr.is_null() {
None
} else {
unsafe { Destination::from_raw(dest_ptr).ok() }
}
}
}
/// Represents option conflicts and their resolutions
#[derive(Debug, Clone)]
pub struct OptionConflict {
/// The conflicting option/value pairs
pub conflicting_options: Vec<(String, String)>,
/// The resolved option/value pairs to fix conflicts
pub resolved_options: Vec<(String, String)>,
}
impl DestinationInfo {
/// Check for option conflicts and get resolutions for a new option/value pair
///
/// This function checks if adding a new option/value pair would conflict
/// with existing options and provides resolutions if conflicts are found.
///
/// # Arguments
/// - `current_options`: Current option/value pairs
/// - `new_option`: The new option name to check
/// - `new_value`: The new option value to check
///
/// # Returns
/// - `Ok(None)`: No conflicts found
/// - `Ok(Some(OptionConflict))`: Conflicts found with resolution
/// - `Err(Error)`: Error checking conflicts or unresolvable conflict
pub fn check_option_conflicts(
&self,
dest: &Destination,
current_options: &[(String, String)],
new_option: &str,
new_value: &str,
) -> Result<Option<OptionConflict>> {
// Convert current options to CUPS format
let mut cups_options_ptr: *mut bindings::cups_option_s = ptr::null_mut();
let mut num_options = 0;
for (name, value) in current_options {
let name_c = CString::new(name.as_str())?;
let value_c = CString::new(value.as_str())?;
unsafe {
num_options = bindings::cupsAddOption(
name_c.as_ptr(),
value_c.as_ptr(),
num_options,
&mut cups_options_ptr,
);
}
}
let new_option_c = CString::new(new_option)?;
let new_value_c = CString::new(new_value)?;
// Get destination pointer (we need to create one temporarily)
let dest_name_c = CString::new(dest.name.as_str())?;
let dest_instance_c = dest.instance.as_ref().map(|i| CString::new(i.as_str())).transpose()?;
let dest_instance_ptr = dest_instance_c.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null());
let dest_ptr = unsafe {
bindings::cupsGetDest(
dest_name_c.as_ptr(),
dest_instance_ptr,
1, // We just need a temporary dest
ptr::null_mut(), // Let CUPS find it
)
};
if dest_ptr.is_null() {
unsafe {
if !cups_options_ptr.is_null() {
bindings::cupsFreeOptions(num_options, cups_options_ptr);
}
}
return Err(Error::DestinationNotFound(dest.name.clone()));
}
let mut num_conflicts = 0;
let mut conflicts: *mut bindings::cups_option_s = ptr::null_mut();
let mut num_resolved = 0;
let mut resolved: *mut bindings::cups_option_s = ptr::null_mut();
let conflict_result = unsafe {
bindings::cupsCopyDestConflicts(
ptr::null_mut(), // Use CUPS_HTTP_DEFAULT
dest_ptr,
self.as_ptr(),
num_options,
cups_options_ptr,
new_option_c.as_ptr(),
new_value_c.as_ptr(),
&mut num_conflicts,
&mut conflicts,
&mut num_resolved,
&mut resolved,
)
};
// Clean up temporary options
unsafe {
if !cups_options_ptr.is_null() {
bindings::cupsFreeOptions(num_options, cups_options_ptr);
}
}
let result = match conflict_result {
1 => {
// Conflicts found
let mut conflicting_options = Vec::new();
let mut resolved_options = Vec::new();
// Extract conflicting options
if !conflicts.is_null() && num_conflicts > 0 {
for i in 0..num_conflicts {
unsafe {
let option = &*conflicts.offset(i as isize);
if !option.name.is_null() && !option.value.is_null() {
let name = CStr::from_ptr(option.name).to_string_lossy().into_owned();
let value = CStr::from_ptr(option.value).to_string_lossy().into_owned();
conflicting_options.push((name, value));
}
}
}
}
// Extract resolved options
if !resolved.is_null() && num_resolved > 0 {
for i in 0..num_resolved {
unsafe {
let option = &*resolved.offset(i as isize);
if !option.name.is_null() && !option.value.is_null() {
let name = CStr::from_ptr(option.name).to_string_lossy().into_owned();
let value = CStr::from_ptr(option.value).to_string_lossy().into_owned();
resolved_options.push((name, value));
}
}
}
}
// Clean up CUPS-allocated memory
unsafe {
if !conflicts.is_null() {
bindings::cupsFreeOptions(num_conflicts, conflicts);
}
if !resolved.is_null() {
bindings::cupsFreeOptions(num_resolved, resolved);
}
}
if resolved_options.is_empty() && !conflicting_options.is_empty() {
// Unresolvable conflict
Err(Error::ConfigurationError(format!(
"Unresolvable option conflict: {} = {} conflicts with existing options",
new_option, new_value
)))
} else {
Ok(Some(OptionConflict {
conflicting_options,
resolved_options,
}))
}
}
0 => {
// No conflicts
Ok(None)
}
_ => {
// Error occurred
Err(Error::ConfigurationError(format!(
"Error checking option conflicts for {} = {}",
new_option, new_value
)))
}
};
result
}
}
impl Drop for Destinations {
fn drop(&mut self) {
unsafe {
if !self.dests.is_null() && self.num_dests > 0 {
bindings::cupsFreeDests(self.num_dests, self.dests);
self.dests = ptr::null_mut();
self.num_dests = 0;
}
}
}
}
/// Enumerate available destinations with a callback function
pub fn enum_destinations<T>(
flags: u32,
msec: i32,
cancel: Option<&mut i32>,
type_filter: u32,
mask: u32,
callback: &mut DestCallback<T>,
user_data: &mut T,
) -> Result<bool> {
// We need to create a context that will be passed to the C callback
let mut context = EnumContext {
callback,
user_data,
};
let cancel_ptr = match cancel {
Some(c) => c as *mut c_int,
None => ptr::null_mut(),
};
let result = unsafe {
bindings::cupsEnumDests(
flags,
msec as c_int,
cancel_ptr,
type_filter as c_uint,
mask as c_uint,
Some(enum_dest_callback::<T>),
&mut context as *mut _ as *mut c_void,
)
};
if result == 0 {
Err(Error::EnumerationError(
"Failed to enumerate destinations".to_string(),
))
} else {
Ok(true)
}
}
// Context structure for the C callback
struct EnumContext<'a, T> {
callback: &'a mut DestCallback<T>,
user_data: &'a mut T,
}
// C-compatible callback function that bridges to our Rust callback
unsafe extern "C" fn enum_dest_callback<T>(
user_data: *mut c_void,
flags: c_uint,
dest_ptr: *mut bindings::cups_dest_s,
) -> c_int {
// Reconstruct our context
let context = unsafe { &mut *(user_data as *mut EnumContext<T>) };
// Convert the raw destination to our Rust type
unsafe {
match Destination::from_raw(dest_ptr) {
Ok(dest) => {
// Call the user's callback
if (context.callback)(flags, &dest, context.user_data) {
1 // Continue enumeration
} else {
0 // Stop enumeration
}
}
Err(e) => {
eprintln!("Warning: Failed to parse destination: {}", e);
1 // Continue enumeration despite error
}
}
}
}
/// Get all available printer destinations
pub fn get_all_destinations() -> Result<Vec<Destination>> {
Destinations::get_all()?.to_vec()
}
/// Get a specific destination by name
pub fn get_destination<S: AsRef<str>>(name: S) -> Result<Destination> {
Destinations::get_destination(name)
}
/// Get the default destination
pub fn get_default_destination() -> Result<Destination> {
Destinations::get_default()
}
/// Copy a destination from one destination array to another
pub fn copy_dest(
dest: *const bindings::cups_dest_s,
num_dests: i32,
dests: *mut *mut bindings::cups_dest_s,
) -> i32 {
unsafe { bindings::cupsCopyDest(dest as *mut bindings::cups_dest_s, num_dests, dests) }
}
/// Remove a destination from an array
pub fn remove_dest(
name: &str,
instance: Option<&str>,
num_dests: i32,
dests: *mut *mut bindings::cups_dest_s,
) -> Result<i32> {
let name_c = CString::new(name)?;
let instance_c = match instance {
Some(i) => Some(CString::new(i)?),
None => None,
};
let instance_ptr = match &instance_c {
Some(s) => s.as_ptr(),
None => ptr::null(),
};
let result =
unsafe { bindings::cupsRemoveDest(name_c.as_ptr(), instance_ptr, num_dests, dests) };
Ok(result)
}
/// Find available destinations with specific filter criteria
pub fn find_destinations(type_filter: u32, mask: u32) -> Result<Vec<Destination>> {
let mut destinations = Vec::new();
enum_destinations(
constants::DEST_FLAGS_NONE,
5000, // 5 second timeout
None,
type_filter,
mask,
&mut |flags, dest, dests: &mut Vec<Destination>| {
if (flags & constants::DEST_FLAGS_REMOVED) == 0 {
dests.push(dest.clone());
}
true // Continue enumeration
},
&mut destinations,
)?;
Ok(destinations)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_destination_creation() {
let mut options = std::collections::HashMap::new();
options.insert("printer-state".to_string(), "3".to_string());
options.insert("printer-info".to_string(), "Test Printer".to_string());
options.insert("printer-is-accepting-jobs".to_string(), "true".to_string());
let dest = Destination {
name: "TestPrinter".to_string(),
instance: None,
is_default: false,
options,
};
assert_eq!(dest.name, "TestPrinter");
assert_eq!(dest.full_name(), "TestPrinter");
assert_eq!(dest.state(), PrinterState::Idle);
assert!(dest.is_accepting_jobs());
assert_eq!(dest.info(), Some(&"Test Printer".to_string()));
}
#[test]
fn test_destination_with_instance() {
let dest = Destination {
name: "TestPrinter".to_string(),
instance: Some("instance1".to_string()),
is_default: true,
options: std::collections::HashMap::new(),
};
assert_eq!(dest.full_name(), "TestPrinter/instance1");
assert!(dest.is_default);
}
#[test]
fn test_destination_state_parsing() {
let mut options = std::collections::HashMap::new();
// Test different printer states
options.insert("printer-state".to_string(), "4".to_string());
let dest = Destination {
name: "Test".to_string(),
instance: None,
is_default: false,
options: options.clone(),
};
assert_eq!(dest.state(), PrinterState::Processing);
options.insert("printer-state".to_string(), "5".to_string());
let dest = Destination {
name: "Test".to_string(),
instance: None,
is_default: false,
options: options.clone(),
};
assert_eq!(dest.state(), PrinterState::Stopped);
}
#[test]
fn test_destination_state_reasons() {
let mut options = std::collections::HashMap::new();
options.insert("printer-state-reasons".to_string(),
"media-tray-empty-error,toner-low-warning".to_string());
let dest = Destination {
name: "Test".to_string(),
instance: None,
is_default: false,
options,
};
let reasons = dest.state_reasons();
assert_eq!(reasons.len(), 2);
assert!(reasons.contains(&"media-tray-empty-error".to_string()));
assert!(reasons.contains(&"toner-low-warning".to_string()));
}
}