rat-rdp-session 0.1.0

RDP session state machine for rat_rdp_lite
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
use std::sync::Arc;

use rat_rdp_bulk::{BulkCompressor, CompressionType as BulkCompressionType};
use rat_rdp_core::{ReadCursor, WriteBuf};
use rat_rdp_dvc::{DrdynvcClient, DvcClientProcessor, DynamicChannelRef};
use rat_rdp_graphics::pointer::DecodedPointer;
use rat_rdp_pdu::gcc::{ChannelName, Monitor};
use rat_rdp_pdu::geometry::InclusiveRectangle;
use rat_rdp_pdu::input::fast_path::{FastPathInput, FastPathInputEvent};
use rat_rdp_pdu::rdp::autodetect::AutoDetectRequest;
use rat_rdp_pdu::rdp::capability_sets::WindowSupportLevel;
use rat_rdp_pdu::rdp::client_info::CompressionType;
use rat_rdp_pdu::rdp::headers::ShareDataPdu;
use rat_rdp_pdu::rdp::multitransport::MultitransportRequestPdu;
use rat_rdp_pdu::rdp::refresh_rectangle::RefreshRectanglePdu;
use rat_rdp_pdu::rdp::session_info::ServerAutoReconnect;
use rat_rdp_pdu::rdp::suppress_output::SuppressOutputPdu;
use rat_rdp_pdu::slow_path::{self, GraphicsUpdateType};
use rat_rdp_pdu::window::{
    WindowingOrdersUpdate, try_decode_fast_path_windowing_orders, try_decode_slow_path_windowing_orders,
};
use rat_rdp_pdu::{Action, mcs};
use rat_rdp_svc::{StaticChannelSet, SvcMessage, SvcProcessor, SvcProcessorMessages};
use tracing::debug;

use crate::fast_path::UpdateKind;
use crate::image::DecodedImage;
use crate::{SessionError, SessionErrorExt as _, SessionResult, fast_path, x224};

fn to_bulk_compression_type(compression_type: CompressionType) -> BulkCompressionType {
    match compression_type {
        CompressionType::K8 => BulkCompressionType::Rdp4,
        CompressionType::K64 => BulkCompressionType::Rdp5,
        CompressionType::Rdp6 => BulkCompressionType::Rdp6,
        CompressionType::Rdp61 => BulkCompressionType::Rdp61,
    }
}

pub struct ActiveStage {
    x224_processor: x224::Processor,
    fast_path_processor: fast_path::Processor,
    /// Shared server-to-client compression history across all output transports.
    bulk_decompressor: Option<BulkCompressor>,
    enable_server_pointer: bool,
    window_support_level: Option<WindowSupportLevel>,
}

/// Builder for [`ActiveStage`].
///
/// All fields are required; they are typically taken straight from `ironrdp-connector`’s
/// `ConnectionResult` once the connection sequence is finalized.
pub struct ActiveStageBuilder {
    pub static_channels: StaticChannelSet,
    pub user_channel_id: u16,
    pub io_channel_id: u16,
    pub message_channel_id: Option<u16>,
    pub share_id: u32,
    /// The bulk compression type negotiated during connection activation.
    pub compression_type: Option<CompressionType>,
    /// Enable server-side pointer updates (client-side pointer rendering).
    pub enable_server_pointer: bool,
    /// Use software rendering mode for pointer bitmap generation.
    pub pointer_software_rendering: bool,
}

impl ActiveStageBuilder {
    pub fn build(self) -> ActiveStage {
        let Self {
            static_channels,
            user_channel_id,
            io_channel_id,
            message_channel_id,
            share_id,
            compression_type,
            enable_server_pointer,
            pointer_software_rendering,
        } = self;

        let x224_processor = x224::Processor::new(
            static_channels,
            user_channel_id,
            io_channel_id,
            message_channel_id,
            share_id,
        );

        let fast_path_processor = fast_path::ProcessorBuilder {
            io_channel_id,
            user_channel_id,
            share_id,
            enable_server_pointer,
            pointer_software_rendering,
        }
        .build();

        ActiveStage {
            x224_processor,
            fast_path_processor,
            bulk_decompressor: new_bulk_decompressor(compression_type),
            enable_server_pointer,
            window_support_level: None,
        }
    }
}

fn new_bulk_decompressor(compression_type: Option<CompressionType>) -> Option<BulkCompressor> {
    compression_type.map(|compression_type| BulkCompressor::new(to_bulk_compression_type(compression_type)))
}

impl ActiveStage {
    pub fn update_mouse_pos(&mut self, x: u16, y: u16) {
        self.fast_path_processor.update_mouse_pos(x, y);
    }

