iced icon indicating copy to clipboard operation
iced copied to clipboard

Image is not updating

Open 0x7CFE opened this issue 4 years ago • 2 comments

I have a form with an image and a button. When the button is pressed, an image handle is reloaded from the same file (which was changed in the meantime). I expect the image to update it's contents, but, for some reason, it stays untouched. What am I doing wrong?

struct Ui {
    next: button::State,
    image: Handle,
}

impl Sandbox for Ui {
    type Message = Message;
    
    fn new() -> Self {
        Ui {
            next: button::State::new(),
            image: Handle::from_path("test.png"),
        }
    }
    
    fn update(&mut self, message: Self::Message) {
        match message {
            Message::Next => {
                // the image on disk was changed by a different program, so I need to re-load it
                self.image = Handle::from_path("test.png");
            }
        }
    }

    // ...

    fn view(&mut self) -> iced::Element<'_, Self::Message> {
        Row::new()
            .push(
                Button::new(&mut self.next, Text::new("Next"))
                    .on_press(Message::Next)
            )
            .push(Image::new(self.image.clone()))
            .into()
    }
}

0x7CFE avatar Jun 12 '20 05:06 0x7CFE

Looks like this happens because in case of Data::Path, Handle::from_data hashes the file name, not it's contents:

    fn from_data(data: Data) -> Handle {
        let mut hasher = Hasher::default();
        data.hash(&mut hasher);

        Handle {
            id: hasher.finish(),
            data: Arc::new(data),
        }
    }

If the file name does not change, its hash will not change either, so iced doesn't know it needs to update the widget.

I've fixed the issue by reading the file contents into a Vec and using Handle::from_memory. If this is the desired behavior, I think, it should be documented.

0x7CFE avatar Jun 12 '20 06:06 0x7CFE

Yes, Handle::from_path returns a Handle pointing to a specific path. It doesn't load any data.

I believe both Image and Svg widgets should be eventually moved to iced_graphics and the API should be improved. We can try to address this issue then.

hecrj avatar Jun 15 '20 17:06 hecrj

I don't think this is a bug. from_path works the same way an image in a browser would.

hecrj avatar Feb 11 '24 03:02 hecrj