spice-client 0.2.0

A pure Rust SPICE client library with native and WebAssembly support
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
//! Cursor channel implementation for hardware cursor support

use crate::channels::{Channel, ChannelConnection};
use crate::error::{Result, SpiceError};
use crate::protocol::*;
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, error, info, warn};

/// Cursor shape data
#[derive(Debug, Clone)]
pub struct CursorShape {
    pub width: u16,
    pub height: u16,
    pub hot_spot_x: u16,
    pub hot_spot_y: u16,
    pub data: Vec<u8>,
    pub mask: Option<Vec<u8>>,
}

/// Cursor update callback type
#[cfg(target_arch = "wasm32")]
pub type CursorUpdateCallback = Arc<dyn Fn(&CursorShape, (i32, i32), bool)>;

/// Cursor update callback type
#[cfg(not(target_arch = "wasm32"))]
pub type CursorUpdateCallback = Arc<dyn Fn(&CursorShape, (i32, i32), bool) + Send + Sync>;

/// Cursor channel for handling mouse cursor updates
pub struct CursorChannel {
    pub(crate) connection: ChannelConnection,
    current_cursor: Option<CursorShape>,
    cursor_cache: HashMap<u64, CursorShape>,
    cursor_visible: bool,
    cursor_position: (i32, i32),
    update_callback: Option<CursorUpdateCallback>,
}

impl CursorChannel {
    pub async fn new(host: &str, port: u16, channel_id: u8) -> Result<Self> {
        Self::new_with_connection_id(host, port, channel_id, None).await
    }