    /// Returns whether a malformed Fast-Path bitmap was discarded and needs a full visual recovery.
    ///
    /// The caller decides whether the negotiated capabilities permit a recovery request.
    pub fn take_bitmap_recovery_request(&mut self) -> bool {
        self.fast_path_processor.take_bitmap_recovery_request()
    }

    /// Encodes outgoing input events and modifies image if necessary (e.g for client-side pointer
    /// rendering).
    pub fn process_fastpath_input(
        &mut self,
        image: &mut DecodedImage,
        events: &[FastPathInputEvent],
    ) -> SessionResult<Vec<ActiveStageOutput>> {
        if events.is_empty() {
            return Ok(Vec::new());
        }

        // Mouse move events are prevalent, so we can preallocate space for
        // response frames + graphics update.
        let mut output = Vec::with_capacity(events.len().div_ceil(FastPathInput::MAX_EVENTS) + 1);

        for event_chunk in events.chunks(FastPathInput::MAX_EVENTS) {
            // PERF: unnecessary copy
            let fastpath_input = FastPathInput::new(event_chunk.to_vec()).map_err(SessionError::decode)?;
            let frame = rat_rdp_core::encode_vec(&fastpath_input).map_err(SessionError::encode)?;
            output.push(ActiveStageOutput::ResponseFrame(frame));
        }

        // If pointer rendering is disabled - we can skip the rest
        if !self.enable_server_pointer {
            return Ok(output);
        }

        // If mouse was moved by client - we should update framebuffer to reflect new
        // pointer position
        let mouse_pos = events.iter().find_map(|event| match event {
            FastPathInputEvent::MouseEvent(event) => Some((event.x_position, event.y_position)),
            FastPathInputEvent::MouseEventEx(event) => Some((event.x_position, event.y_position)),
            _ => None,
        });

        let (mouse_x, mouse_y) = match mouse_pos {
            Some(mouse_pos) => mouse_pos,
            None => return Ok(output),
        };

        // Graphics update is only sent when update is visually changed the framebuffer
        if let Some(rect) = image.move_pointer(mouse_x, mouse_y)? {
            output.push(ActiveStageOutput::GraphicsUpdate(rect));
        }

        Ok(output)
    }

    /// Process a frame received from the server.
    pub fn process(
        &mut self,
        image: &mut DecodedImage,
        action: Action,
        frame: &[u8],
    ) -> SessionResult<Vec<ActiveStageOutput>> {
        let (mut stage_outputs, processor_updates) = match action {
            Action::FastPath => {
                let mut output = WriteBuf::new();
                let processor_updates =
                    self.fast_path_processor
                        .process(image, frame, &mut output, &mut self.bulk_decompressor)?;
                (
                    vec![ActiveStageOutput::ResponseFrame(output.into_inner())],
                    processor_updates,
                )
            }
            Action::X224 => {
                let x224_outputs = self.x224_processor.process(frame, &mut self.bulk_decompressor)?;
                let mut stage_outputs = Vec::new();
                let mut processor_updates = Vec::new();

                for output in x224_outputs {
                    match output {
                        x224::ProcessorOutput::GraphicsUpdate(data) => {
                            let (updates, windowing_orders) = process_slow_path_graphics(
                                &mut self.fast_path_processor,
                                image,
                                self.window_support_level,
                                &data,
                            )?;
                            processor_updates.extend(updates);
                            if let Some(windowing_orders) = windowing_orders {
                                stage_outputs.push(ActiveStageOutput::WindowingOrders(windowing_orders));
                            }
                        }
                        x224::ProcessorOutput::PointerUpdate(data) => {
                            let updates = process_slow_path_pointer(&mut self.fast_path_processor, image, &data)?;
                            processor_updates.extend(updates);
                        }
                        other => {
                            stage_outputs.push(ActiveStageOutput::try_from(other)?);
                        }
                    }
                }

                (stage_outputs, processor_updates)
            }
        };

        for update in processor_updates {
            match update {
                UpdateKind::None => {}
                UpdateKind::Orders(data) => {
                    if let Some(windowing_orders) =
                        process_fast_path_windowing_orders(self.window_support_level, &data)?
                    {
                        stage_outputs.push(ActiveStageOutput::WindowingOrders(windowing_orders));
                    }
                }
                UpdateKind::Region(region) => {
                    stage_outputs.push(ActiveStageOutput::GraphicsUpdate(region));
                }
                UpdateKind::PointerDefault => {
                    stage_outputs.push(ActiveStageOutput::PointerDefault);
                }
                UpdateKind::PointerHidden => {
                    stage_outputs.push(ActiveStageOutput::PointerHidden);
                }
                UpdateKind::PointerPosition { x, y } => {
                    stage_outputs.push(ActiveStageOutput::PointerPosition { x, y });
                }
                UpdateKind::PointerBitmap(pointer) => {
                    stage_outputs.push(ActiveStageOutput::PointerBitmap(pointer));
                }
            }
        }

        Ok(stage_outputs)
    }

