rm-lisa 0.3.2

A logging library for rem-verse, with support for inputs, tasks, and more.
Documentation
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
//! A transaction on the input state.
//!
//! A single transaction should be created, and operated on _per_ `read()`
//! call for wherever you're reading from. If you reuse a transaction, or
//! create one at a finer grained scale you _will_ notice issues when
//! processing multi character input sequences like shift-tab.

use crate::input::{
	autocomplete::AutocompleteProvider,
	history::HistoryProvider,
	stdin::{MultibyteCursorControl, state::raw::UnlockedStdinInputState},
};
use std::borrow::Cow;

/// A wrapper around a write lock, and doing batch processing of input state.
///
/// The goal of the transaction is to process a single data from a read call,
/// and produce all of the changes that happened, and events that might be
/// queued as a result of this transaction.
#[allow(clippy::struct_excessive_bools)]
pub struct InputStateTransaction<'lf> {
	/// The actual underlying write guard.
	locked: &'lf mut UnlockedStdinInputState,
	/// An append buffer that is used to track if we can fire off an append
	/// event, or a 'change' event.
	///
	/// To be more clear:
	///
	/// - If  this is `None`, and input has changed, CHANGE EVENT MUST BE
	///   FIRED.
	/// - If this is `Some`, then you can safely file an append event, or
	///   mass append event.
	append_buffer: Option<String>,
	/// If a cancel has been queued.
	cancel_is_queued: bool,
	/// If a clear screen event has been queued.
	clear_is_queued: bool,
	/// If a pause event has been queued.
	pause_is_queued: bool,
	/// If a start action has been queued.
	start_is_queued: bool,
	/// Used to track if a finish is queued.
	///
	/// - If this is `None`, then a finish is not queued.
	/// - If this is `Some`, then a finish is queued, and this is set to
	///   (`previous_autocomplete`, `input`).
	finish_queued: Option<(Option<String>, String)>,
	/// A multibyte cursor control character has occured.
	multibyte_queued: Option<MultibyteCursorControl>,
	/// Shift-Insert requires multiple bytes that all come in at once in order
	/// to detect.
	///
	/// This counter keeps how far along we are into a multibyte counter.
	multibyte_paste_counter: u8,
	/// Detect multibyte cursor control characters.
	///
	/// Those that start with `\u{1b}`, and `[` followed by more characters
	/// afterwards. This keeps track of those inputs.
	multibyte_cursor_counter: u8,
}

impl<'lf> InputStateTransaction<'lf> {
	/// Create a new transaction to star tprocessing inputs.
	#[must_use]
	pub(super) fn new(lock: &'lf mut UnlockedStdinInputState) -> Self {
		Self {
			locked: lock,
			append_buffer: Some(String::new()),
			cancel_is_queued: false,
			clear_is_queued: false,
			pause_is_queued: false,
			start_is_queued: false,
			finish_queued: None,
			multibyte_cursor_counter: 0,
			multibyte_paste_counter: 0,
			multibyte_queued: None,
		}
	}

	/// Mark that all of our processing has finished.
	///
	/// This will return an 'append' buffer (if one is present). This append
	/// buffer can be used to fire off append events, vs input change events.
	pub fn finished_processing(mut self) -> Option<String> {
		if self.locked.check_promote_history_buffer() {
			self.append_buffer = None;
		}
		self.append_buffer
	}

	/// Get the current cursor position in terms of characters.
	#[must_use]
	pub fn cursor_position(&self) -> usize {
		self.locked.cursor_position()
	}

	/// Attempt to move the cursor left by an amount.
	///
	/// Will return if the cursor actually moved in anyway.
	#[must_use]
	pub fn move_cursor_left(&mut self, amount: usize) -> bool {
		let did_move = self.locked.move_cursor_left(amount);
		if did_move {
			self.append_buffer = None;
		}
		did_move
	}

	/// Attempt to move the cursor right by an amount.
	///
	/// Will return if the cursor actually moved in anyway.
	#[must_use]
	pub fn move_cursor_right(&mut self, amount: usize) -> bool {
		let did_move = self.locked.move_cursor_right(amount);
		if did_move {
			self.append_buffer = None;
		}
		did_move
	}

