gyscos / gyscos/cursive

[BUG] Nested `Printer::with_color` leading to unexpected behavior

Open
#652 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
Rust
Stars
4.8k
Forks
270
Avg merge
5d 19h
Merged PRs (30d)
2

Description

**Describe the bug**
`Printer::with_color` and similar functions are implemented by mutating the printer itself without mutably borrowing it, leading to unexpected (or wrong) behavior when being used nestedly.

**To Reproduce**
```rust
use cursive::{theme::BaseColor, views::Canvas};

fn main() {
let ref mut s = cursive::default();
s.add_layer(
Canvas::new(())
.with_draw(|_, printer| {
printer.with_color(BaseColor::Red.into(), |p_red| {
printer.with_color(BaseColor::Black.into(), |p_black| {
p_red.print((0, 0), "should be red");
p_black.print((0, 1), "should be black");
})
})
})
.with_required_size(|_, _| (20, 10).into()),
);
s.run();
}
```
Run, and see both lines being black.

**Expected behavior**
The first line of text should be red.
Or this code should fail to compile.

**Screenshots**
Actual:
![Actual](https://user-images.githubusercontent.com/28475392/170824306-0a78115d-1cb7-475c-aac3-a2036601afa9.png)
Expected:
![Expected](https://user-images.githubusercontent.com/28475392/170824334-f220bbfa-4f5f-41c5-acab-872f08e2be48.png)

**Environment**
* Operating system used: Windows Terminal & ConHost on Windows 10
* Backend used: crossterm
* Current locale: zh_CN.UTF-8
* Cursive version: 0.18.0 from crates.io

**Additional context**
Well I *do* know that it should not be used like this. But imo such a usage should, and probably could be prevented by borrowing the printer mutably.

BTW I came across this when trying to get two printers with same offset and different color in the same scope. Is there a better way for this?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.