    /// Replaces the fast-path processor wholesale.
    ///
    /// Prefer [`ActiveStage::reactivate`] for a Deactivation-Reactivation Sequence: it also
    /// updates the share_id and the server-pointer setting, which a bare replacement does not.
    pub fn set_fastpath_processor(&mut self, processor: fast_path::Processor) {
        self.fast_path_processor = processor;
    }

    /// Updates the share_id used by the x224 processor for encoding ShareDataPdu.
    ///
    /// [`ActiveStage::reactivate`] already does this, so a Deactivation-Reactivation Sequence does
    /// not need to call it.
    pub fn set_share_id(&mut self, share_id: u32) {
        self.x224_processor.set_share_id(share_id);
    }

    /// Updates the negotiated maximum payload length of outgoing static virtual channel chunks.
    pub fn set_static_channel_chunk_size(&mut self, maximum_chunk_size: usize) -> bool {
        self.x224_processor.set_static_channel_chunk_size(maximum_chunk_size)
    }

    /// Returns the negotiated maximum payload length of outgoing static virtual channel chunks.
    pub fn static_channel_chunk_size(&self) -> usize {
        self.x224_processor.static_channel_chunk_size()
    }

    pub fn set_enable_server_pointer(&mut self, enable_server_pointer: bool) {
        self.enable_server_pointer = enable_server_pointer;
    }

    /// Sets Window List support for the current activation.
    ///
    /// `None` preserves desktop-session behavior by ignoring drawing orders.
    pub fn set_window_support_level(&mut self, window_support_level: Option<WindowSupportLevel>) {
        self.window_support_level = window_support_level;
    }

    /// Rebuilds the fast-path processor for a [Deactivation-Reactivation Sequence].
    ///
    /// The shared bulk decompression history is retained. The server signals any history reset
    /// with the PACKET_FLUSHED and PACKET_AT_FRONT compression flags, which are applied per update.
    ///
    /// Returns `false` without changing the active stage when the negotiated static virtual
    /// channel chunk size is invalid.
    ///
    /// [Deactivation-Reactivation Sequence]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/dfc234ce-481a-4674-9a5d-2a7bafb14432
    pub fn reactivate(
        &mut self,
        io_channel_id: u16,
        user_channel_id: u16,
        share_id: u32,
        enable_server_pointer: bool,
        pointer_software_rendering: bool,
        static_channel_chunk_size: usize,
    ) -> bool {
        if !self
            .x224_processor
            .set_static_channel_chunk_size(static_channel_chunk_size)
        {
            return false;
        }

        self.fast_path_processor = fast_path::ProcessorBuilder {
            io_channel_id,
            user_channel_id,
            share_id,
            enable_server_pointer,
            pointer_software_rendering,
        }
        .build();
        // The x224 processor encodes ShareDataPdu with the server's (possibly new) share_id.
        self.x224_processor.set_share_id(share_id);
        self.enable_server_pointer = enable_server_pointer;

        true
    }

    /// Encodes client-side graceful shutdown request. Note that upon sending this request,
    /// client should wait for server's ShutdownDenied PDU before closing the connection.
    ///
    /// Client-side graceful shutdown is defined in [MS-RDPBCGR]
    ///
    /// [MS-RDPBCGR]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/27915739-8f77-487e-9927-55008af7fd68
    pub fn graceful_shutdown(&self) -> SessionResult<Vec<ActiveStageOutput>> {
        let mut frame = WriteBuf::new();
        self.x224_processor
            .encode_static(&mut frame, ShareDataPdu::ShutdownRequest)?;

        Ok(vec![ActiveStageOutput::ResponseFrame(frame.into_inner())])
    }

    /// Requests a full redraw of the negotiated desktop.
    fn request_full_refresh(&self, width: u16, height: u16) -> SessionResult<Vec<u8>> {
        debug_assert!(width != 0 && height != 0);
        let mut frame = WriteBuf::new();
        self.x224_processor.encode_static(
            &mut frame,
            ShareDataPdu::RefreshRectangle(RefreshRectanglePdu {
                areas_to_refresh: vec![InclusiveRectangle {
                    left: 0,
                    top: 0,
                    right: width.saturating_sub(1),
                    bottom: height.saturating_sub(1),
                }],
            }),
        )?;
        Ok(frame.into_inner())
    }