    pub async fn new_with_connection_id(
        host: &str,
        port: u16,
        channel_id: u8,
        connection_id: Option<u32>,
    ) -> Result<Self> {
        let mut connection =
            ChannelConnection::new(host, port, ChannelType::Cursor, channel_id).await?;
        if let Some(conn_id) = connection_id {
            connection.set_connection_id(conn_id);
        }
        connection.handshake().await?;

        Ok(Self {
            connection,
            current_cursor: None,
            cursor_cache: HashMap::new(),
            cursor_visible: true,
            cursor_position: (0, 0),
            update_callback: None,
        })
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn new_websocket(websocket_url: &str, channel_id: u8) -> Result<Self> {
        Self::new_websocket_with_auth(websocket_url, channel_id, None).await
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn new_websocket_with_auth(
        websocket_url: &str,
        channel_id: u8,
        auth_token: Option<String>,
    ) -> Result<Self> {
        Self::new_websocket_with_auth_and_session(websocket_url, channel_id, auth_token, None, None)
            .await
    }

    #[cfg(target_arch = "wasm32")]
    pub async fn new_websocket_with_auth_and_session(
        websocket_url: &str,
        channel_id: u8,
        auth_token: Option<String>,
        password: Option<String>,
        connection_id: Option<u32>,
    ) -> Result<Self> {
        let mut connection = ChannelConnection::new_websocket_with_auth(
            websocket_url,
            ChannelType::Cursor,
            channel_id,
            auth_token,
        )
        .await?;
        if let Some(pwd) = password {
            connection.set_password(pwd);
        }
        if let Some(conn_id) = connection_id {
            connection.set_connection_id(conn_id);
        }
        connection.handshake().await?;

        Ok(Self {
            connection,
            current_cursor: None,
            cursor_cache: HashMap::new(),
            cursor_visible: true,
            cursor_position: (0, 0),
            update_callback: None,
        })
    }

    pub async fn initialize(&mut self) -> Result<()> {
        info!("Cursor channel {} initialized", self.connection.channel_id);
        Ok(())
    }

    pub fn get_current_cursor(&self) -> Option<&CursorShape> {
        self.current_cursor.as_ref()
    }

    pub fn is_cursor_visible(&self) -> bool {
        self.cursor_visible
    }

    pub fn get_cursor_position(&self) -> (i32, i32) {
        self.cursor_position
    }

    /// Set the cursor update callback
    pub fn set_update_callback(&mut self, callback: CursorUpdateCallback) {
        self.update_callback = Some(callback);
    }

    /// Notify cursor update callback if set
    fn notify_cursor_update(&self) {
        if let Some(callback) = &self.update_callback {
            if let Some(cursor) = &self.current_cursor {
                callback(cursor, self.cursor_position, self.cursor_visible);
            }
        }
    }

    pub async fn run(&mut self) -> Result<()> {
        loop {
            let (header, data) = self.connection.read_message().await?;
            self.handle_message(&header, &data).await?;
        }
    }

    async fn handle_cursor_init(&mut self, data: &[u8]) -> Result<()> {
        if data.len() >= 8 {
            let visible = u16::from_le_bytes([data[0], data[1]]) != 0;
            let x = i16::from_le_bytes([data[2], data[3]]) as i32;
            let y = i16::from_le_bytes([data[4], data[5]]) as i32;
            let trail_len = u16::from_le_bytes([data[6], data[7]]);

            self.cursor_visible = visible;
            self.cursor_position = (x, y);

            info!(
                "Cursor init - visible: {}, position: ({}, {}), trail: {}",
                visible, x, y, trail_len
            );

            self.notify_cursor_update();
        }
        Ok(())
    }

    async fn handle_cursor_set(&mut self, data: &[u8]) -> Result<()> {
        if data.len() >= 17 {
            let cursor_header = SpiceCursorHeader {
                unique: u64::from_le_bytes([
                    data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
                ]),
                type_: data[8],
                width: u16::from_le_bytes([data[9], data[10]]),
                height: u16::from_le_bytes([data[11], data[12]]),
                hot_spot_x: u16::from_le_bytes([data[13], data[14]]),
                hot_spot_y: u16::from_le_bytes([data[15], data[16]]),
            };

            let data_offset = 17;
            let data_size = (cursor_header.width * cursor_header.height * 4) as usize;

            if data.len() >= data_offset + data_size {
                let cursor_data = data[data_offset..data_offset + data_size].to_vec();

                let cursor_shape = CursorShape {
                    width: cursor_header.width,
                    height: cursor_header.height,
                    hot_spot_x: cursor_header.hot_spot_x,
                    hot_spot_y: cursor_header.hot_spot_y,
                    data: cursor_data,
                    mask: None,
                };

                // Cache the cursor
                self.cursor_cache
                    .insert(cursor_header.unique, cursor_shape.clone());
                self.current_cursor = Some(cursor_shape);

                info!(
                    "Set cursor - {}x{}, hotspot: ({}, {})",
                    cursor_header.width,
                    cursor_header.height,
                    cursor_header.hot_spot_x,
                    cursor_header.hot_spot_y
                );

                self.notify_cursor_update();
            }
        }
        Ok(())
    }

    async fn handle_cursor_move(&mut self, data: &[u8]) -> Result<()> {
        if data.len() >= 4 {
            let x = i16::from_le_bytes([data[0], data[1]]) as i32;
            let y = i16::from_le_bytes([data[2], data[3]]) as i32;

            self.cursor_position = (x, y);
            debug!("Cursor moved to ({}, {})", x, y);

            self.notify_cursor_update();
        }
        Ok(())
    }

    async fn handle_cursor_hide(&mut self) -> Result<()> {
        self.cursor_visible = false;
        debug!("Cursor hidden");

        self.notify_cursor_update();
        Ok(())
    }

    async fn handle_cursor_trail(&mut self, data: &[u8]) -> Result<()> {
        if data.len() >= 4 {
            let length = u16::from_le_bytes([data[0], data[1]]);
            let frequency = u16::from_le_bytes([data[2], data[3]]);

            debug!(
                "Cursor trail - length: {}, frequency: {}",
                length, frequency
            );
        }
        Ok(())
    }

    async fn handle_cursor_inval_one(&mut self, data: &[u8]) -> Result<()> {
        if data.len() >= 8 {
            let cache_id = u64::from_le_bytes([
                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
            ]);

            self.cursor_cache.remove(&cache_id);
            debug!("Invalidated cursor cache entry: {}", cache_id);
        }
        Ok(())
    }

    async fn handle_cursor_inval_all(&mut self) -> Result<()> {
        self.cursor_cache.clear();
        debug!("Invalidated all cursor cache entries");
        Ok(())
    }
}

impl Channel for CursorChannel {
    async fn handle_message(&mut self, header: &SpiceDataHeader, data: &[u8]) -> Result<()> {
        match header.msg_type {
            SPICE_MSG_SET_ACK => {
                debug!("Received SET_ACK message");
                // Parse the generation number
                if data.len() >= 4 {
                    let generation = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
                    debug!("Cursor channel: SET_ACK generation: {}", generation);

                    // Send ACK_SYNC response
                    let ack_data = generation.to_le_bytes();
                    self.connection
                        .send_message(SPICE_MSGC_ACK_SYNC, &ack_data)
                        .await?;
                    debug!("Cursor channel: Sent ACK_SYNC response");
                }
            }
            SPICE_MSG_CURSOR_INIT => {
                debug!("Received cursor init");
                self.handle_cursor_init(data).await?;
            }
            SPICE_MSG_CURSOR_SET => {
                debug!("Received cursor set");
                self.handle_cursor_set(data).await?;
            }
            SPICE_MSG_CURSOR_MOVE => {
                debug!("Received cursor move");
                self.handle_cursor_move(data).await?;
            }
            SPICE_MSG_CURSOR_HIDE => {
                debug!("Received cursor hide");
                self.handle_cursor_hide().await?;
            }
            SPICE_MSG_CURSOR_TRAIL => {
                debug!("Received cursor trail");
                self.handle_cursor_trail(data).await?;
            }
            SPICE_MSG_CURSOR_INVAL_ONE => {
                debug!("Received cursor inval one");
                self.handle_cursor_inval_one(data).await?;
            }
            SPICE_MSG_CURSOR_INVAL_ALL => {
                debug!("Received cursor inval all");
                self.handle_cursor_inval_all().await?;
            }
            SPICE_MSG_CURSOR_RESET => {
                debug!("Received cursor reset");
                // Reset cursor to default state
                self.current_cursor = None;
                self.cursor_position = (0, 0);
                self.cursor_visible = false;
                self.cursor_cache.clear();
            }
            x if x == SPICE_MSG_PING => {
                debug!("Received PING message in cursor channel");
                if data.len() >= 4 {
                    let id = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
                    let time = if data.len() >= 12 {
                        u64::from_le_bytes([
                            data[4], data[5], data[6], data[7], data[8], data[9], data[10],
                            data[11],
                        ])
                    } else {
                        0
                    };
                    // Send PONG response
                    let mut pong_data = Vec::with_capacity(12);
                    pong_data.extend_from_slice(&id.to_le_bytes());
                    pong_data.extend_from_slice(&time.to_le_bytes());
                    self.connection
                        .send_message(SPICE_MSGC_PONG, &pong_data)
                        .await?;
                }
            }
            x if x == SPICE_MSG_NOTIFY => {
                if data.len() >= 12 {
                    let severity = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
                    let msg_len =
                        u32::from_le_bytes([data[8], data[9], data[10], data[11]]) as usize;
                    if data.len() >= 12 + msg_len {
                        let message = String::from_utf8_lossy(&data[12..12 + msg_len]);
                        match severity {
                            0 => info!("Cursor server info: {}", message),
                            1 => warn!("Cursor server warning: {}", message),
                            2 => error!("Cursor server error: {}", message),
                            _ => debug!("Cursor server notification: {}", message),
                        }
                    }
                }
            }
            x if x == SPICE_MSG_DISCONNECTING => {
                info!("Cursor channel: Server is disconnecting");
                return Err(SpiceError::ConnectionClosed);
            }
            x if x == SPICE_MSG_MIGRATE => {
                warn!("Cursor channel: Migration not implemented");
            }
            x if x == SPICE_MSG_MIGRATE_DATA => {
                warn!("Cursor channel: Migration data not implemented");
            }
            x if x == SPICE_MSG_WAIT_FOR_CHANNELS => {
                warn!("Cursor channel: Wait for channels not implemented");
            }
            _ => {
                warn!("Unknown cursor message type: {}", header.msg_type);
            }
        }

        Ok(())
    }

    fn channel_type(&self) -> ChannelType {
        ChannelType::Cursor
    }
}

#[derive(Debug, Clone)]
pub struct SpiceCursorHeader {
    pub unique: u64,
    pub type_: u8,
    pub width: u16,
    pub height: u16,
    pub hot_spot_x: u16,
    pub hot_spot_y: u16,
}

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

    #[tokio::test]
    async fn test_cursor_shape_creation() {
        let cursor = CursorShape {
            width: 32,
            height: 32,
            hot_spot_x: 16,
            hot_spot_y: 16,
            data: vec![0xFF; 32 * 32 * 4],
            mask: None,
        };

        assert_eq!(cursor.width, 32);
        assert_eq!(cursor.height, 32);
        assert_eq!(cursor.hot_spot_x, 16);
        assert_eq!(cursor.hot_spot_y, 16);
        assert_eq!(cursor.data.len(), 32 * 32 * 4);
    }

    #[tokio::test]
    async fn test_cursor_position() {
        // Test cursor position parsing
        let move_data = vec![
            0x10, 0x00, // x = 16
            0x20, 0x00, // y = 32
        ];

        let x = i16::from_le_bytes([move_data[0], move_data[1]]) as i32;
        let y = i16::from_le_bytes([move_data[2], move_data[3]]) as i32;

        assert_eq!(x, 16);
        assert_eq!(y, 32);
    }
}