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
//! # Hexdino
//!
//! A hex editor with vim like keybindings written in Rust.
#![doc(html_logo_url = "https://raw.githubusercontent.com/Luz/hexdino/master/logo.png")]
#![deny(trivial_casts)]
use std::io::prelude::*;
use std::fs::OpenOptions;
use std::io::SeekFrom;
use std::path::Path;
use std::error::Error;
use std::env;
use std::cmp;
mod draw;
use draw::draw;
use draw::get_absolute_draw_indices;
mod find;
use find::FindOptSubset;
extern crate ncurses;
use ncurses::*;
extern crate getopts;
use getopts::Options;
extern crate pest;
#[macro_use]
extern crate pest_derive;
use pest::Parser;
#[derive(Parser)]
#[grammar = "cmd.pest"]
struct IdentParser;
extern crate memmem;
use memmem::{Searcher, TwoWaySearcher};
#[derive(PartialEq, Copy, Clone)]
pub enum Cursorstate {
Leftnibble,
Rightnibble,
Asciichar,
}
fn main() {
const VERSION: &str = env!("CARGO_PKG_VERSION");
let mut buf = vec![];
let mut cursorpos: usize = 0;
let mut cstate: Cursorstate = Cursorstate::Leftnibble;
// 0 = display data from first line of file
let mut screenoffset: usize = 0;
const SPALTEN: usize = 16;
let mut command = String::new();
let mut lastcommand = String::new();
let mut debug = String::new();
// start ncursesw
initscr();
let screenheight = getmaxy(stdscr()) as usize;
// ctrl+z and fg works with this
cbreak();
noecho();
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
opts.optflag("v", "version", "print the version");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
endwin();
println!("{}", f.to_string());
println!("Usage: {} FILE [options]", program);
return;
}
};
if matches.opt_present("v") {
endwin();
println!("Version: {}", VERSION);
return;
}
if matches.opt_present("h") {
endwin();
println!("Usage: {} FILE [options]", program);
return;
}
if !has_colors() {
endwin();
println!("Your terminal does not support color!\n");
return;
}
let patharg = match matches.free.is_empty() {
true => String::new(),
false => matches.free[0].clone(),
};
let path = Path::new(&patharg);
if patharg.is_empty() {
endwin();
println!("Patharg is empty!\n");
return;
}
let mut file = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path) {
Err(why) => {
endwin();
println!("Could not open {}: {}", path.display(), why.to_string());
return;
}
Ok(file) => file,
};
file.read_to_end(&mut buf).ok().expect(
"File could not be read.",
);
let draw_range = get_absolute_draw_indices(buf.len(), SPALTEN, screenoffset);
draw(&buf[draw_range.0 .. draw_range.1], cursorpos, SPALTEN, &command, &mut debug, cstate, screenoffset);
let mut quitnow = false;
let mut autoparse = false;
while quitnow == false {
if !autoparse {
let key = std::char::from_u32(getch() as u32).unwrap();
command.push_str(&key.clone().to_string());
}
autoparse = false;
let parsethisstring = command.clone();
let commands = IdentParser::parse(Rule::cmd_list, &parsethisstring)
.unwrap_or_else(|e| panic!("{}", e));
let mut clear = true;
let mut save = false;
for cmd in commands {
match cmd.as_rule() {
Rule::down => {
// debug.push_str(&format!("{:?}", cmd.as_rule()));
if cursorpos + SPALTEN < buf.len() {
// not at end
cursorpos += SPALTEN;
} else {
// when at end
if buf.len() != 0 {
// Suppress underflow
cursorpos = buf.len() - 1;
}
}
}
Rule::up => {
if cursorpos >= SPALTEN {
cursorpos -= SPALTEN;
}
}
Rule::left => {
if cstate == Cursorstate::Asciichar {
if cursorpos > 0 {
cursorpos -= 1;
}
} else if cstate == Cursorstate::Rightnibble {
cstate = Cursorstate::Leftnibble;
} else if cstate == Cursorstate::Leftnibble {
if cursorpos > 0 {
// not at start
cstate = Cursorstate::Rightnibble;
cursorpos -= 1;
}
}
}
Rule::right => {
if cstate == Cursorstate::Asciichar {
if cursorpos + 1 < buf.len() {
// not at end
cursorpos += 1;
}
} else if cstate == Cursorstate::Leftnibble {
cstate = Cursorstate::Rightnibble;
} else if cstate == Cursorstate::Rightnibble {
if cursorpos + 1 < buf.len() {
// not at end
cstate = Cursorstate::Leftnibble;
cursorpos += 1;
}
}
}
Rule::start => {
cursorpos -= cursorpos % SPALTEN; // jump to start of line
if cstate == Cursorstate::Rightnibble {
cstate = Cursorstate::Leftnibble;
}
}
Rule::end => {
// check if no overflow
if cursorpos - (cursorpos % SPALTEN) + (SPALTEN - 1) < buf.len() {
// jump to end of line
cursorpos = cursorpos - (cursorpos % SPALTEN) + (SPALTEN - 1);
} else {
// jump to end of line
cursorpos = buf.len() - 1
}
if cstate == Cursorstate::Leftnibble {
cstate = Cursorstate::Rightnibble;
}
}
Rule::bottom => {
cursorpos = buf.len() - 1;
cursorpos -= cursorpos % SPALTEN; // jump to start of line
}
Rule::replace => {
// debug.push_str("next char will be the replacement!");
clear = false;
}
Rule::remove => {
// check if in valid range
if buf.len() > 0 && cursorpos < buf.len() {
// remove the current char
buf.remove(cursorpos);
}
// always perform the movement if possible
if cursorpos > 0 && cursorpos >= buf.len() {
cursorpos -= 1;
}
lastcommand = command.clone();
}
Rule::insert => {
// debug.push_str("next chars will be inserted!");
clear = false;
}
Rule::jumpascii => {
if cstate == Cursorstate::Asciichar {
cstate = Cursorstate::Leftnibble;
} else {
cstate = Cursorstate::Asciichar;
}
}
Rule::helpfile => {
command.push_str("No helpfile yet");
}
Rule::repeat => {
command = lastcommand.clone();
clear = false;
autoparse = true;
}
Rule::backspace => {
command.pop();
command.pop();
clear = false;
}
Rule::saveandexit => {
save = true;
quitnow = true;
}
Rule::exit => quitnow = true,
Rule::save => save = true,
_ => (),
}
for inner_cmd in cmd.into_inner() {
match inner_cmd.as_rule() {
Rule::replacement => {
let key = inner_cmd.as_str().chars().nth(0).unwrap_or('x');
if cstate == Cursorstate::Asciichar {
if cursorpos >= buf.len() {
buf.insert(cursorpos, 0);
}
// buf[cursorpos] = inner_cmd.as_str();
buf[cursorpos] = key as u8;
} else {
let mask = if cstate == Cursorstate::Leftnibble {
0x0F
} else {
0xF0
};
let shift = if cstate == Cursorstate::Leftnibble {
4
} else {
0
};
if cursorpos >= buf.len() {
buf.insert(cursorpos, 0);
}
// Change the selected nibble
if let Some(c) = key.to_digit(16) {
buf[cursorpos] = buf[cursorpos] & mask | (c as u8) << shift;
}
}
lastcommand.clear();
lastcommand.push_str(&format!("{}{}", command.chars().nth(0).unwrap_or('?'), key ));
}
Rule::dd_lines => {
let amount: usize = inner_cmd.as_str().parse().unwrap_or(1);
// check if in valid range
if buf.len() > 0 && cursorpos < buf.len() {
let startofline = cursorpos - cursorpos % SPALTEN;
let mut endofline = cursorpos - (cursorpos % SPALTEN) + (SPALTEN * amount ) ;
endofline = cmp::min( endofline, buf.len() );
buf.drain(startofline..endofline);
}
lastcommand = command.clone();
}
Rule::insertment => {
let key = inner_cmd.as_str().chars().nth(0).unwrap_or('x');
lastcommand = command.clone();
// debug.push_str(&format!("Inserted: {:?}", inner_cmd.as_str()));
command.pop(); // remove the just inserted thing
clear = false;
if cstate == Cursorstate::Leftnibble {
// Left nibble
if let Some(c) = key.to_digit(16) {
buf.insert(cursorpos, (c as u8) << 4);
cstate = Cursorstate::Rightnibble;
}
} else if cstate == Cursorstate::Rightnibble {
// Right nibble
if cursorpos == buf.len() {
buf.insert(cursorpos, 0);
}
if let Some(c) = key.to_digit(16) {
buf[cursorpos] = buf[cursorpos] & 0xF0 | c as u8;
cstate = Cursorstate::Leftnibble;
cursorpos += 1;
}
} else if cstate == Cursorstate::Asciichar {
buf.insert(cursorpos, key as u8);
cursorpos += 1;
}
lastcommand.clear();
lastcommand.push_str(&format!("Command repeation for {:?} not yet implemented.", inner_cmd.as_rule()));
}
Rule::searchstr => {
let search = inner_cmd.as_str().as_bytes();
let foundpos = TwoWaySearcher::new(&search);
cursorpos = foundpos.search_in(&buf).unwrap_or(cursorpos);
}
Rule::searchbytes => {
let search = inner_cmd.as_str().as_bytes();
let mut needle = vec![];
for i in 0..search.len() {
let nibble = match search[i] as u8 {
c @ 48...57 => c - 48, // Numbers from 0 to 9
b'x' => 0x10, // x is the wildcard
b'X' => 0x10, // X is the wildcard
c @ b'a'...b'f' => c - 87,
c @ b'A'...b'F' => c - 55,
_ => panic!("Should not get to this position!"),
};
needle.push(nibble);
}
cursorpos = buf.find_subset(&needle).unwrap_or(cursorpos);
// debug.push_str(&format!("Searching for: {:?}", needle ));
}
Rule::gg_line => {
let linenr: usize = inner_cmd.as_str().parse().unwrap_or(0);
cursorpos = linenr * SPALTEN; // jump to the line
if cursorpos > buf.len() { // detect file end
cursorpos = buf.len();
}
cursorpos -= cursorpos % SPALTEN; // jump to start of line
}
Rule::escape => (),
Rule::gatherone => clear = false,
_ => {
command.push_str(&format!("no rule for {:?} ", inner_cmd.as_rule()));
clear = false;
}
};
}
if save {
if path.exists() {
let mut file = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path) {
Err(why) => {
panic!(
"Could not open {}: {}",
path.display(),
Error::description(&why)
)
}
Ok(file) => file,
};
file.seek(SeekFrom::Start(0)).ok().expect(
"Filepointer could not be set to 0",
);
file.write_all(&mut buf).ok().expect(
"File could not be written.",
);
file.set_len(buf.len() as u64).ok().expect(
"File could not be set to correct lenght.",
);
command.push_str("File saved!");
} else {
command.push_str("Careful, file could not be saved!");
}
// TODO: define filename during runtime
save = false;
}
if clear {
command.clear();
}
// Always move screen when cursor leaves screen
if cursorpos > (screenheight + screenoffset - 1) * SPALTEN - 1 {
screenoffset = 2 + cursorpos / SPALTEN - screenheight;
}
if cursorpos < screenoffset * SPALTEN {
screenoffset = cursorpos / SPALTEN;
}
}
let draw_range = get_absolute_draw_indices(buf.len(), SPALTEN, screenoffset);
draw(&buf[draw_range.0 .. draw_range.1], cursorpos, SPALTEN, &command, &mut debug, cstate, screenoffset);
}
refresh();
endwin();
}