    /// Requests a full redraw using a server-supported recovery PDU.
    ///
    /// A Suppress Output toggle is preferred when supported because it is the documented Refresh
    /// Rect workaround for affected Microsoft RDP servers.
    ///
    /// [MS-RDPBCGR 2.2.11.3.1]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/0be71491-0b01-402c-947d-080706ccf91b
    pub fn request_full_redraw(
        &self,
        width: u16,
        height: u16,
        refresh_rect_support: bool,
        suppress_output_support: bool,
    ) -> SessionResult<Vec<Vec<u8>>> {
        debug_assert!(width != 0 && height != 0);
        if suppress_output_support {
            let mut suppress = WriteBuf::new();
            self.x224_processor.encode_static(
                &mut suppress,
                ShareDataPdu::SuppressOutput(SuppressOutputPdu { desktop_rect: None }),
            )?;

            let mut resume = WriteBuf::new();
            self.x224_processor.encode_static(
                &mut resume,
                ShareDataPdu::SuppressOutput(SuppressOutputPdu {
                    desktop_rect: Some(InclusiveRectangle {
                        left: 0,
                        top: 0,
                        right: width.saturating_sub(1),
                        bottom: height.saturating_sub(1),
                    }),
                }),
            )?;

            return Ok(vec![suppress.into_inner(), resume.into_inner()]);
        }

        if refresh_rect_support {
            return Ok(vec![self.request_full_refresh(width, height)?]);
        }

        Ok(Vec::new())
    }

    /// Send a pdu on the static global channel. Typically used to send input events
    pub fn encode_static(&self, output: &mut WriteBuf, pdu: ShareDataPdu) -> SessionResult<usize> {
        self.x224_processor.encode_static(output, pdu)
    }

    pub fn get_svc_processor<T: SvcProcessor + 'static>(&mut self) -> Option<&T> {
        self.x224_processor.get_svc_processor()
    }

    pub fn get_svc_processor_mut<T: SvcProcessor + 'static>(&mut self) -> Option<&mut T> {
        self.x224_processor.get_svc_processor_mut()
    }

    pub fn get_dvc<T: DvcClientProcessor + 'static>(&self) -> Option<DynamicChannelRef<'_, T>> {
        self.x224_processor.get_dvc::<T>()
    }

    pub fn get_dvc_by_channel_id<T: DvcClientProcessor + 'static>(
        &self,
        channel_id: u32,
    ) -> Option<DynamicChannelRef<'_, T>> {
        self.x224_processor.get_dvc_by_channel_id(channel_id)
    }

    /// Returns whether the Display Control channel is available and has received server capabilities.
    ///
    /// `None` means no Display Control client is configured. `Some(false)` means it is configured
    /// but its dynamic channel is still opening or has not received its capabilities PDU.
    pub fn display_control_ready(&mut self) -> Option<bool> {
        None
    }

    /// Completes user's SVC request with data, required to sent it over the network and returns
    /// a buffer with encoded data.
    pub fn process_svc_processor_messages<C: SvcProcessor + 'static>(
        &self,
        messages: SvcProcessorMessages<C>,
    ) -> SessionResult<Vec<u8>> {
        self.x224_processor.process_svc_processor_messages(messages)
    }

    /// Completes an SVC request for a runtime-defined channel name.
    pub fn process_svc_messages_by_name(
        &self,
        channel_name: &ChannelName,
        messages: Vec<SvcMessage>,
    ) -> SessionResult<Vec<u8>> {
        self.x224_processor.process_svc_messages_by_name(channel_name, messages)
    }

    /// Fully encodes a resize request for sending over the Display Control Virtual Channel.
    ///
    /// If the Display Control Virtual Channel is not available, not yet connected, or has not
    /// received its required server capabilities PDU, this method returns `None`.
    ///
    /// Per [2.2.2.2.1]:
    /// - The `width` MUST be greater than or equal to 200 pixels and less than or equal to 8192 pixels, and MUST NOT be an odd value.
    /// - The `height` MUST be greater than or equal to 200 pixels and less than or equal to 8192 pixels.
    /// - The `scale_factor` MUST be ignored if it is less than 100 percent or greater than 500 percent.
    /// - The `physical_dims` (width, height) MUST be ignored if either is less than 10 mm or greater than 10,000 mm.
    ///
    /// Use [`ironrdp_displaycontrol::pdu::MonitorLayoutEntry::adjust_display_size`] to adjust `width` and `height` before calling this function
    /// to ensure the display size is within the valid range.
    ///
    /// [2.2.2.2.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpedisp/ea2de591-9203-42cd-9908-be7a55237d1c
    pub fn encode_resize(
        &mut self,
        _width: u32,
        _height: u32,
        _scale_factor: Option<u32>,
        _physical_dims: Option<(u32, u32)>,
    ) -> Option<SessionResult<Vec<u8>>> {
        None
    }

    /// Returns whether the RDPEI channel is available and ready (SC_READY / CS_READY exchanged).
    ///
    /// `None` means no RDPEI client is configured. `Some(false)` means it is registered but not
    /// yet ready (or currently suspended for touch/pen send purposes when checking readiness for
    /// injection — use [`Self::rdpei_can_send_touch`] for the send gate).
    pub fn rdpei_ready(&mut self) -> Option<bool> {
        None
    }

    pub fn rdpei_can_send_touch(&mut self) -> bool {
        false
    }

    pub fn encode_rdpei_touch(&mut self, _event: ()) -> Option<SessionResult<Vec<u8>>> {
        None
    }

    pub fn encode_rdpei_dismiss_hovering(&mut self, _contact_id: u8) -> Option<SessionResult<Vec<u8>>> {
        None
    }

    pub fn encode_rdpei_pen(&mut self, _event: ()) -> Option<SessionResult<Vec<u8>>> {
        None
    }

    pub fn encode_dvc_messages(&mut self, messages: Vec<SvcMessage>) -> SessionResult<Vec<u8>> {
        self.process_svc_processor_messages(SvcProcessorMessages::<DrdynvcClient>::new(messages))
    }
}

