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
// Copyright (c) 2022 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use crate::core::{error::Error, EmptyAsNone, FromXml, IntoXml};
use crate::ns::RTT;

generate_attribute!(
    /// Events for real-time text.
    Event, "event", {
        /// Begin a new real-time message.
        New => "new",

        /// Re-initialize the real-time message.
        Reset => "reset",

        /// Modify existing real-time message.
        Edit => "edit",

        /// Signals activation of real-time text.
        Init => "init",

        /// Signals deactivation of real-time text.
        Cancel => "cancel",
    }, Default = Edit
);

/// Supports the transmission of text, including key presses, and text block inserts.
#[derive(FromXml, IntoXml, Debug, PartialEq, Clone)]
#[xml(namespace = RTT, name = "t")]
pub struct Insert {
    /// Position in the message to start inserting from.  If None, this means to start from the
    /// end of the message.
    #[xml(attribute = "p")]
    pos: Option<u32>,

    /// Text to insert.
    #[xml(text(codec = EmptyAsNone))]
    text: Option<String>,
}

impl TryFrom<Action> for Insert {
    type Error = Error;

    fn try_from(action: Action) -> Result<Insert, Error> {
        match action {
            Action::Insert(insert) => Ok(insert),
            _ => Err(Error::ParseError("This is not an insert action.")),
        }
    }
}

fn one() -> u32 {
    1
}

/// Supports the behavior of backspace key presses.  Text is removed towards beginning of the
/// message.  This element is also used for all delete operations, including the backspace key, the
/// delete key, and text block deletes.
#[derive(FromXml, IntoXml, Debug, PartialEq, Clone)]
#[xml(namespace = RTT, name = "e")]
pub struct Erase {
    /// Position in the message to start erasing from.  If None, this means to start from the end
    /// of the message.
    #[xml(attribute = "p")]
    pub pos: Option<u32>,

    /// Amount of characters to erase, to the left.
    #[xml(attribute(name = "n", default = one))]
    pub num: u32,
}

impl TryFrom<Action> for Erase {
    type Error = Error;

    fn try_from(action: Action) -> Result<Erase, Error> {
        match action {
            Action::Erase(erase) => Ok(erase),
            _ => Err(Error::ParseError("This is not an erase action.")),
        }
    }
}

/// Allow for the transmission of intervals, between real-time text actions, to recreate the
/// pauses between key presses.
#[derive(FromXml, IntoXml, Debug, PartialEq, Clone)]
#[xml(namespace = RTT, name = "w")]
pub struct Wait {
    /// Amount of milliseconds to wait before the next action.
    #[xml(attribute = "n")]
    pub time: u32,
}

impl TryFrom<Action> for Wait {
    type Error = Error;

    fn try_from(action: Action) -> Result<Wait, Error> {
        match action {
            Action::Wait(wait) => Ok(wait),
            _ => Err(Error::ParseError("This is not a wait action.")),
        }
    }
}

/// Choice between the three possible actions.
#[derive(FromXml, IntoXml, Debug, PartialEq, Clone)]
pub enum Action {
    /// Insert text action.
    #[xml(transparent)]
    Insert(Insert),

    /// Erase text action.
    #[xml(transparent)]
    Erase(Erase),

    /// Wait action.
    #[xml(transparent)]
    Wait(Wait),
}

/// Element transmitted at regular interval by the sender client while a message is being composed.
#[derive(FromXml, IntoXml, Debug, PartialEq, Clone)]
#[xml(namespace = RTT, name = "rtt")]
pub struct Rtt {
    /// Counter to maintain synchronisation of real-time text.  Senders MUST increment this value
    /// by 1 for each subsequent edit to the same real-time message, including when appending new
    /// text.  Receiving clients MUST monitor this 'seq' value as a lightweight verification on the
    /// synchronization of real-time text messages.  The bounds of 'seq' is 31-bits, the range of
    /// positive values for a signed 32-bit integer.
    #[xml(attribute)]
    pub seq: u32,

    /// This attribute signals events for real-time text.
    #[xml(attribute(default))]
    pub event: Event,

    /// When editing a message using XEP-0308, this references the id of the message being edited.
    #[xml(attribute)]
    pub id: Option<String>,

    /// Vector of actions being transmitted by this element.
    #[xml(children)]
    pub actions: Vec<Action>,
}

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

    #[cfg(target_pointer_width = "32")]
    #[test]
    fn test_size() {
        assert_size!(Event, 1);
        assert_size!(Insert, 20);
        assert_size!(Erase, 12);
        assert_size!(Wait, 4);
        assert_size!(Action, 20);
        assert_size!(Rtt, 32);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn test_size() {
        assert_size!(Event, 1);
        assert_size!(Insert, 32);
        assert_size!(Erase, 12);
        assert_size!(Wait, 4);
        assert_size!(Action, 32);
        assert_size!(Rtt, 56);
    }

    #[test]
    fn simple() {
        let elem: Element = "<rtt xmlns='urn:xmpp:rtt:0' seq='0'/>".parse().unwrap();
        let rtt = Rtt::try_from(elem).unwrap();
        assert_eq!(rtt.seq, 0);
        assert_eq!(rtt.event, Event::Edit);
        assert_eq!(rtt.id, None);
        assert_eq!(rtt.actions.len(), 0);
    }

    #[test]
    fn sequence() {
        let elem: Element = "<rtt xmlns='urn:xmpp:rtt:0' seq='0' event='new'><t>Hello,</t><w n='50'/><e/><t>!</t></rtt>"
            .parse()
            .unwrap();

        let rtt = Rtt::try_from(elem).unwrap();
        assert_eq!(rtt.seq, 0);
        assert_eq!(rtt.event, Event::New);
        assert_eq!(rtt.id, None);

        let mut actions = rtt.actions.into_iter();
        assert_eq!(actions.len(), 4);

        let t: Insert = actions.next().unwrap().try_into().unwrap();
        assert_eq!(t.pos, None);
        assert_eq!(t.text, Some(String::from("Hello,")));

        let w: Wait = actions.next().unwrap().try_into().unwrap();
        assert_eq!(w.time, 50);

        let e: Erase = actions.next().unwrap().try_into().unwrap();
        assert_eq!(e.pos, None);
        assert_eq!(e.num, 1);

        let t: Insert = actions.next().unwrap().try_into().unwrap();
        assert_eq!(t.pos, None);
        assert_eq!(t.text, Some(String::from("!")));
    }
}