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
use super::*;
use crate::walkers::*;
use failure::Error;
use oatie::doc::*;
use oatie::rtf::*;

pub fn init_caret(ctx: ActionContext) -> Result<Op<RtfSchema>, Error> {
    let mut walker = Walker::new(&ctx.doc);
    if !walker.goto_pos(0) {
        bail!("Could not insert first caret");
    }

    let mut writer = walker.to_writer();
    writer.add.begin();
    writer.add.close(caret_attrs(&ctx.client_id, true));
    writer.add.begin();
    writer.add.close(caret_attrs(&ctx.client_id, false));
    Ok(writer.exit_result())
}

/// Arrow keys move the caret.
pub fn caret_move(
    ctx: ActionContext,
    increase: bool,
    preserve_select: bool,
) -> Result<Op<RtfSchema>, Error> {
    Ok(ctx)
        .and_then(|ctx| {
            // If we aren't preserving the selection, collapse the anchor caret
            // to where the focus caret is.
            if !preserve_select {
                let op = caret_clear(&ctx, Pos::Anchor).unwrap_or_else(|_| Op::empty());
                ctx.apply(&op)
            } else {
                Ok(ctx)
            }
        })
        .and_then(|ctx| {
            let mut walker = ctx.get_walker(Pos::Focus)?;

            // Remove focus caret and move it to next position.
            let op = Op::transform_advance(
                &{
                    // First operation removes the caret.
                    let mut writer = walker.to_writer();
                    writer.del.begin();
                    writer.del.close();
                    writer.exit_result()
                },
                &{
                    // Move the walker to the new position.
                    if increase {
                        walker.next_char();
                    } else {
                        walker.back_char();
                    }

                    // Insert the carets.
                    let mut writer = walker.to_writer();
                    if !preserve_select {
                        writer.add.begin();
                        writer.add.close(caret_attrs(&ctx.client_id, false));
                    }
                    writer.add.begin();
                    writer.add.close(caret_attrs(&ctx.client_id, true));
                    writer.exit_result()
                },
            );

            ctx.apply(&op)
        })
        .map(|ctx| ctx.result())
}

// TODO make walker_left_word and walker_right_word methods of Walker itself?

// Find the next walker position after the current word.
fn walker_right_word(walker: &mut Walker<'_>) {
    walker.next_char();
    loop {
        match walker.doc().head() {
            Some(DocText(_, ref text)) => {
                if is_boundary_char(text.as_str().chars().next().unwrap()) {
                    break;
                } else {
                    walker.next_char();
                }
            }
            Some(DocGroup(ref attrs, _)) => {
                if let Attrs::Caret { .. } = attrs {
                    // guess we'll stop
                    break;
                }
            }
            None => {
                // guess we'll stop
                break;
            }
        }
    }
}

// Find the last walker position before the current word.
fn walker_left_word(walker: &mut Walker<'_>) {
    walker.back_char();
    loop {
        match walker.doc().unhead() {
            Some(DocText(_, ref text)) => {
                if is_boundary_char(text.as_str().chars().rev().next().unwrap()) {
                    break;
                } else {
                    walker.back_char();
                }
            }
            Some(DocGroup(ref attrs, _)) => {
                if let Attrs::Caret { .. } = attrs {
                    // guess we'll stop
                    break;
                }
            }
            None => {
                // guess we'll stop
                break;
            }
        }
    }
}

pub fn caret_word_select(
    ctx: &ActionContext,
    cur: &CurSpan,
) -> Result<Op<RtfSchema>, Error> {
    Ok(Op::transform_advance(
        &Op::transform_advance(
            &caret_clear(ctx, Pos::Anchor).unwrap_or_else(|_| Op::empty()),
            &caret_clear(ctx, Pos::Focus).unwrap_or_else(|_| Op::empty()),
        ),
        &Op::transform_advance(
            &{
                // Insert anchor before word.
                let mut walker = Walker::to_cursor(&ctx.doc, cur);
                walker_left_word(&mut walker);
                let mut writer = walker.to_writer();
                writer.add.begin();
                writer.add.close(caret_attrs(
                    &ctx.client_id,
                    false
                ));
                writer.exit_result()
            },
            &{
                // Insert focus after word.
                let mut walker = Walker::to_cursor(&ctx.doc, cur);
                walker_right_word(&mut walker);
                let mut writer = walker.to_writer();
                writer.add.begin();
                writer.add.close(caret_attrs(
                    &ctx.client_id,
                    true
                ));
                writer.exit_result()
            }
        ),
    ))
}


