Merge branch 'fix/editor-barcode-hri'
@@ -198,10 +198,10 @@ Images are converted to monochrome raster data and scaled to width (never wider
198
198
|-------|--------|
199
199
| Mode | Optional `RASTER` prefix; otherwise native ESC/POS |
200
200
| Symbology | Native: `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A`, `UPC-E`, `ITF`, `CODABAR`. Raster-only: `CODE93`, `CODE11` |
201
| Data | Literal or `${Param}` |
201
| Data | Literal or `${Param}`; multiple words joined until the first `key=value` attribute |
202
202
| `height` | Module / PNG height in dots (default: 64) |
203
203
| `align` | `left`, `center`, `right` |
204
| `show_text` | Native only: HRI below barcode |
204
| `show_text` | Native only: print HRI text under barcode (default: off; set `show_text=true` to enable) |
205
205
206
206
Raster barcodes stretch horizontally to full printable width.
207
207
@@ -215,7 +215,7 @@ Raster barcodes stretch horizontally to full printable width.
215
215
216
216
| Attribute | Native | Raster |
217
217
|-----------|--------|--------|
218
| Data | URL/text; may include `${Param}` | Same |
218
| Data | URL/text; may include `${Param}`; multiple words joined until the first `key=value` attribute | Same |
219
219
| `size` | Module size 1–16 (default 4) | — |
220
220
| `scale` | — | Pixels per module (default 4) |
221
221
| `version` | — | QR version 1–40 (optional) |
@@ -198,10 +198,10 @@ Images are converted to monochrome raster data and scaled to width (never wider198
|-------|--------|198
|-------|--------|199
| Mode | Optional `RASTER` prefix; otherwise native ESC/POS |199
| Mode | Optional `RASTER` prefix; otherwise native ESC/POS |200
| Symbology | Native: `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A`, `UPC-E`, `ITF`, `CODABAR`. Raster-only: `CODE93`, `CODE11` |200
| Symbology | Native: `CODE128`, `EAN13`, `EAN8`, `CODE39`, `UPC-A`, `UPC-E`, `ITF`, `CODABAR`. Raster-only: `CODE93`, `CODE11` |201
| Data | Literal or `${Param}` |201
| Data | Literal or `${Param}`; multiple words joined until the first `key=value` attribute |202
| `height` | Module / PNG height in dots (default: 64) |202
| `height` | Module / PNG height in dots (default: 64) |203
| `align` | `left`, `center`, `right` |203
| `align` | `left`, `center`, `right` |204
| `show_text` | Native only: HRI below barcode |204
| `show_text` | Native only: print HRI text under barcode (default: off; set `show_text=true` to enable) |205
205
206
Raster barcodes stretch horizontally to full printable width.206
Raster barcodes stretch horizontally to full printable width.207
207
@@ -215,7 +215,7 @@ Raster barcodes stretch horizontally to full printable width.215
215
216
| Attribute | Native | Raster |216
| Attribute | Native | Raster |217
|-----------|--------|--------|217
|-----------|--------|--------|218
| Data | URL/text; may include `${Param}` | Same |218
| Data | URL/text; may include `${Param}`; multiple words joined until the first `key=value` attribute | Same |219
| `size` | Module size 1–16 (default 4) | — |219
| `size` | Module size 1–16 (default 4) | — |220
| `scale` | — | Pixels per module (default 4) |220
| `scale` | — | Pixels per module (default 4) |221
| `version` | — | QR version 1–40 (optional) |221
| `version` | — | QR version 1–40 (optional) |@@ -178,12 +178,15 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a
178
178
@barcode CODE128 ${OrderId}
179
179
@barcode UPC-A 012345678905
180
180
@barcode ITF 12345678 height=80
181
@barcode CODE128 hallo wereld
182
@barcode CODE128 ABC show_text=true
181
183
```
182
184
183
185
**Raster** (bitmap). Raster barcodes stretch horizontally to full paper width; height follows `height`.
184
186
185
187
```markdown
186
188
@barcode RASTER CODE128 ${OrderId}
189
@barcode RASTER CODE128 hallo wereld
187
190
@barcode RASTER CODE93 ABC-1234
188
191
```
189
192
@@ -204,7 +207,9 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a
204
207
|-----------|-------------|
205
208
| `height` | Height in dots (default `64`) |
206
209
| `align` | `left`, `center`, `right` |
207
| `show_text` | Native only: human-readable text under barcode |
210
| `show_text` | Native only: human-readable text under barcode (default off; `show_text=true` to enable) |
211
212
Data may contain spaces; tokens after the symbology are joined until the first `key=value` attribute.
208
213
209
214
### QR code
210
215
@@ -213,6 +218,7 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a
213
218
```markdown
214
219
@qr https://example.com/${Id}
215
220
@qr ${Url} size=6 ecc=H align=center
221
@qr hallo wereld size=4
216
222
```
217
223
218
224
**Raster** (bitmap; QR versions 1–40):
@@ -178,12 +178,15 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a178
@barcode CODE128 ${OrderId}178
@barcode CODE128 ${OrderId}179
@barcode UPC-A 012345678905179
@barcode UPC-A 012345678905180
@barcode ITF 12345678 height=80180
@barcode ITF 12345678 height=80181
@barcode CODE128 hallo wereld182
@barcode CODE128 ABC show_text=true181
```183
```182
184
183
**Raster** (bitmap). Raster barcodes stretch horizontally to full paper width; height follows `height`.185
**Raster** (bitmap). Raster barcodes stretch horizontally to full paper width; height follows `height`.184
186
185
```markdown187
```markdown186
@barcode RASTER CODE128 ${OrderId}188
@barcode RASTER CODE128 ${OrderId}189
@barcode RASTER CODE128 hallo wereld187
@barcode RASTER CODE93 ABC-1234190
@barcode RASTER CODE93 ABC-1234188
```191
```189
192
@@ -204,7 +207,9 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a204
|-----------|-------------|207
|-----------|-------------|205
| `height` | Height in dots (default `64`) |208
| `height` | Height in dots (default `64`) |206
| `align` | `left`, `center`, `right` |209
| `align` | `left`, `center`, `right` |207
| `show_text` | Native only: human-readable text under barcode |210
| `show_text` | Native only: human-readable text under barcode (default off; `show_text=true` to enable) |211
212
Data may contain spaces; tokens after the symbology are joined until the first `key=value` attribute.208
213
209
### QR code214
### QR code210
215
@@ -213,6 +218,7 @@ Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs a213
```markdown218
```markdown214
@qr https://example.com/${Id}219
@qr https://example.com/${Id}215
@qr ${Url} size=6 ecc=H align=center220
@qr ${Url} size=6 ecc=H align=center221
@qr hallo wereld size=4216
```222
```217
223
218
**Raster** (bitmap; QR versions 1–40):224
**Raster** (bitmap; QR versions 1–40):@@ -31,7 +31,7 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).
31
31
| List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |
32
32
| Inline checkbox | ASCII `[ ]` / `[x]` | `[]` / `[x]` / `$[Name]` — same font as text |
33
33
| Partial cut | GS V 66 0 | `@cut` in template only |
34
| Barcode | GS k | Native symbologies; raster via GS v 0 |
34
| Barcode | GS H, GS h, GS w, GS k | Native: HRI off by default (`GS H 0`); `show_text=true` → `GS H 2`. Raster via GS v 0 |
35
35
| QR Code | GS ( k | Model 2; or raster GS v 0 |
36
36
| Raster image | GS v 0 | `@image` / raster barcode / raster QR |
37
37
@@ -31,7 +31,7 @@ Target **Epson ESC/POS** compatible printers (58 mm / 80 mm thermal).31
| List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |31
| List bullet | `*` top-level, `-` nested | `- item` / ` - nested`; hanging wrap |32
| Inline checkbox | ASCII `[ ]` / `[x]` | `[]` / `[x]` / `$[Name]` — same font as text |32
| Inline checkbox | ASCII `[ ]` / `[x]` | `[]` / `[x]` / `$[Name]` — same font as text |33
| Partial cut | GS V 66 0 | `@cut` in template only |33
| Partial cut | GS V 66 0 | `@cut` in template only |34
| Barcode | GS k | Native symbologies; raster via GS v 0 |34
| Barcode | GS H, GS h, GS w, GS k | Native: HRI off by default (`GS H 0`); `show_text=true` → `GS H 2`. Raster via GS v 0 |35
| QR Code | GS ( k | Model 2; or raster GS v 0 |35
| QR Code | GS ( k | Model 2; or raster GS v 0 |36
| Raster image | GS v 0 | `@image` / raster barcode / raster QR |36
| Raster image | GS v 0 | `@image` / raster barcode / raster QR |37
37
@@ -5,9 +5,9 @@ use eframe::egui;
5
5
use posprint::config::AppConfig;
6
6
use posprint::dsl::{self, parse};
7
7
use posprint::editor_assist::{
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
9
complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options,
10
insert_at_cursor, parameter_insert_options, qr_insert_options,
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, byte_index_to_char,
9
char_index_to_byte, complete_directive, date_time_insert_options, directive_ghost_suffix,
10
image_insert_options, insert_at_cursor, parameter_insert_options, qr_insert_options,
11
11
};
12
12
use posprint::help_view;
13
13
use posprint::io::{PosFile, PosMetadata};
@@ -572,8 +572,20 @@ impl PosPrintApp {
572
572
if let Some((at_index, prefix)) = tab_completion {
573
573
if let Some(completed) = complete_directive(&prefix) {
574
574
let undo_before = self.body.clone();
575
self.editor_cursor =
576
apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
575
// Use the pre-TextEdit cursor: that is the end of the typed prefix.
576
self.editor_cursor = apply_directive_completion(
577
&mut self.body,
578
at_index,
579
cursor_before,
580
completed,
581
);
582
// Sync egui TextEdit caret to the end of the completed directive.
583
let char_idx = byte_index_to_char(&self.body, self.editor_cursor);
584
let mut state = output.state;
585
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(
586
egui::text::CCursor::new(char_idx),
587
)));
588
state.store(ui.ctx(), output.response.id);
577
589
self.undo.record(undo_before);
578
590
self.dirty = true;
579
591
}
@@ -5,9 +5,9 @@ use eframe::egui;5
use posprint::config::AppConfig;
5
use posprint::config::AppConfig;
6
use posprint::dsl::{self, parse};
6
use posprint::dsl::{self, parse};
7
use posprint::editor_assist::{
7
use posprint::editor_assist::{
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, byte_index_to_char,
9
complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options,
9
char_index_to_byte, complete_directive, date_time_insert_options, directive_ghost_suffix,
10
insert_at_cursor, parameter_insert_options, qr_insert_options,
10
image_insert_options, insert_at_cursor, parameter_insert_options, qr_insert_options,
11
};
11
};
12
use posprint::help_view;
12
use posprint::help_view;
13
use posprint::io::{PosFile, PosMetadata};
13
use posprint::io::{PosFile, PosMetadata};
@@ -572,8 +572,20 @@ impl PosPrintApp {572
if let Some((at_index, prefix)) = tab_completion {
572
if let Some((at_index, prefix)) = tab_completion {
573
if let Some(completed) = complete_directive(&prefix) {
573
if let Some(completed) = complete_directive(&prefix) {
574
let undo_before = self.body.clone();
574
let undo_before = self.body.clone();
575
self.editor_cursor =
575
// Use the pre-TextEdit cursor: that is the end of the typed prefix.
576
apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
576
self.editor_cursor = apply_directive_completion(
577
&mut self.body,
578
at_index,
579
cursor_before,
580
completed,
581
);
582
// Sync egui TextEdit caret to the end of the completed directive.
583
let char_idx = byte_index_to_char(&self.body, self.editor_cursor);
584
let mut state = output.state;
585
state.cursor.set_char_range(Some(egui::text::CCursorRange::one(
586
egui::text::CCursor::new(char_idx),
587
)));
588
state.store(ui.ctx(), output.response.id);
577
self.undo.record(undo_before);
589
self.undo.record(undo_before);
578
self.dirty = true;
590
self.dirty = true;
579
}
591
}
@@ -493,12 +493,12 @@ fn parse_barcode_directive(
493
493
));
494
494
}
495
495
496
let data = parts[data_idx].to_string();
497
let attr_start = data_idx + 1;
496
let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@barcode")?;
498
497
let mut height = 64u8;
499
498
let mut align = default_align;
500
let mut show_text = true;
501
for attr in &parts[attr_start..] {
499
// Default off: many printers print HRI under native barcodes otherwise.
500
let mut show_text = false;
501
for attr in attrs {
502
502
if let Some((k, v)) = attr.split_once('=') {
503
503
match k.to_ascii_lowercase().as_str() {
504
504
"height" => {
@@ -510,6 +510,12 @@ fn parse_barcode_directive(
510
510
"show_text" => show_text = v == "true",
511
511
_ => return Err(err(line_no, 1, format!("unknown barcode attribute {k}"))),
512
512
}
513
} else {
514
return Err(err(
515
line_no,
516
1,
517
format!("unexpected barcode token '{attr}' (attributes use key=value)"),
518
));
513
519
}
514
520
}
515
521
Ok(Block::Barcode {
@@ -588,13 +594,12 @@ fn parse_qr_directive(
588
594
(QrMode::Native, 0)
589
595
};
590
596
591
let data = parts[data_idx].to_string();
592
let attr_start = data_idx + 1;
597
let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@qr")?;
593
598
let mut size = 4u8;
594
599
let mut ecc = QrEcc::M;
595
600
let mut align = default_align;
596
601
let mut version = None;
597
for attr in &parts[attr_start..] {
602
for attr in attrs {
598
603
if let Some((k, v)) = attr.split_once('=') {
599
604
match k.to_ascii_lowercase().as_str() {
600
605
"size" => {
@@ -625,6 +630,12 @@ fn parse_qr_directive(
625
630
"align" => align = parse_align_value(v, line_no)?,
626
631
_ => return Err(err(line_no, 1, format!("unknown qr attribute {k}"))),
627
632
}
633
} else {
634
return Err(err(
635
line_no,
636
1,
637
format!("unexpected qr token '{attr}' (attributes use key=value)"),
638
));
628
639
}
629
640
}
630
641
Ok(Block::Qr {
@@ -646,6 +657,32 @@ fn parse_align_value(value: &str, line_no: usize) -> Result<Align, ParseError> {
646
657
}
647
658
}
648
659
660
/// Collect data tokens from `data_idx` until the first `key=value` attribute.
661
/// Remaining tokens are returned as attributes (must all be `key=value`).
662
fn take_data_tokens<'a>(
663
parts: &'a [&str],
664
data_idx: usize,
665
line_no: usize,
666
directive: &str,
667
) -> Result<(String, &'a [&'a str]), ParseError> {
668
if data_idx >= parts.len() {
669
return Err(err(line_no, 1, format!("{directive} requires data")));
670
}
671
if parts[data_idx].contains('=') {
672
return Err(err(
673
line_no,
674
1,
675
format!("{directive} data cannot start with an attribute"),
676
));
677
}
678
let mut data_end = data_idx + 1;
679
while data_end < parts.len() && !parts[data_end].contains('=') {
680
data_end += 1;
681
}
682
let data = parts[data_idx..data_end].join(" ");
683
Ok((data, &parts[data_end..]))
684
}
685
649
686
fn is_list_item_line(line: &str) -> bool {
650
687
line.trim_start().starts_with("- ")
651
688
}
@@ -1144,4 +1181,48 @@ mod tests {
1144
1181
}
1145
1182
));
1146
1183
}
1184
1185
#[test]
1186
fn barcode_data_joins_words_until_attributes() {
1187
let doc = parse("@barcode RASTER CODE128 hallo wereld height=80").unwrap();
1188
match &doc.blocks[0] {
1189
Block::Barcode {
1190
data,
1191
height,
1192
show_text,
1193
..
1194
} => {
1195
assert_eq!(data, "hallo wereld");
1196
assert_eq!(*height, 80);
1197
assert!(!*show_text);
1198
}
1199
other => panic!("expected barcode, got {other:?}"),
1200
}
1201
}
1202
1203
#[test]
1204
fn barcode_show_text_defaults_false_and_can_enable() {
1205
let off = parse("@barcode CODE128 ABC").unwrap();
1206
match &off.blocks[0] {
1207
Block::Barcode { show_text, .. } => assert!(!*show_text),
1208
other => panic!("expected barcode, got {other:?}"),
1209
}
1210
let on = parse("@barcode CODE128 ABC show_text=true").unwrap();
1211
match &on.blocks[0] {
1212
Block::Barcode { show_text, .. } => assert!(*show_text),
1213
other => panic!("expected barcode, got {other:?}"),
1214
}
1215
}
1216
1217
#[test]
1218
fn qr_data_joins_words_until_attributes() {
1219
let doc = parse("@qr hallo wereld size=6").unwrap();
1220
match &doc.blocks[0] {
1221
Block::Qr { data, size, .. } => {
1222
assert_eq!(data, "hallo wereld");
1223
assert_eq!(*size, 6);
1224
}
1225
other => panic!("expected qr, got {other:?}"),
1226
}
1227
}
1147
1228
}
@@ -493,12 +493,12 @@ fn parse_barcode_directive(493
));
493
));
494
}
494
}
495
495
496
let data = parts[data_idx].to_string();
496
let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@barcode")?;
497
let attr_start = data_idx + 1;
498
let mut height = 64u8;
497
let mut height = 64u8;
499
let mut align = default_align;
498
let mut align = default_align;
500
let mut show_text = true;
499
// Default off: many printers print HRI under native barcodes otherwise.
501
for attr in &parts[attr_start..] {
500
let mut show_text = false;
501
for attr in attrs {
502
if let Some((k, v)) = attr.split_once('=') {
502
if let Some((k, v)) = attr.split_once('=') {
503
match k.to_ascii_lowercase().as_str() {
503
match k.to_ascii_lowercase().as_str() {
504
"height" => {
504
"height" => {
@@ -510,6 +510,12 @@ fn parse_barcode_directive(510
"show_text" => show_text = v == "true",
510
"show_text" => show_text = v == "true",
511
_ => return Err(err(line_no, 1, format!("unknown barcode attribute {k}"))),
511
_ => return Err(err(line_no, 1, format!("unknown barcode attribute {k}"))),
512
}
512
}
513
} else {
514
return Err(err(
515
line_no,
516
1,
517
format!("unexpected barcode token '{attr}' (attributes use key=value)"),
518
));
513
}
519
}
514
}
520
}
515
Ok(Block::Barcode {
521
Ok(Block::Barcode {
@@ -588,13 +594,12 @@ fn parse_qr_directive(588
(QrMode::Native, 0)
594
(QrMode::Native, 0)
589
};
595
};
590
596
591
let data = parts[data_idx].to_string();
597
let (data, attrs) = take_data_tokens(&parts, data_idx, line_no, "@qr")?;
592
let attr_start = data_idx + 1;
593
let mut size = 4u8;
598
let mut size = 4u8;
594
let mut ecc = QrEcc::M;
599
let mut ecc = QrEcc::M;
595
let mut align = default_align;
600
let mut align = default_align;
596
let mut version = None;
601
let mut version = None;
597
for attr in &parts[attr_start..] {
602
for attr in attrs {
598
if let Some((k, v)) = attr.split_once('=') {
603
if let Some((k, v)) = attr.split_once('=') {
599
match k.to_ascii_lowercase().as_str() {
604
match k.to_ascii_lowercase().as_str() {
600
"size" => {
605
"size" => {
@@ -625,6 +630,12 @@ fn parse_qr_directive(625
"align" => align = parse_align_value(v, line_no)?,
630
"align" => align = parse_align_value(v, line_no)?,
626
_ => return Err(err(line_no, 1, format!("unknown qr attribute {k}"))),
631
_ => return Err(err(line_no, 1, format!("unknown qr attribute {k}"))),
627
}
632
}
633
} else {
634
return Err(err(
635
line_no,
636
1,
637
format!("unexpected qr token '{attr}' (attributes use key=value)"),
638
));
628
}
639
}
629
}
640
}
630
Ok(Block::Qr {
641
Ok(Block::Qr {
@@ -646,6 +657,32 @@ fn parse_align_value(value: &str, line_no: usize) -> Result<Align, ParseError> {646
}
657
}
647
}
658
}
648
659
660
/// Collect data tokens from `data_idx` until the first `key=value` attribute.
661
/// Remaining tokens are returned as attributes (must all be `key=value`).
662
fn take_data_tokens<'a>(
663
parts: &'a [&str],
664
data_idx: usize,
665
line_no: usize,
666
directive: &str,
667
) -> Result<(String, &'a [&'a str]), ParseError> {
668
if data_idx >= parts.len() {
669
return Err(err(line_no, 1, format!("{directive} requires data")));
670
}
671
if parts[data_idx].contains('=') {
672
return Err(err(
673
line_no,
674
1,
675
format!("{directive} data cannot start with an attribute"),
676
));
677
}
678
let mut data_end = data_idx + 1;
679
while data_end < parts.len() && !parts[data_end].contains('=') {
680
data_end += 1;
681
}
682
let data = parts[data_idx..data_end].join(" ");
683
Ok((data, &parts[data_end..]))
684
}
685
649
fn is_list_item_line(line: &str) -> bool {
686
fn is_list_item_line(line: &str) -> bool {
650
line.trim_start().starts_with("- ")
687
line.trim_start().starts_with("- ")
651
}
688
}
@@ -1144,4 +1181,48 @@ mod tests {1144
}
1181
}
1145
));
1182
));
1146
}
1183
}
1184
1185
#[test]
1186
fn barcode_data_joins_words_until_attributes() {
1187
let doc = parse("@barcode RASTER CODE128 hallo wereld height=80").unwrap();
1188
match &doc.blocks[0] {
1189
Block::Barcode {
1190
data,
1191
height,
1192
show_text,
1193
..
1194
} => {
1195
assert_eq!(data, "hallo wereld");
1196
assert_eq!(*height, 80);
1197
assert!(!*show_text);
1198
}
1199
other => panic!("expected barcode, got {other:?}"),
1200
}
1201
}
1202
1203
#[test]
1204
fn barcode_show_text_defaults_false_and_can_enable() {
1205
let off = parse("@barcode CODE128 ABC").unwrap();
1206
match &off.blocks[0] {
1207
Block::Barcode { show_text, .. } => assert!(!*show_text),
1208
other => panic!("expected barcode, got {other:?}"),
1209
}
1210
let on = parse("@barcode CODE128 ABC show_text=true").unwrap();
1211
match &on.blocks[0] {
1212
Block::Barcode { show_text, .. } => assert!(*show_text),
1213
other => panic!("expected barcode, got {other:?}"),
1214
}
1215
}
1216
1217
#[test]
1218
fn qr_data_joins_words_until_attributes() {
1219
let doc = parse("@qr hallo wereld size=6").unwrap();
1220
match &doc.blocks[0] {
1221
Block::Qr { data, size, .. } => {
1222
assert_eq!(data, "hallo wereld");
1223
assert_eq!(*size, 6);
1224
}
1225
other => panic!("expected qr, got {other:?}"),
1226
}
1227
}
1147
}
1228
}
@@ -211,6 +211,12 @@ pub fn char_index_to_byte(s: &str, char_index: usize) -> usize {
211
211
.unwrap_or(s.len())
212
212
}
213
213
214
/// Convert a UTF-8 byte offset to an egui `CCursor` character index.
215
pub fn byte_index_to_char(s: &str, byte_index: usize) -> usize {
216
let byte_index = floor_char_boundary(s, byte_index.min(s.len()));
217
s[..byte_index].chars().count()
218
}
219
214
220
/// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics).
215
221
pub fn floor_char_boundary(s: &str, mut index: usize) -> usize {
216
222
if index >= s.len() {
@@ -331,6 +337,10 @@ mod tests {
331
337
assert_eq!(char_index_to_byte(&s, 2), 4);
332
338
assert_eq!(char_index_to_byte(&s, 3), 5);
333
339
assert_eq!(char_index_to_byte(&s, 99), 5);
340
assert_eq!(byte_index_to_char(&s, 0), 0);
341
assert_eq!(byte_index_to_char(&s, 1), 1);
342
assert_eq!(byte_index_to_char(&s, 4), 2);
343
assert_eq!(byte_index_to_char(&s, 5), 3);
334
344
}
335
345
336
346
#[test]
@@ -211,6 +211,12 @@ pub fn char_index_to_byte(s: &str, char_index: usize) -> usize {211
.unwrap_or(s.len())211
.unwrap_or(s.len())212
}212
}213
213
214
/// Convert a UTF-8 byte offset to an egui `CCursor` character index.215
pub fn byte_index_to_char(s: &str, byte_index: usize) -> usize {216
let byte_index = floor_char_boundary(s, byte_index.min(s.len()));217
s[..byte_index].chars().count()218
}219
214
/// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics).220
/// Clamp `index` down to the nearest char boundary (avoids UTF-8 slice panics).215
pub fn floor_char_boundary(s: &str, mut index: usize) -> usize {221
pub fn floor_char_boundary(s: &str, mut index: usize) -> usize {216
if index >= s.len() {222
if index >= s.len() {@@ -331,6 +337,10 @@ mod tests {331
assert_eq!(char_index_to_byte(&s, 2), 4);337
assert_eq!(char_index_to_byte(&s, 2), 4);332
assert_eq!(char_index_to_byte(&s, 3), 5);338
assert_eq!(char_index_to_byte(&s, 3), 5);333
assert_eq!(char_index_to_byte(&s, 99), 5);339
assert_eq!(char_index_to_byte(&s, 99), 5);340
assert_eq!(byte_index_to_char(&s, 0), 0);341
assert_eq!(byte_index_to_char(&s, 1), 1);342
assert_eq!(byte_index_to_char(&s, 4), 2);343
assert_eq!(byte_index_to_char(&s, 5), 3);334
}344
}335
345
336
#[test]346
#[test]