#[derive(Debug)]
pub enum ActiveStageOutput {
    ResponseFrame(Vec<u8>),
    GraphicsUpdate(InclusiveRectangle),
    PointerDefault,
    PointerHidden,
    PointerPosition {
        x: u16,
        y: u16,
    },
    PointerBitmap(Arc<DecodedPointer>),
    /// Server-reported remote monitor layout ([MS-RDPBCGR] 2.2.12.1).
    MonitorLayout(Vec<Monitor>),
    /// Validated Windowing Alternate Secondary Drawing Orders.
    ///
    /// The payload is a complete slow-path Orders graphics update. It remains
    /// protocol data rather than a RAIL message.
    WindowingOrders(Vec<u8>),
    Terminate(GracefulDisconnectReason),
    /// Server Save Session Info notification ([MS-RDPBCGR] 2.2.10.1).
    ///
    /// This value-free event deliberately excludes server-provided session details, which can
    /// include credentials and auto-reconnect cookies.
    SaveSessionInfo {
        /// Whether the notification unambiguously reports a completed logon.
        logon_complete: bool,
    },
    /// Received a Server Deactivate All PDU. The consumer should execute the [Deactivation-Reactivation Sequence].
    ///
    /// [Deactivation-Reactivation Sequence]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/dfc234ce-481a-4674-9a5d-2a7bafb14432
    DeactivateAll,
    /// Server Initiate Multitransport Request. The application should establish a
    /// sideband UDP transport using the provided request parameters.
    ///
    /// See [\[MS-RDPBCGR\] 2.2.15.1].
    ///
    /// [\[MS-RDPBCGR\] 2.2.15.1]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/de783158-8b01-4818-8fb0-62523a5b3490
    MultitransportRequest(MultitransportRequestPdu),
    /// Server-reported network characteristics ([\[MS-RDPBCGR\] 2.2.14.1.5]).
    ///
    /// Contains an [`AutoDetectRequest::NetworkCharacteristicsResult`] with
    /// RTT and/or bandwidth measurements computed by the server.
    ///
    /// See [\[MS-RDPBCGR\] 2.2.14.1.5].
    ///
    /// [\[MS-RDPBCGR\] 2.2.14.1.5]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/228ffc5c-b60c-4d3e-9781-ac613f822fdf
    AutoDetect(AutoDetectRequest),
    /// Server Auto-Reconnect Cookie ([\[MS-RDPBCGR\] 2.2.4.2]), received in a Save
    /// Session Info PDU.
    ///
    /// Hold this and pass it to `ClientConnector::with_auto_reconnect_cookie` when
    /// reconnecting after an ungraceful disconnect, so the server can reattach the
    /// session without a fresh logon. It can arrive more than once per session,
    /// since the server regenerates it hourly; keep the most recent.
    ///
    /// [\[MS-RDPBCGR\] 2.2.4.2]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/18f4f605-0ee3-4175-8a62-cf8775252547
    AutoReconnectCookie(ServerAutoReconnect),
    /// Server rejected the automatic reconnection attempt.
    AutoReconnectFailed,
}

impl TryFrom<x224::ProcessorOutput> for ActiveStageOutput {
    type Error = SessionError;