	/// Get a reference to the current input buffer *WITH* autocomplete.
	#[must_use]
	pub fn current_input(&self) -> Cow<'_, str> {
		self.locked.buffer()
	}

	/// Get the last used completion index, and increment it by one.
	///
	/// Used to determine what autocomplete suggestion specifically we're using.
	#[must_use]
	pub fn get_last_completion_index(&mut self) -> Option<usize> {
		self.locked.get_last_completion_index()
	}

	/// Get the last used completion index, and decrement it by one.
	///
	/// Used to determine what autocomplete suggestion specifically we're using.
	#[must_use]
	pub fn get_previous_completion_index(&mut self) -> Option<usize> {
		self.locked.get_previous_completion_index()
	}

	/// Get the current input *WITHOUT* pending auto completes.
	#[must_use]
	pub fn uncompleted_input(&self) -> &str {
		self.locked.uncompleted_input()
	}

	/// Perform a backspace operation.
	pub fn backspace(&mut self) {
		let (was_previously_started, did_backspace) = self.locked.backspace();
		if was_previously_started && did_backspace {
			self.append_buffer = None;
		}
		if !was_previously_started && !did_backspace && self.locked.started() {
			_ = self.cancel();
		}
	}

	/// Perform a cancel operation and reset all our state.
	///
	/// Returning if we had previously started accepting inputs.
	#[must_use]
	pub fn cancel(&mut self) -> bool {
		self.cancel_is_queued = true;

		let had_started = self.locked.cancel();
		if !had_started && !self.start_is_queued {
			self.append_buffer = Some(String::new());
		}
		had_started
	}

	/// Process a user requesting that we clear the screen.
	pub fn clear(&mut self) {
		self.locked.promote_autocomplete_buffer();
		self.append_buffer = None;
		self.clear_is_queued = true;
	}

	/// Complete the current input, or mark it as 'finished'.
	///
	/// Will ignore empty completion events.
	pub fn complete(&mut self) {
		// Promote autocomplete incase inner locked is still autocompleted
		// last.
		let prev_autocomplete = self.append_buffer.take();
		self.append_buffer = Some(String::new());

		let completed = self.locked.complete();
		if !completed.is_empty() {
			_ = self.finish_queued.insert((prev_autocomplete, completed));
		}
	}

	/// Process a tab/shift-tab character, and potentially autocomplete input.
	pub fn tab_action(
		&mut self,
		autocomplete_provider: Option<&dyn AutocompleteProvider>,
		history_provider: Option<&dyn HistoryProvider>,
		do_insert_tab: bool,
		is_shift_tab: bool,
	) {
		if let Some(buff) = self.locked.history_search_buffer_mut().take() {
			self.locked.handle_new_autocomplete_suggestion(&buff);
			self.append_buffer = None;
			return;
		}

		let Some(ap) = autocomplete_provider else {
			if do_insert_tab {
				return self.new_character_action(' ', history_provider);
			}

			return;
		};

		if ap.can_autocomplete() {
			let completion_index = if is_shift_tab {
				self.get_previous_completion_index()
			} else {
				self.get_last_completion_index()
			};
			// Either a change, or a cursor change.
			self.append_buffer = None;

			let Some(ac_value) = ap.get_tab_completion(completion_index, self.uncompleted_input())
			else {
				if do_insert_tab {
					return self.new_character_action(' ', history_provider);
				}

				return;
			};

			if ac_value.is_empty() {
				if do_insert_tab {
					self.new_character_action(' ', history_provider);
				}
			} else {
				self.locked.handle_new_autocomplete_suggestion(&ac_value);
			}
		} else if do_insert_tab {
			self.new_character_action(' ', history_provider);
		}
	}

	/// Look up the previous command run in history, and set that as our new
	/// input.
	///
	/// Previous history action can be thought of as hitting the 'up arrow' once,
	/// and getitng the previous command that was run.
	pub fn previous_history_action(&mut self, history_provider: Option<&dyn HistoryProvider>) {
		let Some(hprovider) = history_provider else {
			return self.cancel_if_empty();
		};
		let next_index = self.locked.get_next_history_index();
		if let Some(history_item) = hprovider.get_previous_command(next_index) {
			let prev_buff_is_empty = self.locked.uncompleted_input().is_empty();
			let max_len = history_item.chars().count();
			if !prev_buff_is_empty && self.locked.original_uncompleted_history().is_none() {
				let to_save = self.locked.uncompleted_input().to_owned();
				self.locked.set_uncompleted_history(to_save);
			}
			self.locked.handle_new_buff_from_history(history_item);
			self.append_buffer = None;

			if !self.locked.started() {
				self.locked.mark_started();
				self.start_is_queued = true;
			}
			if prev_buff_is_empty {
				self.locked.set_cursor_position(max_len);
			}
		} else {
			self.cancel_if_empty();
		}
	}

	/// Look up the next command run in history, and set that as our new input.
	///
	/// Get the next item in history in the future (e.g. hitting the down arrow).
	pub fn next_history_action(&mut self, history_provider: Option<&dyn HistoryProvider>) {
		let Some(hprovider) = history_provider else {
			return self.cancel_if_empty();
		};
		let Some(next_index) = self.locked.get_previous_history_index() else {
			if let Some(value) = self.locked.take_original_uncompleted_history() {
				self.locked.handle_new_buff_from_history(value);
				self.append_buffer = None;
				return;
			}

			return self.cancel_if_empty();
		};

		if let Some(history_item) = hprovider.get_previous_command(next_index) {
			self.locked.handle_new_buff_from_history(history_item);
			self.append_buffer = None;

			if !self.locked.started() {
				self.locked.mark_started();
				self.start_is_queued = true;
			}
		} else if let Some(value) = self.locked.take_original_uncompleted_history() {
			self.locked.handle_new_buff_from_history(value);
			self.append_buffer = None;
		} else {
			self.cancel_if_empty();
		}
	}

	/// Start a history search action.
	pub fn start_history_search_action(&mut self, history: Option<&dyn HistoryProvider>) {
		self.locked.start_history_search_suggestions(history);
		self.append_buffer = None;
	}

	/// Process a user typing in a new character.
	pub fn new_character_action(
		&mut self,
		new_character: char,
		history: Option<&dyn HistoryProvider>,
	) {
		self.check_multibyte_paste(new_character);
		let did_multibyte = self.check_multibyte_u1b(new_character);

		let did_change;
		(self.start_is_queued, did_change) =
			self.locked.process(new_character, did_multibyte, history);
		if did_change {
			self.append_buffer = None;
		} else if let Some(buf) = self.append_buffer.as_mut() {
			buf.push(new_character);
		}
	}

	/// Process a user typing a lot of characters at once (e.g. from a clipboard).
	pub fn new_string_action(&mut self, data: &str, history: Option<&dyn HistoryProvider>) {
		let did_change;
		(self.start_is_queued, did_change) = self.locked.process_all(data, history);
		if did_change {
			self.append_buffer = None;
		} else if let Some(buf) = self.append_buffer.as_mut() {
			*buf += data;
		}
	}

	/// Process a Ctrl-U action which cuts all the content from the cursor to
	/// the beginning, and saves it.
	pub fn uwk_cursor_to_begin(&mut self) {
		if self.locked.uwk_cursor_to_begin() {
			self.append_buffer = None;
		}
	}

	/// Process a Ctrl-K action which cuts all the content from the cursor to
	/// the end, and saves it.
	pub fn uwk_cursor_to_end(&mut self) {
		if self.locked.uwk_cursor_to_end() {
			self.append_buffer = None;
		}
	}

	/// Process a Ctrl-W action which cuts out a current word from your cursor.
	pub fn uwk_cursor_word(&mut self) {
		if self.locked.uwk_cursor_word() {
			self.append_buffer = None;
		}
	}

	/// Paste in content form the UWK buffer.
	pub fn paste_uwk(&mut self) {
		if self.locked.paste_uwk() {
			self.append_buffer = None;
		}
	}

	/// Swap the last two characters on standard in, including whitespace.
	pub fn swap_last_two_characters(&mut self) {
		if self.locked.swap_last_two_characters() {
			self.append_buffer = None;
		}
	}

	/// Process a user requesting that we pause STDOUT/STDERR.
	pub fn pause_output(&mut self) {
		self.locked.promote_autocomplete_buffer();
		self.pause_is_queued = true;
	}

	/// Check if a cancel was triggered, and reset it's state.
	#[must_use]
	pub const fn did_trigger_cancel(&mut self) -> bool {
		let queued = self.cancel_is_queued;
		self.cancel_is_queued = false;
		queued
	}

	/// If someone has requested clearing a screening.
	#[must_use]
	pub const fn did_trigger_clear(&mut self) -> bool {
		let queued = self.clear_is_queued;
		self.clear_is_queued = false;
		queued
	}

	#[must_use]
	pub const fn did_trigger_pause(&mut self) -> bool {
		let queued = self.pause_is_queued;
		self.pause_is_queued = false;
		queued
	}

	/// Check if a multibyte-paste should be triggered.
	#[must_use]
	pub fn did_trigger_multibyte_paste(&mut self) -> bool {
		if self.multibyte_paste_counter == 9 {
			self.multibyte_paste_counter = 0;
			// We hit a multibyte paste! YAY!
			self.locked.pop_n(9);
			if let Some(ledger) = self.append_buffer.as_mut() {
				for _ in 0..9 {
					_ = ledger.pop();
				}
			}
			return true;
		}

		false
	}

	/// Check if a multibyte cursor control event occured.
	///
	/// This has to take an autocomplete provider because shift-tab
	/// can trigger autocomplete cycling.
	pub fn did_trigger_multibyte_cursor(
		&mut self,
		autocomplete_provider: Option<&dyn AutocompleteProvider>,
		history_provider: Option<&dyn HistoryProvider>,
		ansi_supported: bool,
	) -> Option<(bool, usize, Option<String>, usize)> {
		let event = self.multibyte_queued.take()?;

		match event {
			MultibyteCursorControl::ShiftTab => {
				self.locked.pop_n(3);
				if let Some(ledger) = self.append_buffer.as_mut() {
					for _ in 0..3 {
						_ = ledger.pop();
					}
				}

				self.tab_action(autocomplete_provider, history_provider, false, true);
			}
			MultibyteCursorControl::UpArrow => {
				self.locked.pop_n_promoting_autocomplete_buffer(3);
				if let Some(ledger) = self.append_buffer.as_mut() {
					for _ in 0..3 {
						_ = ledger.pop();
					}
				}

				self.previous_history_action(history_provider);
			}
			MultibyteCursorControl::DownArrow => {
				self.locked.pop_n_promoting_autocomplete_buffer(3);
				if let Some(ledger) = self.append_buffer.as_mut() {
					for _ in 0..3 {
						_ = ledger.pop();
					}
				}

				self.next_history_action(history_provider);
			}
			MultibyteCursorControl::LeftArrow | MultibyteCursorControl::RightArrow => {
				self.locked.pop_n_promoting_autocomplete_buffer(3);
				if let Some(ledger) = self.append_buffer.as_mut() {
					for _ in 0..3 {
						_ = ledger.pop();
					}
				}

				if ansi_supported {
					let org_append = self.append_buffer.take();
					let org_position = self.cursor_position();
					let move_left = matches!(event, MultibyteCursorControl::LeftArrow);
					let move_result = if move_left {
						self.locked.move_cursor_left(1)
					} else {
						self.locked.move_cursor_right(1)
					};
					return if move_result {
						self.append_buffer = Some(String::with_capacity(0));
						Some((move_left, 1, org_append, org_position))
					} else {
						None
					};
				}
			}
			MultibyteCursorControl::ShiftLeftArrow | MultibyteCursorControl::ShiftRightArrow => {
				self.locked.pop_n_promoting_autocomplete_buffer(6);
				if let Some(ledger) = self.append_buffer.as_mut() {
					for _ in 0..6 {
						_ = ledger.pop();
					}
				}

				if ansi_supported {
					let move_left = matches!(event, MultibyteCursorControl::ShiftLeftArrow);
					let cursor_move_amount =
						if let Some((start, end)) = self.locked.get_word_bounds_at_cursor() {
							if move_left {
								self.locked.cursor_position() - start
							} else {
								end - self.locked.cursor_position()
							}
						} else if move_left {
							self.locked.cursor_position()
						} else {
							self.locked.uncompleted_input().chars().count()
						};
					let move_result = if move_left {
						self.locked.move_cursor_left(cursor_move_amount)
					} else {
						self.locked.move_cursor_right(cursor_move_amount)
					};

					return if move_result {
						let org_append = self.append_buffer.take();
						self.append_buffer = Some(String::with_capacity(0));
						let org_position = self.cursor_position();
						Some((move_left, cursor_move_amount, org_append, org_position))
					} else {
						None
					};
				}
			}
		}

		self.multibyte_cursor_counter = 0;
		None
	}

	/// Check if a start was triggered, and reset it's state.
	#[must_use]
	pub fn did_trigger_start(&mut self) -> bool {
		let queued = self.start_is_queued;
		self.start_is_queued = false;
		queued
	}

	/// Check if a finish was triggered, and reset it's state.
	#[must_use]
	pub fn did_trigger_finish(&mut self) -> Option<(Option<String>, String)> {
		self.finish_queued.take()
	}

	/// Perform a cancellation if the buffer is currently empty.
	fn cancel_if_empty(&mut self) {
		if self.locked.buffer().is_empty() && self.locked.started() {
			_ = self.cancel();
		}
	}

	/// Check if a new character is part of a multibyte paste counter.
	fn check_multibyte_paste(&mut self, new_character: char) {
		if new_character == '\\' && self.multibyte_paste_counter == 0 {
			self.multibyte_paste_counter += 1;
		} else if self.multibyte_paste_counter > 0 {
			let do_reset = match self.multibyte_paste_counter {
				1 => new_character != '\\',
				2 => new_character != 'u',
				3 => new_character != '{',
				4 => new_character != '1',
				5 => new_character != 'b',
				6 => new_character != '}',
				7 => new_character != '[',
				8 => new_character != 'Z',
				_ => true,
			};

			if do_reset {
				self.multibyte_paste_counter = 0;
			} else {
				self.multibyte_paste_counter += 1;
			}
		}
	}

	/// Check for multibyte cursor counters returning if it was part of a
	/// multibyte character.
	fn check_multibyte_u1b(&mut self, new_character: char) -> bool {
		if new_character == '\u{1b}' && self.multibyte_cursor_counter == 0 {
			self.multibyte_cursor_counter += 1;
			true
		} else if self.multibyte_cursor_counter > 0 {
			let mut did_multibyte = true;
			let do_reset = match self.multibyte_cursor_counter {
				1 => {
					let should_reset = new_character != '[';
					if should_reset {
						did_multibyte = false;
					}
					should_reset
				}
				2 => match new_character {
					'A' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::UpArrow);
						true
					}
					'B' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::DownArrow);
						true
					}
					'C' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::RightArrow);
						true
					}
					'D' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::LeftArrow);
						true
					}
					'Z' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::ShiftTab);
						true
					}
					'1' => false,
					_ => {
						did_multibyte = false;
						true
					}
				},
				3 => {
					if new_character != ';' {
						did_multibyte = false;
					}
					false
				}
				4 => {
					if new_character != '2' {
						did_multibyte = false;
					}
					false
				}
				5 => match new_character {
					'C' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::ShiftRightArrow);
						true
					}
					'D' => {
						_ = self
							.multibyte_queued
							.insert(MultibyteCursorControl::ShiftLeftArrow);
						true
					}
					_ => {
						did_multibyte = false;
						true
					}
				},
				_ => {
					did_multibyte = false;
					true
				}
			};

			if do_reset {
				self.multibyte_cursor_counter = 0;
			} else {
				self.multibyte_cursor_counter += 1;
			}
			did_multibyte
		} else {
			false
		}
	}
}