# CUPS-RS Implementation TODO
This document outlines the missing functionality in cups-rs compared to the complete CUPS C API. The current implementation covers approximately 70% of the full API, focusing on core printing workflows.
## Implementation Status Overview
**✅ Implemented (70%)**
- Basic printer discovery (`cupsEnumDests`, `cupsGetDests2`)
- Destination information (`cupsCopyDestInfo`, `cupsCheckDestSupported`)
- Job creation and document submission (`cupsCreateDestJob`, `cupsStartDestDocument`)
- **Job lifecycle completion** (`cupsCloseDestJob`) ← **NEW**
- **Multi-document job support** with per-document options ← **NEW**
- **Authentication & security layer** (password/certificate callbacks) ← **NEW**
- **Advanced destination management** (add/remove/conflicts/lpoptions) ← **NEW**
- **Server & configuration management** (server/user/encryption/user-agent) ← **NEW**
- Basic media size queries (`cupsGetDestMediaByName`, `cupsGetDestMediaBySize`)
- Job management (`cupsGetJobs2`, `cupsCancelDestJob`)
- Basic option handling (`cupsAddOption`, `cupsGetOption`)
**❌ Missing (55%)**
- Server configuration management
- Localization support
- Low-level IPP request handling
- HTTP layer access
- Connection management
---
## HIGH PRIORITY - Core Missing Functionality
### 1. Job Lifecycle Completion
**Status**: ✅ COMPLETED
**Impact**: Jobs can now be properly finalized with multi-document support
#### Implemented Functions:
- [x] `cupsCloseDestJob` - Finalize and start printing multi-document jobs
- [x] Multi-document job support - Full support for multiple documents per job
- [x] Per-document print options - Document-specific settings supported
#### Implementation Details:
```rust
impl Job {
// ✅ IMPLEMENTED - Finalize multi-document jobs
pub fn close(&self) -> Result<()> {
// Calls cupsCloseDestJob to finalize the job
// Required when last_document=0 in cupsStartDestDocument
}
// ✅ IMPLEMENTED - Multi-document support with per-document options
pub fn submit_data_with_options(
&self,
data: &[u8],
format: &str,
doc_name: &str,
options: &[(String, String)],
last_document: bool,
) -> Result<()> {
// Supports per-document options and multi-document workflows
}
// ✅ IMPLEMENTED - File submission with options
pub fn submit_file_with_options<P: AsRef<Path>>(
&self,
file_path: P,
format: &str,
options: &[(String, String)],
last_document: bool,
) -> Result<()> {
// File-based submission with per-document options
}
}
```
### 2. Authentication & Security Layer
**Status**: ✅ COMPLETED
**Impact**: Now supports secured environments, GUI applications, and managed networks
#### Implemented Functions:
- [x] `cupsSetPasswordCB2` - Password callbacks for GUI applications
- [x] `cupsDoAuthentication` - Manual authentication handling
- [x] `cupsGetPassword2` - Get password from current callback
- [x] `cupsSetClientCertCB` - Client certificate callbacks (framework ready)
- [x] `cupsSetServerCertCB` - Server certificate validation (framework ready)
- [ ] `cupsSetCredentials` - SSL/TLS credential management (lower priority)
- [ ] `cupsSetServerCredentials` - Server credential setup (lower priority)
- [ ] `cupsMakeServerCredentials` - Self-signed certificate creation (lower priority)
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Authentication callback types
pub type PasswordCallback = dyn Fn(&str, Option<&str>, &str, &str) -> Option<String> + Send + Sync;
pub type ClientCertCallback = dyn Fn(&str) -> Option<Vec<u8>> + Send + Sync;
pub type ServerCertCallback = dyn Fn(&str, &[u8]) -> bool + Send + Sync;
// ✅ IMPLEMENTED - Thread-safe callback management
pub fn set_password_callback(callback: Option<Box<PasswordCallback>>) -> Result<()>;
pub fn set_client_cert_callback(callback: Option<Box<ClientCertCallback>>) -> Result<()>;
pub fn set_server_cert_callback(callback: Option<Box<ServerCertCallback>>) -> Result<()>;
pub fn get_password(prompt: &str, http: Option<&str>, method: &str, resource: &str) -> Option<String>;
pub fn do_authentication(http_connection: Option<&str>, method: &str, resource: &str) -> Result<()>;
```
### 3. Advanced Destination Management
**Status**: ✅ COMPLETED
**Impact**: Now supports comprehensive printer list management, conflict resolution, and preferences
#### Implemented Functions:
- [x] `cupsAddDest` - Add destinations to lists
- [x] `cupsSetDefaultDest` - Set default printer
- [x] `cupsSetDests2` - Save destination preferences to lpoptions
- [x] `cupsRemoveDest` - Remove destinations from lists
- [x] `cupsCopyDestConflicts` - Option conflict detection and resolution
- [ ] `cupsAddDestMediaOptions` - Add media-specific options (lower priority)
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Destination management
impl Destinations {
pub fn add_destination(&mut self, name: &str, instance: Option<&str>) -> Result<()>;
pub fn remove_destination(&mut self, name: &str, instance: Option<&str>) -> Result<bool>;
pub fn set_default_destination(&mut self, name: &str, instance: Option<&str>) -> Result<()>;
pub fn save_to_lpoptions(&self) -> Result<()>;
pub fn find_destination(&self, name: &str, instance: Option<&str>) -> Option<Destination>;
}
// ✅ IMPLEMENTED - Option conflict detection
pub struct OptionConflict {
pub conflicting_options: Vec<(String, String)>,
pub resolved_options: Vec<(String, String)>,
}
impl DestinationInfo {
pub fn check_option_conflicts(
&self,
dest: &Destination,
current_options: &[(String, String)],
new_option: &str,
new_value: &str,
) -> Result<Option<OptionConflict>>;
}
```
### 4. Server & Configuration Management
**Status**: ✅ COMPLETED
**Impact**: Now supports multi-server environments, user management, and encryption configuration
#### Implemented Functions:
- [x] `cupsServer` / `cupsSetServer` - Server configuration
- [x] `cupsUser` / `cupsSetUser` - User management
- [x] `cupsEncryption` / `cupsSetEncryption` - Encryption settings
- [x] `cupsUserAgent` / `cupsSetUserAgent` - HTTP user agent strings
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Server configuration functions
pub fn get_server() -> String;
pub fn set_server(server: Option<&str>) -> Result<()>;
pub fn get_user() -> String;
pub fn set_user(user: Option<&str>) -> Result<()>;
pub fn get_encryption() -> EncryptionMode;
pub fn set_encryption(mode: EncryptionMode);
pub fn get_user_agent() -> String;
pub fn set_user_agent(agent: Option<&str>) -> Result<()>;
// ✅ IMPLEMENTED - Type-safe encryption modes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncryptionMode {
Never,
IfRequested,
Required,
Always,
}
// ✅ IMPLEMENTED - Scoped configuration management
pub struct CupsConfig {
// Automatic restoration with Drop trait
}
impl CupsConfig {
pub fn new() -> Self;
pub fn with_server(self, server: &str) -> Result<Self>;
pub fn with_user(self, user: &str) -> Result<Self>;
pub fn with_encryption(self, mode: EncryptionMode) -> Self;
pub fn with_user_agent(self, user_agent: &str) -> Result<Self>;
pub fn current_config(&self) -> ConfigSummary;
}
```
---
## MEDIUM PRIORITY - Enhanced Functionality
### 5. Localization Support
**Status**: ✅ COMPLETED
**Impact**: UI applications can now display localized printer options in user's language
#### Implemented Functions:
- [x] `cupsLocalizeDestMedia` - Localized media size names
- [x] `cupsLocalizeDestOption` - Localized option names
- [x] `cupsLocalizeDestValue` - Localized option values
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Localization support in DestinationInfo
impl DestinationInfo {
pub fn localize_media(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
flags: u32,
size: &MediaSize,
) -> Result<String>;
pub fn localize_option(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
option: &str,
) -> Result<String>;
pub fn localize_value(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
option: &str,
value: &str,
) -> Result<String>;
}
```
### 6. Advanced Media & Option Queries
**Status**: ✅ COMPLETED
**Impact**: Applications can now query ready media, defaults, and supported values dynamically
#### Implemented Functions:
- [x] `cupsFindDestReady` - Currently loaded/ready media and finishings
- [x] `cupsFindDestDefault` - Default values for options
- [x] `cupsFindDestSupported` - Supported values for options
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Advanced destination queries
impl DestinationInfo {
pub fn get_ready_media(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
) -> Result<Vec<MediaSize>>;
pub fn get_ready_finishings(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
) -> Result<Vec<i32>>;
pub fn get_default_value(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
option: &str,
) -> Result<Option<String>>;
pub fn get_supported_values(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
option: &str,
) -> Result<Vec<String>>;
pub fn get_supported_options(
&self,
http: *mut bindings::_http_s,
dest: *mut bindings::cups_dest_s,
) -> Result<Vec<String>>;
}
```
### 7. Direct Connection Management
**Status**: ✅ COMPLETED
**Impact**: Applications can now connect directly to printers or CUPS schedulers with advanced connection control
#### Implemented Functions:
- [x] `cupsConnectDest` - Direct printer connections with timeouts and cancellation
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Direct connection management
pub struct HttpConnection {
// Safe wrapper around http_t with automatic cleanup
}
impl HttpConnection {
pub fn as_ptr(&self) -> *mut bindings::_http_s;
pub fn resource_path(&self) -> &str;
pub fn close(&mut self);
pub fn is_connected(&self) -> bool;
}
impl Destination {
pub fn connect(
&self,
flags: ConnectionFlags,
timeout_ms: Option<i32>,
cancel: Option<&AtomicBool>,
) -> Result<HttpConnection>;
pub fn connect_with_callback<T>(
&self,
flags: ConnectionFlags,
timeout_ms: Option<i32>,
cancel: Option<&AtomicBool>,
callback: &mut DestCallback<T>,
user_data: &mut T,
) -> Result<HttpConnection>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionFlags {
Scheduler, // Connect to CUPS scheduler
Device, // Connect directly to device
}
// ✅ IMPLEMENTED - Convenience function
pub fn connect_to_destination(
dest: &Destination,
flags: ConnectionFlags,
timeout_ms: Option<i32>,
cancel: Option<&AtomicBool>,
) -> Result<HttpConnection>;
```
### 8. Option Processing & Validation
**Status**: ✅ COMPLETED
**Impact**: Enhanced developer experience with convenient option handling
#### Implemented Functions:
- [x] `cupsParseOptions` - Command-line option parsing
- [x] `cupsRemoveOption` - Option removal from arrays
- [x] `cupsAddIntegerOption` - Type-safe integer options
- [x] `cupsEncodeOption` - Single option to IPP attribute
- [x] `cupsEncodeOptions` / `cupsEncodeOptions2` - Batch IPP encoding
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - Option processing functions
pub fn parse_options(arg: &str) -> Result<Vec<(String, String)>>;
pub fn add_option(name: &str, value: &str, options: Vec<(String, String)>) -> Vec<(String, String)>;
pub fn add_integer_option(name: &str, value: i32, options: Vec<(String, String)>) -> Vec<(String, String)>;
pub fn remove_option(name: &str, options: Vec<(String, String)>) -> (Vec<(String, String)>, bool);
pub fn get_option<'a>(name: &str, options: &'a [(String, String)]) -> Option<&'a str>;
pub fn get_integer_option(name: &str, options: &[(String, String)]) -> Option<i32>;
// ✅ IMPLEMENTED - IPP encoding functions
pub fn encode_option(
ipp: *mut bindings::ipp_s,
group_tag: bindings::ipp_tag_t,
name: &str,
value: &str,
) -> Result<()>;
pub fn encode_options(
ipp: *mut bindings::ipp_s,
options: &[(String, String)],
) -> Result<()>;
pub fn encode_options_with_group(
ipp: *mut bindings::ipp_s,
options: &[(String, String)],
group_tag: bindings::ipp_tag_t,
) -> Result<()>;
```
---
## LOWER PRIORITY - Advanced/Specialized
### 9. Low-Level IPP Request Handling
**Status**: ✅ COMPLETED
**Impact**: Applications can now build custom IPP requests and parse responses manually
#### Implemented Functions:
- [x] `ippNewRequest` - Create IPP request messages
- [x] `ippAdd*` family - Add attributes (Boolean, Integer, String, Strings)
- [x] `ippGet*` family - Read attributes (String, Integer, Boolean, Count)
- [x] `ippFind*` family - Search attributes
- [x] `cupsDoRequest` - Send custom IPP requests
- [ ] `ippSet*` family - Modify attributes (lower priority)
- [ ] `cupsDoFileRequest` - Send IPP requests with files (lower priority)
- [ ] `ippRead` / `ippWrite` - Serialize IPP messages (lower priority)
#### Implementation Details:
```rust
// ✅ IMPLEMENTED - IPP request/response handling
pub struct IppRequest {
// Safe wrapper with automatic cleanup
}
pub struct IppResponse {
// Safe wrapper with automatic cleanup
}
pub struct IppAttribute {
// IPP attribute accessor
}
impl IppRequest {
pub fn new(operation: IppOperation) -> Result<Self>;
pub fn add_string(&mut self, group: IppTag, value_tag: IppValueTag, name: &str, value: &str) -> Result<()>;
pub fn add_integer(&mut self, group: IppTag, value_tag: IppValueTag, name: &str, value: i32) -> Result<()>;
pub fn add_boolean(&mut self, group: IppTag, name: &str, value: bool) -> Result<()>;
pub fn add_strings(&mut self, group: IppTag, value_tag: IppValueTag, name: &str, values: &[&str]) -> Result<()>;
pub fn send(&self, connection: &HttpConnection, resource: &str) -> Result<IppResponse>;
}
impl IppResponse {
pub fn status(&self) -> IppStatus;
pub fn is_successful(&self) -> bool;
pub fn find_attribute(&self, name: &str, group: Option<IppTag>) -> Option<IppAttribute>;
pub fn attributes(&self) -> Vec<IppAttribute>;
}
impl IppAttribute {
pub fn name(&self) -> Option<String>;
pub fn count(&self) -> usize;
pub fn get_string(&self, index: usize) -> Option<String>;
pub fn get_integer(&self, index: usize) -> i32;
pub fn get_boolean(&self, index: usize) -> bool;
}
// ✅ IMPLEMENTED - Type-safe enums
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IppTag { Operation, Job, Printer, Subscription, EventNotification, Document, ... }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IppValueTag { Integer, Boolean, Enum, String, Text, Name, Keyword, Uri, ... }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IppOperation { PrintJob, ValidateJob, CreateJob, SendDocument, CancelJob, ... }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IppStatus { Ok, ErrorBadRequest, ErrorNotFound, ... }
```
### 10. HTTP Layer Functions
**Status**: 🟡 Very Specialized Use Cases
**Impact**: Cannot access low-level HTTP functionality
#### Missing Functions (~60 functions):
- [ ] `httpConnect2` / `httpClose` - HTTP connection management
- [ ] `httpGet` / `httpPost` / `httpPut` - HTTP methods
- [ ] `httpRead2` / `httpWrite2` - Data transfer
- [ ] `httpAddr*` family - Network address handling
- [ ] `http*Credentials` family - SSL/TLS certificate management
### 11. URI-Based Printer Discovery
**Status**: 🟡 Network Printer Support
**Impact**: Cannot discover printers by URI
#### Missing Functions:
- [ ] `cupsGetDestWithURI` - Create destinations from IPP/IPPS URIs
#### Implementation Details:
```rust
pub fn get_destination_with_uri(name: Option<&str>, uri: &str) -> Result<Destination>;
```
---
## Architecture Gaps & Rust-Specific Enhancements
### Missing Rust-Specific Features
#### 1. Async Support
**Current**: Entirely synchronous API
**Needed**: Async versions of network operations
```rust
pub async fn enum_destinations_async(...) -> Result<Vec<Destination>>;
pub async fn create_job_async(...) -> Result<Job>;
```
#### 2. Builder Patterns
**Current**: Manual option construction
**Needed**: Fluent builder APIs
```rust
let options = PrintOptions::builder()
.copies(2)
.color_mode(ColorMode::Color)
.duplex(DuplexMode::TwoSidedPortrait)
.media(MediaSize::A4)
.build();
```
#### 3. Type-Safe Enums
**Current**: String constants
**Needed**: Rust enums for all printer capabilities
```rust
#[derive(Debug, Clone)]
pub enum PrinterCapability {
Color, BlackAndWhite, Duplex, Staple, Punch, etc.
}
```
#### 4. Callback Safety
**Current**: Unsafe C callback bridging
**Needed**: Safe Rust closures with proper lifetime management
#### 5. Error Recovery
**Current**: Basic error types
**Needed**: Structured errors with recovery suggestions
```rust
#[derive(Debug)]
pub enum CupsError {
PrinterNotAccepting { printer: String, suggestion: String },
AuthenticationRequired { realm: String, methods: Vec<AuthMethod> },
NetworkTimeout { retry_suggested: bool },
}
```
### Thread Safety & Memory Management
#### 1. Connection Pooling
**Issue**: CUPS has per-thread state management
**Needed**: Thread-safe connection management
#### 2. Resource Cleanup
**Issue**: C resource lifetimes
**Needed**: More RAII patterns with automatic cleanup
#### 3. Configuration Management
**Issue**: Global state in CUPS
**Needed**: Scoped configuration objects
---
## Implementation Phases
### Phase 1: Essential Enterprise Features (3-4 weeks)
**Priority**: 🔴 Critical for production use
1. **Job Lifecycle Completion**
- Implement `cupsCloseDestJob` wrapper
- Add multi-document job support
- Support per-document options
2. **Authentication Framework**
- Password callback infrastructure
- Basic authentication handling
- GUI application support
3. **Destination Management**
- Add/remove destinations
- Set default printer
- Save preferences to lpoptions
4. **Server Configuration**
- Server/user/encryption settings
- Configuration persistence
### Phase 2: Enhanced User Experience (2-3 weeks)
**Priority**: 🟡 Important for polished applications
1. **Localization Support**
- Localized option/value names
- Multi-language media descriptions
2. **Advanced Queries**
- Ready media detection
- Default value queries
- Supported value enumeration
3. **Connection Management**
- Direct printer connections
- Timeout and cancellation support
4. **Enhanced Option Handling**
- Command-line parsing
- Type-safe option builders
- Conflict resolution
### Phase 3: Complete API Coverage (4-5 weeks)
**Priority**: 🟡 Specialized and administrative tools
1. **Low-level IPP Layer**
- Manual IPP request construction
- Custom attribute handling
- Raw message processing
2. **HTTP Layer Access**
- Direct HTTP operations
- SSL/TLS management
- Network address handling
3. **Administrative Functions**
- Server credential management
- Certificate validation
- URI-based discovery
### Phase 4: Rust-Specific Enhancements (2-3 weeks)
**Priority**: 🟢 Nice-to-have improvements
1. **Async Support**
- Tokio integration
- Async printer discovery
- Non-blocking job submission
2. **Enhanced Type Safety**
- Enum-based capabilities
- Builder patterns
- Compile-time validation
3. **Better Error Handling**
- Structured error types
- Recovery suggestions
- Error categorization
---
## Testing Strategy
### Phase 1 Testing
- Authentication with various CUPS servers
- Multi-document job workflows
- Destination management operations
- Server configuration scenarios
### Phase 2 Testing
- Localization in different locales
- Media detection and selection
- Direct printer communication
- Option conflict scenarios
### Phase 3 Testing
- Custom IPP request/response handling
- SSL/TLS connection scenarios
- Administrative operations
- Network printer discovery
### Phase 4 Testing
- Async operation performance
- Type safety verification
- Error handling completeness
- Memory safety under load
---
## Compatibility Matrix
| Basic Printing | ✅ Complete | ✅ | ✅ | ✅ | ✅ |
| Authentication | ✅ Complete | ✅ Complete | ✅ Complete | ✅ | ✅ |
| Destination Mgmt | ✅ Complete | ✅ Complete | ✅ | ✅ | ✅ |
| Localization | ❌ Missing | ❌ | ✅ Complete | ✅ | ✅ |
| IPP Low-level | ❌ Missing | ❌ | ❌ | ✅ Complete | ✅ |
| Async Support | ❌ Missing | ❌ | ❌ | ❌ | ✅ Complete |
---
## Success Metrics
### Phase 1 Success Criteria
- [x] **Can authenticate with secured CUPS servers** ← **COMPLETED**
- [x] **Can manage printer lists programmatically** ← **COMPLETED**
- [x] **Can submit multi-document jobs** ← **COMPLETED**
- [ ] Can configure server connections
### Phase 2 Success Criteria
- [ ] UI applications show localized printer options
- [ ] Can detect and display ready media
- [ ] Can resolve option conflicts automatically
- [ ] Can connect directly to network printers
### Phase 3 Success Criteria
- [ ] Can build custom printer management tools
- [ ] Can handle all IPP operations manually
- [ ] Can discover printers by URI
- [ ] Full API compatibility with C CUPS library
### Phase 4 Success Criteria
- [ ] Provides idiomatic Rust printing API
- [ ] Supports async/await patterns
- [ ] Offers compile-time safety for printer operations
- [ ] Demonstrates performance benefits over C bindings
---
*This TODO serves as the comprehensive roadmap for completing the cups-rs implementation. Each phase builds upon the previous one, ensuring a stable and progressively more capable library.*