    fn try_from(value: x224::ProcessorOutput) -> Result<Self, Self::Error> {
        match value {
            x224::ProcessorOutput::ResponseFrame(frame) => Ok(Self::ResponseFrame(frame)),
            x224::ProcessorOutput::Disconnect(desc) => {
                let desc = match desc {
                    x224::DisconnectDescription::McsDisconnect(reason) => match reason {
                        mcs::DisconnectReason::ProviderInitiated => GracefulDisconnectReason::ServerInitiated,
                        mcs::DisconnectReason::UserRequested => GracefulDisconnectReason::UserInitiated,
                        other => GracefulDisconnectReason::Other(other.description().to_owned()),
                    },
                    x224::DisconnectDescription::ErrorInfo(info) => GracefulDisconnectReason::Other(info.description()),
                };

                Ok(Self::Terminate(desc))
            }
            x224::ProcessorOutput::SaveSessionInfo { logon_complete } => Ok(Self::SaveSessionInfo { logon_complete }),
            x224::ProcessorOutput::DeactivateAll => Ok(Self::DeactivateAll),
            x224::ProcessorOutput::MultitransportRequest(pdu) => Ok(Self::MultitransportRequest(pdu)),
            x224::ProcessorOutput::AutoDetect(request) => Ok(Self::AutoDetect(request)),
            x224::ProcessorOutput::AutoReconnectCookie(cookie) => Ok(Self::AutoReconnectCookie(cookie)),
            x224::ProcessorOutput::AutoReconnectFailed => Ok(Self::AutoReconnectFailed),
            x224::ProcessorOutput::MonitorLayout(monitors) => Ok(Self::MonitorLayout(monitors)),
            // GraphicsUpdate and PointerUpdate are consumed in ActiveStage::process()
            // before reaching this conversion.
            x224::ProcessorOutput::GraphicsUpdate(_) | x224::ProcessorOutput::PointerUpdate(_) => Err(
                SessionError::general("slow-path graphics/pointer updates should be handled before this conversion"),
            ),
        }
    }
}

/// Reasons for graceful disconnect. This type provides GUI-friendly descriptions for
/// disconnect reasons.
#[derive(Debug, Clone)]
pub enum GracefulDisconnectReason {
    UserInitiated,
    ServerInitiated,
    Other(String),
}

impl GracefulDisconnectReason {
    pub fn description(&self) -> String {
        match self {
            GracefulDisconnectReason::UserInitiated => "user initiated disconnect".to_owned(),
            GracefulDisconnectReason::ServerInitiated => "server initiated disconnect".to_owned(),
            GracefulDisconnectReason::Other(description) => description.clone(),
        }
    }
}

impl core::fmt::Display for GracefulDisconnectReason {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.description())
    }
}

/// Parse and process a slow-path graphics update through the shared bitmap pipeline.
fn process_slow_path_graphics(
    fast_path_processor: &mut fast_path::Processor,
    image: &mut DecodedImage,
    window_support_level: Option<WindowSupportLevel>,
    data: &[u8],
) -> SessionResult<(Vec<UpdateKind>, Option<Vec<u8>>)> {
    let mut src = ReadCursor::new(data);
    let update_type = slow_path::read_graphics_update_type(&mut src).map_err(SessionError::decode)?;

    match update_type {
        GraphicsUpdateType::Bitmap => {
            let bitmap = slow_path::decode_slow_path_bitmap(&mut src).map_err(SessionError::decode)?;
            fast_path_processor
                .process_bitmap_update(image, bitmap)
                .map(|updates| (updates, None))
        }
        GraphicsUpdateType::Orders => {
            let Some(window_support_level) = window_support_level else {
                return Ok((Vec::new(), None));
            };
            let orders = try_decode_slow_path_windowing_orders(&mut src).map_err(SessionError::decode)?;
            validate_windowing_orders_support(&orders, window_support_level)?;
            Ok((Vec::new(), Some(data.to_vec())))
        }
        GraphicsUpdateType::Palette => {
            fast_path_processor.process_palette_update(data);
            Ok((Vec::new(), None))
        }
        // Synchronize is an artifact from the T.128 multipoint protocol
        // and carries no data. Safe to ignore.
        GraphicsUpdateType::Synchronize => {
            debug!("Ignoring slow-path synchronize update");
            Ok((Vec::new(), None))
        }
    }
}

fn process_fast_path_windowing_orders(
    window_support_level: Option<WindowSupportLevel>,
    data: &[u8],
) -> SessionResult<Option<Vec<u8>>> {
    let Some(window_support_level) = window_support_level else {
        return Ok(None);
    };

    let mut src = ReadCursor::new(data);
    let orders = try_decode_fast_path_windowing_orders(&mut src).map_err(SessionError::decode)?;
    validate_windowing_orders_support(&orders, window_support_level)?;

    let mut normalized = Vec::with_capacity(
        2 /* updateType */ + 2 /* pad2OctetsA */ + data.len() + 2, /* pad2OctetsB */
    );
    normalized.extend_from_slice(&0u16.to_le_bytes());
    normalized.extend_from_slice(&0u16.to_le_bytes());
    normalized.extend_from_slice(&data[..2]);
    normalized.extend_from_slice(&0u16.to_le_bytes());
    normalized.extend_from_slice(&data[2..]);
    Ok(Some(normalized))
}

