-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathcmd.rs
More file actions
1491 lines (1321 loc) · 51.6 KB
/
cmd.rs
File metadata and controls
1491 lines (1321 loc) · 51.6 KB
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::autocomplete::{self, Autocomplete, FileCompleter, FileCompleterOpts};
use crate::brush::BrushMode;
use crate::history::History;
use crate::parser::*;
use crate::platform;
use crate::session::{Direction, Input, Mode, PanState, Tool, VisualState};
use memoir::traits::Parse;
use memoir::*;
use crate::gfx::Rect;
use crate::gfx::Rgba8;
use std::fmt;
use std::path::Path;
pub const COMMENT: char = '-';
#[derive(Clone, PartialEq, Debug)]
pub enum Op {
Incr,
Decr,
Set(f32),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Axis {
Horizontal,
Vertical,
}
/// User command. Most of the interactions available to
/// the user are modeled as commands that are processed
/// by the session.
#[derive(PartialEq, Debug, Clone)]
pub enum Command {
// Brush
Brush,
BrushSet(BrushMode),
BrushToggle(BrushMode),
BrushSize(Op),
BrushUnset(BrushMode),
#[allow(dead_code)]
Crop(Rect<u32>),
ChangeDir(Option<String>),
Echo(Value),
// Files
Edit(Vec<String>),
EditFrames(Vec<String>),
Export(Option<u32>, String),
Write(Option<String>),
WriteFrames(Option<String>),
WriteQuit,
SaveAs(String),
Quit,
QuitAll,
ForceQuit,
ForceQuitAll,
Source(Option<String>),
// Frames
FrameAdd,
FrameClone(i32),
FrameRemove,
FramePrev,
FrameNext,
FrameResize(u32, u32),
// Palette
PaletteAdd(Rgba8),
PaletteClear,
PaletteGradient(Rgba8, Rgba8, usize),
PaletteSample,
PaletteSort,
PaletteWrite(String),
// Navigation
Pan(i32, i32),
Zoom(Op),
PaintColor(Rgba8, i32, i32),
PaintForeground(i32, i32),
PaintBackground(i32, i32),
PaintPalette(usize, i32, i32),
PaintLine(Rgba8, i32, i32, i32, i32),
// Selection
SelectionMove(i32, i32),
SelectionResize(i32, i32),
SelectionOffset(i32, i32),
SelectionExpand,
SelectionPaste,
SelectionYank,
SelectionCut,
SelectionFill(Option<Rgba8>),
SelectionErase,
SelectionJump(Direction),
SelectionFlip(Axis),
// Settings
Set(String, Value),
Toggle(String),
Reset,
Map(Box<KeyMapping>),
MapClear,
Slice(Option<usize>),
Fill(Option<Rgba8>),
SwapColors,
Mode(Mode),
Tool(Tool),
ToolPrev,
Undo,
Redo,
// View
ViewCenter,
ViewNext,
ViewPrev,
Noop,
}
impl Command {
pub fn repeats(&self) -> bool {
matches!(
self,
Self::Zoom(_)
| Self::BrushSize(_)
| Self::Pan(_, _)
| Self::Undo
| Self::Redo
| Self::ViewNext
| Self::ViewPrev
| Self::SelectionMove(_, _)
| Self::SelectionJump(_)
| Self::SelectionResize(_, _)
| Self::SelectionOffset(_, _)
)
}
}
impl fmt::Display for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Brush => write!(f, "Reset brush"),
Self::BrushSet(m) => write!(f, "Set brush mode to `{}`", m),
Self::BrushToggle(m) => write!(f, "Toggle `{}` brush mode", m),
Self::BrushSize(Op::Incr) => write!(f, "Increase brush size"),
Self::BrushSize(Op::Decr) => write!(f, "Decrease brush size"),
Self::BrushSize(Op::Set(s)) => write!(f, "Set brush size to {}", s),
Self::BrushUnset(m) => write!(f, "Unset brush `{}` mode", m),
Self::Crop(_) => write!(f, "Crop view"),
Self::ChangeDir(_) => write!(f, "Change the current working directory"),
Self::Echo(_) => write!(f, "Echo a value"),
Self::Edit(_) => write!(f, "Edit path(s)"),
Self::EditFrames(_) => write!(f, "Edit path(s) as animation frames"),
Self::Fill(Some(c)) => write!(f, "Fill view with {color}", color = c),
Self::Fill(None) => write!(f, "Fill view with background color"),
Self::ForceQuit => write!(f, "Quit view without saving"),
Self::ForceQuitAll => write!(f, "Quit all views without saving"),
Self::Map(_) => write!(f, "Map a key combination to a command"),
Self::MapClear => write!(f, "Clear all key mappings"),
Self::Mode(Mode::Help) => write!(f, "Toggle help"),
Self::Mode(m) => write!(f, "Switch to {} mode", m),
Self::FrameAdd => write!(f, "Add a blank frame to the view"),
Self::FrameClone(i) => write!(f, "Clone frame {} and add it to the view", i),
Self::FrameRemove => write!(f, "Remove the last frame of the view"),
Self::FramePrev => write!(f, "Navigate to previous frame"),
Self::FrameNext => write!(f, "Navigate to next frame"),
Self::Noop => write!(f, "No-op"),
Self::PaletteAdd(c) => write!(f, "Add {color} to palette", color = c),
Self::PaletteClear => write!(f, "Clear palette"),
Self::PaletteGradient(cs, ce, n) => write!(
f,
"Create {} colors gradient from {} to {}",
number = n,
colorstart = cs,
colorend = ce
),
Self::PaletteSample => write!(f, "Sample palette from view"),
Self::PaletteSort => write!(f, "Sort palette colors"),
Self::Pan(x, 0) if *x > 0 => write!(f, "Pan workspace right"),
Self::Pan(x, 0) if *x < 0 => write!(f, "Pan workspace left"),
Self::Pan(0, y) if *y > 0 => write!(f, "Pan workspace up"),
Self::Pan(0, y) if *y < 0 => write!(f, "Pan workspace down"),
Self::Pan(x, y) => write!(f, "Pan workspace by {},{}", x, y),
Self::Quit => write!(f, "Quit active view"),
Self::QuitAll => write!(f, "Quit all views"),
Self::Redo => write!(f, "Redo view edit"),
Self::FrameResize(_, _) => write!(f, "Resize active view frame"),
Self::Tool(Tool::Pan(_)) => write!(f, "Pan tool"),
Self::Tool(Tool::Brush) => write!(f, "Brush tool"),
Self::Tool(Tool::Sampler) => write!(f, "Color sampler tool"),
Self::Tool(Tool::FloodFill) => write!(f, "Flood fill tool"),
Self::ToolPrev => write!(f, "Switch to previous tool"),
Self::Set(s, v) => write!(f, "Set {setting} to {val}", setting = s, val = v),
Self::Slice(Some(n)) => write!(f, "Slice view into {} frame(s)", n),
Self::Slice(None) => write!(f, "Reset view slices"),
Self::Source(_) => write!(f, "Source an rx script (eg. a palette)"),
Self::SwapColors => write!(f, "Swap foreground & background colors"),
Self::Toggle(s) => write!(f, "Toggle {setting} on/off", setting = s),
Self::Undo => write!(f, "Undo view edit"),
Self::ViewCenter => write!(f, "Center active view"),
Self::ViewNext => write!(f, "Go to next view"),
Self::ViewPrev => write!(f, "Go to previous view"),
Self::Write(None) => write!(f, "Write view to disk"),
Self::Write(Some(_)) => write!(f, "Write view to disk as..."),
Self::WriteQuit => write!(f, "Write view to disk and quit"),
Self::SaveAs(_) => write!(f, "Change view name and write view to disk as..."),
Self::Zoom(Op::Incr) => write!(f, "Zoom in view"),
Self::Zoom(Op::Decr) => write!(f, "Zoom out view"),
Self::Zoom(Op::Set(z)) => write!(f, "Set view zoom to {:.1}", z),
Self::Reset => write!(f, "Reset all settings to default"),
Self::SelectionFill(None) => write!(f, "Fill selection with foreground color"),
Self::SelectionYank => write!(f, "Yank (copy) selection"),
Self::SelectionCut => write!(f, "Cut selection"),
Self::SelectionPaste => write!(f, "Paste selection"),
Self::SelectionExpand => write!(f, "Expand selection to frame"),
Self::SelectionOffset(1, 1) => write!(f, "Outset selection"),
Self::SelectionOffset(-1, -1) => write!(f, "Inset selection"),
Self::SelectionOffset(x, y) => write!(f, "Offset selection by {:2},{:2}", x, y),
Self::SelectionMove(x, 0) if *x > 0 => write!(f, "Move selection right"),
Self::SelectionMove(x, 0) if *x < 0 => write!(f, "Move selection left"),
Self::SelectionMove(0, y) if *y > 0 => write!(f, "Move selection up"),
Self::SelectionMove(0, y) if *y < 0 => write!(f, "Move selection down"),
Self::SelectionJump(Direction::Forward) => {
write!(f, "Move selection forward by one frame")
}
Self::SelectionJump(Direction::Backward) => {
write!(f, "Move selection backward by one frame")
}
Self::SelectionErase => write!(f, "Erase selection contents"),
Self::SelectionFlip(Axis::Horizontal) => write!(f, "Flip selection horizontally"),
Self::SelectionFlip(Axis::Vertical) => write!(f, "Flip selection vertically"),
Self::PaintColor(_, x, y) => write!(f, "Paint {:2},{:2}", x, y),
_ => write!(f, "..."),
}
}
}
impl From<Command> for String {
fn from(cmd: Command) -> Self {
match cmd {
Command::Brush => format!("brush"),
Command::BrushSet(m) => format!("brush/set {}", m),
Command::BrushSize(Op::Incr) => format!("brush/size +"),
Command::BrushSize(Op::Decr) => format!("brush/size -"),
Command::BrushSize(Op::Set(s)) => format!("brush/size {}", s),
Command::BrushUnset(m) => format!("brush/unset {}", m),
Command::Echo(_) => unimplemented!(),
Command::Edit(_) => unimplemented!(),
Command::Fill(Some(c)) => format!("v/fill {}", c),
Command::Fill(None) => format!("v/fill"),
Command::ForceQuit => format!("q!"),
Command::ForceQuitAll => format!("qa!"),
Command::Map(_) => format!("map <key> <command> {{<command>}}"),
Command::Mode(m) => format!("mode {}", m),
Command::FrameAdd => format!("f/add"),
Command::FrameClone(i) => format!("f/clone {}", i),
Command::FrameRemove => format!("f/remove"),
Command::Export(None, path) => format!("export {}", path),
Command::Export(Some(s), path) => format!("export @{}x {}", s, path),
Command::Noop => format!(""),
Command::PaletteAdd(c) => format!("p/add {}", c),
Command::PaletteClear => format!("p/clear"),
Command::PaletteWrite(_) => format!("p/write"),
Command::PaletteSample => format!("p/sample"),
Command::PaletteGradient(cs, ce, n) => format!("p/gradient {} {} {}", cs, ce, n),
Command::Pan(x, y) => format!("pan {} {}", x, y),
Command::Quit => format!("q"),
Command::Redo => format!("redo"),
Command::FrameResize(w, h) => format!("f/resize {} {}", w, h),
Command::Set(s, v) => format!("set {} = {}", s, v),
Command::Slice(Some(n)) => format!("slice {}", n),
Command::Slice(None) => format!("slice"),
Command::Source(Some(path)) => format!("source {}", path),
Command::SwapColors => format!("swap"),
Command::Toggle(s) => format!("toggle {}", s),
Command::Undo => format!("undo"),
Command::ViewCenter => format!("v/center"),
Command::ViewNext => format!("v/next"),
Command::ViewPrev => format!("v/prev"),
Command::Write(None) => format!("w"),
Command::Write(Some(path)) => format!("w {}", path),
Command::WriteQuit => format!("wq"),
Command::SaveAs(path) => format!("saveas {}", path),
Command::Zoom(Op::Incr) => format!("v/zoom +"),
Command::Zoom(Op::Decr) => format!("v/zoom -"),
Command::Zoom(Op::Set(z)) => format!("v/zoom {}", z),
_ => unimplemented!(),
}
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(PartialEq, Debug, Clone)]
pub struct KeyMapping {
pub input: Input,
pub press: Command,
pub release: Option<Command>,
pub modes: Vec<Mode>,
}
impl KeyMapping {
pub fn parser(modes: &[Mode]) -> Parser<KeyMapping> {
let modes = modes.to_vec();
// Prevent stack overflow.
let press = Parser::new(
move |input| Commands::default().parser().parse(input),
"<cmd>",
);
// Prevent stack overflow.
let release = Parser::new(
move |input| {
if let Some(i) = input.bytes().position(|c| c == b'}') {
match Commands::default().parser().parse(&input[..i]) {
Ok((cmd, rest)) if rest.is_empty() => Ok((cmd, &input[i..])),
Ok((_, rest)) => {
Err((format!("expected {:?}, got {:?}", '}', rest).into(), rest))
}
Err(err) => Err(err),
}
} else {
Err(("unclosed '{' delimiter".into(), input))
}
},
"<cmd>",
);
let character = between('\'', '\'', character())
.map(Input::Character)
.skip(whitespace())
.then(press.clone())
.map(|(input, press)| ((input, press), None));
let key = param::<platform::Key>()
.map(Input::Key)
.skip(whitespace())
.then(press)
.skip(optional(whitespace()))
.then(optional(between('{', '}', release)));
character
.or(key)
.map(move |((input, press), release)| KeyMapping {
input,
press,
release,
modes: modes.clone(),
})
.label("<key> <cmd>") // TODO: We should provide the full command somehow.
}
}
////////////////////////////////////////////////////////////////////////////////
#[derive(Clone, PartialEq, Debug)]
pub enum Value {
Bool(bool),
U32(u32),
U32Tuple(u32, u32),
F32Tuple(f32, f32),
F64(f64),
Str(String),
Ident(String),
Rgba8(Rgba8),
}
impl Value {
pub fn is_set(&self) -> bool {
if let Value::Bool(b) = self {
return *b;
}
panic!("expected {:?} to be a `bool`", self);
}
pub fn to_f64(&self) -> f64 {
if let Value::F64(n) = self {
return *n;
}
panic!("expected {:?} to be a `float`", self);
}
pub fn to_u64(&self) -> u64 {
if let Value::U32(n) = self {
return *n as u64;
}
panic!("expected {:?} to be a `uint`", self);
}
pub fn to_rgba8(&self) -> Rgba8 {
if let Value::Rgba8(rgba8) = self {
return *rgba8;
}
panic!("expected {:?} to be a `Rgba8`", self);
}
pub fn description(&self) -> &'static str {
match self {
Self::Bool(_) => "on / off",
Self::U32(_) => "positive integer, eg. 32",
Self::F64(_) => "float, eg. 1.33",
Self::U32Tuple(_, _) => "two positive integers, eg. 32, 48",
Self::F32Tuple(_, _) => "two floats , eg. 32.17, 48.29",
Self::Str(_) => "string, eg. \"fnord\"",
Self::Rgba8(_) => "color, eg. #ffff00",
Self::Ident(_) => "identifier, eg. fnord",
}
}
}
impl From<Value> for (u32, u32) {
fn from(other: Value) -> (u32, u32) {
if let Value::U32Tuple(x, y) = other {
return (x, y);
}
panic!("expected {:?} to be a `(u32, u32)`", other);
}
}
impl From<Value> for f32 {
fn from(other: Value) -> f32 {
if let Value::F64(x) = other {
return x as f32;
}
panic!("expected {:?} to be a `f64`", other);
}
}
impl From<Value> for f64 {
fn from(other: Value) -> f64 {
if let Value::F64(x) = other {
return x as f64;
}
panic!("expected {:?} to be a `f64`", other);
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Bool(true) => "on".fmt(f),
Value::Bool(false) => "off".fmt(f),
Value::U32(u) => u.fmt(f),
Value::F64(x) => x.fmt(f),
Value::U32Tuple(x, y) => write!(f, "{},{}", x, y),
Value::F32Tuple(x, y) => write!(f, "{},{}", x, y),
Value::Str(s) => s.fmt(f),
Value::Rgba8(c) => c.fmt(f),
Value::Ident(i) => i.fmt(f),
}
}
}
impl Parse for Value {
fn parser() -> Parser<Self> {
let str_val = quoted().map(Value::Str).label("<string>");
let rgba8_val = color().map(Value::Rgba8);
let u32_tuple_val = tuple::<u32>(natural(), natural()).map(|(x, y)| Value::U32Tuple(x, y));
let u32_val = natural::<u32>().map(Value::U32);
let f64_tuple_val =
tuple::<f32>(rational(), rational()).map(|(x, y)| Value::F32Tuple(x, y));
let f64_val = rational::<f64>().map(Value::F64).label("0.0 .. 4096.0");
let bool_val = string("on")
.value(Value::Bool(true))
.or(string("off").value(Value::Bool(false)))
.label("on/off");
let ident_val = identifier().map(Value::Ident);
greediest(vec![
rgba8_val,
u32_tuple_val,
f64_tuple_val,
u32_val,
f64_val,
bool_val,
ident_val,
str_val,
])
.label("<value>")
}
}
////////////////////////////////////////////////////////////////////////////////
pub struct CommandLine {
/// The history of commands entered.
pub history: History,
/// Command auto-complete.
pub autocomplete: Autocomplete<CommandCompleter>,
/// Input cursor position.
pub cursor: usize,
/// Parser.
pub parser: Parser<Command>,
/// Commands.
pub commands: Commands,
/// The current input string displayed to the user.
input: String,
/// File extensions supported.
extensions: Vec<String>,
}
impl CommandLine {
const MAX_INPUT: usize = 256;
pub fn new<P: AsRef<Path>>(cwd: P, history_path: P, extensions: &[&str]) -> Self {
let cmds = Commands::default();
Self {
input: String::with_capacity(Self::MAX_INPUT),
cursor: 0,
parser: cmds.line_parser(),
commands: cmds,
history: History::new(history_path, 1024),
autocomplete: Autocomplete::new(CommandCompleter::new(cwd, extensions)),
extensions: extensions.iter().map(|e| (*e).into()).collect(),
}
}
pub fn set_cwd(&mut self, path: &Path) {
let exts: Vec<_> = self.extensions.iter().map(|s| s.as_str()).collect();
self.autocomplete = Autocomplete::new(CommandCompleter::new(path, exts.as_slice()));
}
pub fn parse(&self, input: &str) -> Result<Command, Error> {
match self.parser.parse(input) {
Ok((cmd, _)) => Ok(cmd),
Err((err, _)) => Err(err),
}
}
pub fn input(&self) -> String {
self.input.clone()
}
pub fn is_empty(&self) -> bool {
self.input.is_empty()
}
pub fn history_prev(&mut self) {
let prefix = self.prefix();
if let Some(entry) = self.history.prev(&prefix).map(str::to_owned) {
self.replace(&entry);
}
}
pub fn history_next(&mut self) {
let prefix = self.prefix();
if let Some(entry) = self.history.next(&prefix).map(str::to_owned) {
self.replace(&entry);
} else {
self.reset();
}
}
pub fn completion_next(&mut self) {
let prefix = self.prefix();
if let Some((completion, range)) = self.autocomplete.next(&prefix, self.cursor) {
// Replace old completion with new one.
self.cursor = range.start + completion.len();
self.input.replace_range(range, &completion);
}
}
pub fn cursor_backward(&mut self) -> Option<char> {
if let Some(c) = self.peek_back() {
let cursor = self.cursor - c.len_utf8();
// Don't allow deleting the `:` prefix of the command.
if c != ':' || cursor > 0 {
self.cursor = cursor;
self.autocomplete.invalidate();
return Some(c);
}
}
None
}
pub fn cursor_forward(&mut self) -> Option<char> {
if let Some(c) = self.input[self.cursor..].chars().next() {
self.cursor += c.len_utf8();
self.autocomplete.invalidate();
Some(c)
} else {
None
}
}
pub fn cursor_back(&mut self) {
if self.cursor > 1 {
self.cursor = 1;
self.autocomplete.invalidate();
}
}
pub fn cursor_front(&mut self) {
self.cursor = self.input.len();
}
pub fn putc(&mut self, c: char) {
if self.input.len() + c.len_utf8() > self.input.capacity() {
return;
}
self.input.insert(self.cursor, c);
self.cursor += c.len_utf8();
self.autocomplete.invalidate();
}
pub fn puts(&mut self, s: &str) {
// TODO: Check capacity.
self.input.push_str(s);
self.cursor += s.len();
self.autocomplete.invalidate();
}
pub fn delc(&mut self) {
match self.peek_back() {
// Don't allow deleting the ':' unless it's the last remaining character.
Some(c) if self.cursor > 1 || self.input.len() == 1 => {
self.cursor -= c.len_utf8();
self.input.remove(self.cursor);
self.autocomplete.invalidate();
}
_ => {}
}
}
pub fn clear(&mut self) {
self.cursor = 0;
self.input.clear();
self.history.reset();
self.autocomplete.invalidate();
}
////////////////////////////////////////////////////////////////////////////
fn replace(&mut self, s: &str) {
// We don't re-assign `input` here, because it
// has a fixed capacity we want to preserve.
self.input.clear();
self.input.push_str(s);
self.autocomplete.invalidate();
}
fn reset(&mut self) {
self.clear();
self.putc(':');
}
fn prefix(&self) -> String {
self.input[..self.cursor].to_owned()
}
#[cfg(test)]
fn peek(&self) -> Option<char> {
self.input[self.cursor..].chars().next()
}
fn peek_back(&self) -> Option<char> {
self.input[..self.cursor].chars().next_back()
}
}
pub struct Commands {
commands: Vec<(&'static str, &'static str, Parser<Command>)>,
}
impl Commands {
pub fn new() -> Self {
Self {
commands: vec![(
"#",
"Add color to palette",
color().map(Command::PaletteAdd),
)],
}
}
pub fn parser(&self) -> Parser<Command> {
use std::iter;
let noop = expect(|s| s.is_empty(), "<empty>").value(Command::Noop);
let commands = self.commands.iter().map(|(_, _, v)| v.clone());
let choices = commands.chain(iter::once(noop)).collect();
symbol(':')
.then(
choice(choices).or(peek(
until(hush(whitespace()).or(end()))
.try_map(|cmd| Err(format!("unknown command: {}", cmd))),
)),
)
.map(|(_, cmd)| cmd)
}
pub fn line_parser(&self) -> Parser<Command> {
self.parser()
.skip(optional(whitespace()))
.skip(optional(comment()))
.end()
}
pub fn iter(&self) -> impl Iterator<Item = &(&'static str, &'static str, Parser<Command>)> {
self.commands.iter()
}
///////////////////////////////////////////////////////////////////////////
fn command<F>(mut self, name: &'static str, help: &'static str, f: F) -> Self
where
F: Fn(Parser<String>) -> Parser<Command>,
{
let cmd = peek(
string(name)
.followed_by(hush(whitespace()) / end())
.skip(optional(whitespace())),
)
.label(name);
self.commands.push((name, help, f(cmd)));
self
}
}
impl Default for Commands {
fn default() -> Self {
Self::new()
.command("q", "Quit view", |p| p.value(Command::Quit))
.command("qa", "Quit all views", |p| p.value(Command::QuitAll))
.command("q!", "Force quit view", |p| p.value(Command::ForceQuit))
.command("qa!", "Force quit all views", |p| {
p.value(Command::ForceQuitAll)
})
.command("export", "Export view", |p| {
p.then(optional(scale().skip(whitespace())).then(path()))
.map(|(_, (scale, path))| Command::Export(scale, path))
})
.command("wq", "Write & quit view", |p| p.value(Command::WriteQuit))
.command("saveas", "Write and change view name", |p| {
p.then(path()).map(|(_, path)| Command::SaveAs(path))
})
.command("x", "Write & quit view", |p| p.value(Command::WriteQuit))
.command("w", "Write view", |p| {
p.then(optional(path()))
.map(|(_, path)| Command::Write(path))
})
.command("w/frames", "Write view as individual frames", |p| {
p.then(optional(path()))
.map(|(_, dir)| Command::WriteFrames(dir))
})
.command("e", "Edit path(s)", |p| {
p.then(paths()).map(|(_, paths)| Command::Edit(paths))
})
.command("e/frames", "Edit frames as view", |p| {
p.then(paths()).map(|(_, paths)| Command::EditFrames(paths))
})
.command("help", "Display help", |p| {
p.value(Command::Mode(Mode::Help))
})
.command("set", "Set setting to value", |p| {
p.then(setting())
.skip(optional(whitespace()))
.then(optional(
symbol('=')
.skip(optional(whitespace()))
.then(Value::parser())
.map(|(_, v)| v),
))
.map(|((_, k), v)| Command::Set(k, v.unwrap_or(Value::Bool(true))))
})
.command("unset", "Set setting to `off`", |p| {
p.then(setting())
.map(|(_, k)| Command::Set(k, Value::Bool(false)))
})
.command("toggle", "Toggle setting", |p| {
p.then(setting()).map(|(_, k)| Command::Toggle(k))
})
.command("echo", "Echo setting or value", |p| {
p.then(Value::parser()).map(|(_, v)| Command::Echo(v))
})
.command("slice", "Slice view into <n> frames", |p| {
p.then(optional(natural::<usize>().label("<n>")))
.map(|(_, n)| Command::Slice(n))
})
.command(
"source",
"Source an rx script (eg. palette or config)",
|p| p.then(optional(path())).map(|(_, p)| Command::Source(p)),
)
.command("cd", "Change current directory", |p| {
p.then(optional(path())).map(|(_, p)| Command::ChangeDir(p))
})
.command("zoom", "Zoom view", |p| {
p.then(
peek(rational::<f32>().label("<level>"))
.try_map(|z| {
if z >= 1.0 {
Ok(Command::Zoom(Op::Set(z)))
} else {
Err("zoom level must be >= 1.0")
}
})
.or(symbol('+')
.value(Command::Zoom(Op::Incr))
.or(symbol('-').value(Command::Zoom(Op::Decr)))
.or(fail("couldn't parse zoom parameter")))
.label("+/-"),
)
.map(|(_, cmd)| cmd)
})
.command("brush/size", "Set brush size", |p| {
p.then(
natural::<usize>()
.label("<size>")
.map(|z| Command::BrushSize(Op::Set(z as f32)))
.or(symbol('+')
.value(Command::BrushSize(Op::Incr))
.or(symbol('-').value(Command::BrushSize(Op::Decr)))
.or(fail("couldn't parse brush size parameter")))
.label("+/-"),
)
.map(|(_, cmd)| cmd)
})
.command(
"brush/set",
"Set brush mode, eg. `xsym` for x-symmetry",
|p| {
p.then(param::<BrushMode>())
.map(|(_, m)| Command::BrushSet(m))
},
)
.command("brush/unset", "Unset brush mode", |p| {
p.then(param::<BrushMode>())
.map(|(_, m)| Command::BrushUnset(m))
})
.command("brush/toggle", "Toggle brush mode", |p| {
p.then(param::<BrushMode>())
.map(|(_, m)| Command::BrushToggle(m))
})
.command("brush", "Switch to brush", |p| {
p.value(Command::Tool(Tool::Brush))
})
.command("flood", "Switch to flood fill tool", |p| {
p.value(Command::Tool(Tool::FloodFill))
})
.command("mode", "Set session mode, eg. `visual` or `normal`", |p| {
p.then(param::<Mode>()).map(|(_, m)| Command::Mode(m))
})
.command("visual", "Set session mode to visual", |p| {
p.map(|_| Command::Mode(Mode::Visual(VisualState::default())))
})
.command("sampler/off", "Switch the sampler tool off", |p| {
p.value(Command::ToolPrev)
})
.command("sampler", "Switch to the sampler tool", |p| {
p.value(Command::Tool(Tool::Sampler))
})
.command("v/next", "Activate the next view", |p| {
p.value(Command::ViewNext)
})
.command("v/prev", "Activate the previous view", |p| {
p.value(Command::ViewPrev)
})
.command("v/center", "Center the active view", |p| {
p.value(Command::ViewCenter)
})
.command("v/clear", "Clear the active view", |p| {
p.value(Command::Fill(Some(Rgba8::TRANSPARENT)))
})
.command("v/fill", "Fill the active view", |p| {
p.then(optional(color())).map(|(_, c)| Command::Fill(c))
})
.command("pan", "Switch to the pan tool", |p| {
p.then(tuple::<i32>(integer().label("<x>"), integer().label("<y>")))
.map(|(_, (x, y))| Command::Pan(x, y))
})
.command("map", "Map keys to a command in all modes", |p| {
p.then(KeyMapping::parser(&[
Mode::Normal,
Mode::Visual(VisualState::selecting()),
Mode::Visual(VisualState::Pasting),
]))
.map(|(_, km)| Command::Map(Box::new(km)))
})
.command("map/visual", "Map keys to a command in visual mode", |p| {
p.then(KeyMapping::parser(&[
Mode::Visual(VisualState::selecting()),
Mode::Visual(VisualState::Pasting),
]))
.map(|(_, km)| Command::Map(Box::new(km)))
})
.command("map/normal", "Map keys to a command in normal mode", |p| {
p.then(KeyMapping::parser(&[Mode::Normal]))
.map(|(_, km)| Command::Map(Box::new(km)))
})
.command("map/help", "Map keys to a command in help mode", |p| {
p.then(KeyMapping::parser(&[Mode::Help]))
.map(|(_, km)| Command::Map(Box::new(km)))
})
.command("map/clear!", "Clear all key mappings", |p| {
p.value(Command::MapClear)
})
.command("p/add", "Add a color to the palette", |p| {
p.then(color()).map(|(_, rgba)| Command::PaletteAdd(rgba))
})
.command("p/clear", "Clear the color palette", |p| {
p.value(Command::PaletteClear)
})
.command("p/gradient", "Add a gradient to the palette", |p| {
p.then(tuple::<Rgba8>(
color().label("<from>"),
color().label("<to>"),
))
.skip(whitespace())
.then(natural::<usize>().label("<count>"))
.map(|((_, (cs, ce)), n)| Command::PaletteGradient(cs, ce, n))
})
.command(
"p/sample",
"Sample palette colors from the active view",
|p| p.value(Command::PaletteSample),
)
.command("p/sort", "Sort the palette colors", |p| {
p.value(Command::PaletteSort)
})
.command("p/write", "Write the color palette to a file", |p| {
p.then(path()).map(|(_, path)| Command::PaletteWrite(path))
})
.command("undo", "Undo the last edit", |p| p.value(Command::Undo))
.command("redo", "Redo the last edit", |p| p.value(Command::Redo))
.command("f/add", "Add a blank frame to the active view", |p| {
p.value(Command::FrameAdd)
})
.command("f/clone", "Clone a frame and add it to the view", |p| {
p.then(optional(integer::<i32>().label("<index>")))
.map(|(_, index)| Command::FrameClone(index.unwrap_or(-1)))
})
.command(
"f/remove",
"Remove the last frame from the active view",
|p| p.value(Command::FrameRemove),
)
.command("f/prev", "Navigate to previous frame", |p| {
p.value(Command::FramePrev)
})
.command("f/next", "Navigate to next frame", |p| {
p.value(Command::FrameNext)
})
.command("f/resize", "Resize the active view frame(s)", |p| {
p.then(tuple::<u32>(
natural().label("<width>"),
natural().label("<height>"),
))
.map(|(_, (w, h))| Command::FrameResize(w, h))
})
.command("tool", "Switch tool", |p| {
p.then(word().label("pan/brush/sampler/.."))
.try_map(|(_, t)| match t.as_str() {
"pan" => Ok(Command::Tool(Tool::Pan(PanState::default()))),
"brush" => Ok(Command::Tool(Tool::Brush)),
"sampler" => Ok(Command::Tool(Tool::Sampler)),
_ => Err(format!("unknown tool {:?}", t)),
})
})
.command("tool/prev", "Switch to previous tool", |p| {
p.value(Command::ToolPrev)
})
.command("swap", "Swap foreground and background colors", |p| {
p.value(Command::SwapColors)
})
.command("reset!", "Reset all settings to defaults", |p| {
p.value(Command::Reset)
})
.command("selection/move", "Move selection", |p| {
p.then(tuple::<i32>(integer().label("<x>"), integer().label("<y>")))
.map(|(_, (x, y))| Command::SelectionMove(x, y))
})
.command("selection/resize", "Resize selection", |p| {
p.then(tuple::<i32>(integer().label("<x>"), integer().label("<y>")))
.map(|(_, (x, y))| Command::SelectionResize(x, y))
})
.command("selection/yank", "Yank/copy selection content", |p| {
p.value(Command::SelectionYank)
})
.command("selection/cut", "Cut selection content", |p| {
p.value(Command::SelectionCut)
})
.command("selection/paste", "Paste into selection", |p| {
p.value(Command::SelectionPaste)