pub fn caret_word_move(
    ctx: ActionContext,
    increase: bool,
    preserve_select: bool,
) -> Result<Op<RtfSchema>, Error> {
    Ok(ctx)
        .and_then(|ctx| {
            // If we aren't preserving the selection, collapse the anchor caret
            // to where the focus caret is.
            if !preserve_select {
                let op = caret_clear(&ctx, Pos::Anchor).unwrap_or_else(|_| Op::empty());
                ctx.apply(&op)
            } else {
                Ok(ctx)
            }
        })
        .and_then(|ctx| {
            let mut walker = ctx.get_walker(Pos::Focus).expect("Expected a Focus caret");

            // First operation removes the caret.
            let mut writer = walker.to_writer();
            writer.del.begin();
            writer.del.close();
            let op_1 = writer.exit_result();

            // Walk backward to start or forward to end of word.
            if increase {
                walker_right_word(&mut walker);
            } else {
                walker_left_word(&mut walker);
            }

            // Second operation inserts the new caret.
            let mut writer = walker.to_writer();
            if !preserve_select {
                writer.add.begin();
                writer.add.close(caret_attrs(&ctx.client_id, false));
            }
            writer.add.begin();
            writer.add.close(caret_attrs(&ctx.client_id, true));
            let op_2 = writer.exit_result();

            // Return composed operations. Select proper order or otherwise composition
            // will be invalid.
            ctx.apply(&Op::transform_advance(&op_1, &op_2))
        })
        .map(|ctx| ctx.result())
}

pub fn caret_select_all(ctx: ActionContext) -> Result<Op<RtfSchema>, Error> {
    Ok(Op::transform_advance(
        &{
            Op::transform_advance(
                &{
                    // Delete focus caret.
                    caret_clear(&ctx, Pos::Focus).unwrap_or_else(|_| Op::empty())
                },
                &{
                    // Delete anchor caret.
                    caret_clear(&ctx, Pos::Anchor).unwrap_or_else(|_| Op::empty())
                },
            )
        },
        &{
            Op::transform_advance(
                &{
                    // Insert anchor caret at start.
                    let mut start = Walker::new(&ctx.doc);
                    start.goto_pos(0);

                    let mut writer = start.to_writer();
                    writer.add.begin();
                    writer.add.close(caret_attrs(&ctx.client_id, false));
                    writer.exit_result()
                },
                &{
                    // Insert focus caret at end.
                    let mut end = Walker::new(&ctx.doc);
                    end.goto_end();

                    let mut writer = end.to_writer();
                    writer.add.begin();
                    writer.add.close(caret_attrs(&ctx.client_id, true));
                    writer.exit_result()
                },
            )
        },
    ))
}

pub fn caret_block_move(ctx: ActionContext, increase: bool) -> Result<Op<RtfSchema>, Error> {
    let mut walker = ctx.get_walker(Pos::Focus).expect("Expected a Focus caret");

    // First operation removes the caret.
    let mut writer = walker.to_writer();
    writer.del.begin();
    writer.del.close();
    let op_1 = writer.exit_result();

    // Second operation inserts the new caret.
    if increase {
        if !walker.next_block() {
            return Ok(op!([], []));
        }
    } else {
        assert!(walker.back_block());
        let _ = walker.back_block(); // don't care
    }

    let mut writer = walker.to_writer();
    writer.add.begin();
    writer.add.close(caret_attrs(&ctx.client_id, false));
    writer.add.begin();
    writer.add.close(caret_attrs(&ctx.client_id, true));
    let op_2 = writer.exit_result();

    // Return composed operations. Select proper order or otherwise composition
    // will be invalid.
    Ok(Op::transform_advance(&op_1, &op_2))
}

// Delete a caret.
pub fn caret_clear_inner(walker: Walker<'_>) -> Result<Op<RtfSchema>, Error> {
    let mut writer = walker.to_writer();
    writer.del.begin();
    writer.del.close();
    Ok(writer.exit_result())
}

// Deletes a caret, returning its position.
pub fn caret_clear(ctx: &ActionContext, position: Pos) -> Result<Op<RtfSchema>, Error> {
    caret_clear_inner(ctx.get_walker(position)?)
}

pub fn cur_to_caret(ctx: &ActionContext, cur: &CurSpan, pos: Pos) -> Result<Op<RtfSchema>, Error> {
    Ok(Op::transform_advance(
        &{
            // First operation removes the caret.
            caret_clear(ctx, pos).unwrap_or_else(|_| Op::empty())
        },
        &{
            // Second operation inserts a new caret.
            let walker = Walker::to_cursor(&ctx.doc, cur);
            let mut writer = walker.to_writer();
            writer.add.begin();
            writer.add.close(caret_attrs(
                &ctx.client_id,
                if pos == Pos::Focus { true } else { false },
            ));
            writer.exit_result()
        },
    ))
}