fn validate_windowing_orders_support(
    orders: &WindowingOrdersUpdate<'_>,
    window_support_level: WindowSupportLevel,
) -> SessionResult<()> {
    if window_support_level == WindowSupportLevel::SupportedEx
        || !orders.orders.iter().any(|order| order.requires_extended_support())
    {
        return Ok(());
    }

    Err(SessionError::general(
        "received extended window order fields without negotiated extended window support",
    ))
}

/// Parse and process a slow-path pointer update through the shared pointer pipeline.
fn process_slow_path_pointer(
    fast_path_processor: &mut fast_path::Processor,
    image: &mut DecodedImage,
    data: &[u8],
) -> SessionResult<Vec<UpdateKind>> {
    let mut src = ReadCursor::new(data);
    let pointer = slow_path::decode_slow_path_pointer(&mut src).map_err(SessionError::decode)?;
    fast_path_processor.process_pointer_update(image, pointer)
}

#[cfg(test)]
mod tests {
    use rat_rdp_core::Decode as _;
    use rat_rdp_graphics::image_processing::PixelFormat;
    use rat_rdp_pdu::gcc::MonitorFlags;
    use rat_rdp_pdu::input::fast_path::KeyboardFlags;
    use rat_rdp_pdu::pointer::{ColorPointerAttribute, Point16, PointerAttribute, PointerUpdateData};

    use super::*;

    #[test]
    fn full_redraw_prefers_suppress_output_toggle_when_supported() {
        let stage = ActiveStageBuilder {
            static_channels: StaticChannelSet::new(),
            user_channel_id: 1001,
            io_channel_id: 1003,
            message_channel_id: None,
            share_id: 1,
            compression_type: None,
            enable_server_pointer: true,
            pointer_software_rendering: false,
        }
        .build();

        let suppress_output_frames = stage.request_full_redraw(1024, 768, true, true).unwrap();
        assert_eq!(suppress_output_frames.len(), 2);
        assert!(suppress_output_frames.iter().all(|frame| !frame.is_empty()));

        assert_eq!(stage.request_full_redraw(1024, 768, true, false).unwrap().len(), 1);
        assert!(stage.request_full_redraw(1024, 768, false, false).unwrap().is_empty());
    }

    #[test]
    fn fastpath_input_splits_at_event_limit() {
        let mut stage = ActiveStageBuilder {
            static_channels: StaticChannelSet::new(),
            user_channel_id: 1001,
            io_channel_id: 1003,
            message_channel_id: None,
            share_id: 1,
            compression_type: None,
            enable_server_pointer: false,
            pointer_software_rendering: false,
        }
        .build();
        let mut image = DecodedImage::new(PixelFormat::RgbA32, 1, 1);
        let events = (0..=u8::MAX)
            .map(|code| FastPathInputEvent::UnicodeKeyboardEvent(KeyboardFlags::empty(), u16::from(code)))
            .collect::<Vec<_>>();

        let output = stage.process_fastpath_input(&mut image, &events).unwrap();
        let input_frames = output
            .into_iter()
            .map(|output| {
                let ActiveStageOutput::ResponseFrame(frame) = output else {
                    panic!("expected a fast-path input frame");
                };
                FastPathInput::decode(&mut ReadCursor::new(&frame)).unwrap()
            })
            .collect::<Vec<_>>();

        assert_eq!(
            input_frames
                .iter()
                .map(|input| input.input_events().len())
                .collect::<Vec<_>>(),
            [FastPathInput::MAX_EVENTS, 1]
        );
        assert_eq!(
            input_frames
                .iter()
                .flat_map(FastPathInput::input_events)
                .collect::<Vec<_>>(),
            events.iter().collect::<Vec<_>>()
        );
    }

    #[test]
    fn monitor_layout_is_forwarded_from_x224() {
        let monitors = vec![Monitor {
            left: 0,
            top: 0,
            right: 799,
            bottom: 599,
            flags: MonitorFlags::PRIMARY,
        }];

        let output = ActiveStageOutput::try_from(x224::ProcessorOutput::MonitorLayout(monitors.clone()))
            .expect("monitor layout should be forwarded from X.224");

        let ActiveStageOutput::MonitorLayout(actual) = output else {
            panic!("expected a monitor layout output");
        };
        assert_eq!(actual, monitors);
    }

    #[test]
    fn slow_path_palette_applies_to_indexed_pointer() {
        let mut palette_data = vec![0; 8 + 256 * 3];
        palette_data[0..2].copy_from_slice(&0x0002u16.to_le_bytes());
        palette_data[4..8].copy_from_slice(&256u32.to_le_bytes());
        palette_data[8 + 3..8 + 6].copy_from_slice(&[0x10, 0x20, 0x30]);

        let mut processor = fast_path::ProcessorBuilder {
            io_channel_id: 0,
            user_channel_id: 0,
            share_id: 0,
            enable_server_pointer: true,
            pointer_software_rendering: false,
        }
        .build();
        let mut image = DecodedImage::new(PixelFormat::RgbA32, 1, 1);

        let (palette_updates, windowing_orders) =
            process_slow_path_graphics(&mut processor, &mut image, None, &palette_data)
                .expect("slow-path palette update should succeed");
        assert!(palette_updates.is_empty());
        assert!(windowing_orders.is_none());

        let pointer = PointerAttribute {
            xor_bpp: 8,
            color_pointer: ColorPointerAttribute {
                cache_index: 0,
                hot_spot: Point16 { x: 0, y: 0 },
                width: 1,
                height: 1,
                xor_mask: &[1, 0],
                and_mask: &[0, 0],
            },
        };
        let pointer_updates = processor
            .process_pointer_update(&mut image, PointerUpdateData::New(pointer))
            .expect("indexed pointer should decode with slow-path palette");

        let [UpdateKind::PointerBitmap(pointer)] = pointer_updates.as_slice() else {
            panic!("expected an accelerated pointer bitmap");
        };
        assert_eq!(pointer.bitmap_data, [0x10, 0x20, 0x30, 0xff]);
    }

    fn window_order(fields_present: u32) -> Vec<u8> {
        let mut order = Vec::new();
        order.push(0x2e);
        let client_area_size = (fields_present & 0x0001_0000 != 0).then_some([0; 8]);
        let order_size: u16 = if client_area_size.is_some() { 19 } else { 11 };
        order.extend_from_slice(&order_size.to_le_bytes());
        order.extend_from_slice(&fields_present.to_le_bytes());
        order.extend_from_slice(&7u32.to_le_bytes());
        if let Some(client_area_size) = client_area_size {
            order.extend_from_slice(&client_area_size);
        }
        order
    }

    fn slow_path_orders_update(order: &[u8]) -> Vec<u8> {
        let mut update = Vec::new();
        update.extend_from_slice(&0u16.to_le_bytes());
        update.extend_from_slice(&0u16.to_le_bytes());
        update.extend_from_slice(&1u16.to_le_bytes());
        update.extend_from_slice(&0u16.to_le_bytes());
        update.extend_from_slice(order);
        update
    }

    #[test]
    fn slow_path_windowing_orders_require_negotiated_support() {
        let mut processor = fast_path::ProcessorBuilder {
            io_channel_id: 0,
            user_channel_id: 0,
            share_id: 0,
            enable_server_pointer: false,
            pointer_software_rendering: false,
        }
        .build();
        let mut image = DecodedImage::new(PixelFormat::RgbA32, 1, 1);
        let update = slow_path_orders_update(&window_order(0x2100_0000));

        let (_, orders) = process_slow_path_graphics(&mut processor, &mut image, None, &update).unwrap();
        assert!(orders.is_none());

        let (_, orders) =
            process_slow_path_graphics(&mut processor, &mut image, Some(WindowSupportLevel::Supported), &update)
                .unwrap();
        assert_eq!(orders.as_deref(), Some(update.as_slice()));
    }

    #[test]
    fn fast_path_windowing_orders_are_normalized_for_forwarding() {
        let order = window_order(0x2100_0000);
        let mut update = Vec::new();
        update.extend_from_slice(&1u16.to_le_bytes());
        update.extend_from_slice(&order);

        let normalized = process_fast_path_windowing_orders(Some(WindowSupportLevel::Supported), &update)
            .unwrap()
            .unwrap();
        assert_eq!(
            normalized,
            [
                0, 0, // updateType
                0, 0, // pad2OctetsA
                1, 0, // numberOrders
                0, 0, // pad2OctetsB
                0x2e, 11, 0, 0, 0, 0, 0x21, 7, 0, 0, 0,
            ]
        );
    }

    #[test]
    fn extended_windowing_orders_require_extended_support() {
        let update = slow_path_orders_update(&window_order(0x0101_0000));
        let mut processor = fast_path::ProcessorBuilder {
            io_channel_id: 0,
            user_channel_id: 0,
            share_id: 0,
            enable_server_pointer: false,
            pointer_software_rendering: false,
        }
        .build();
        let mut image = DecodedImage::new(PixelFormat::RgbA32, 1, 1);

        assert!(
            process_slow_path_graphics(&mut processor, &mut image, Some(WindowSupportLevel::Supported), &update)
                .is_err()
        );
        assert!(
            process_slow_path_graphics(
                &mut processor,
                &mut image,
                Some(WindowSupportLevel::SupportedEx),
                &update
            )
            .is_ok()
        );
    }
}