Buffer problems when extending GtkSourceView (Rust)

Hi!
I am creating a Object that extends directly from a GtkSourceView:

mod imp {
    use super::*;
    use gtk::glib;
    use sourceview::subclass::prelude::*;

    #[derive(Default)]
    pub struct MyView;

    #[glib::object_subclass]
    impl ObjectSubclass for MyView {
        const NAME: &'static str = "MySourceView";
        type Type = super::MyView;
        type ParentType = sourceview::View;        
    }
    
    impl ObjectImpl for MyView {}
    impl WidgetImpl for MyView {}
    impl TextViewImpl for MyView {}
    impl ViewImpl for MyView {}
}

glib::wrapper! {
    pub struct MyView(ObjectSubclass<imp::MyView>)
        @extends sourceview::View, gtk::TextView, gtk::Widget;
}

impl MyView {
    pub fn new() -> Self {
       ...
    }
}

I have problems getting the Buffer of MyView, because it returns the TextBuffer (of the TextView) and not the Buffer of the SourceView

my_view.buffer() (as TextViewExt) // ← Wrong
// I need the SourceViewBuffer

The rest is correct, it shows me and returns the functions corresponding to GtkSourceView.

I don’t know if it’s a problem when I extended the Widget. Or how can you cast from TextBuffer to SourceViewBuffer.

I did tests in C and Vala and I don’t have that problem.

Thanks.

You can cast it via e.g. buffer.downcast_ref::<gtksourceview::SourceBuffer>() or buffer.downcast::<gtksourceview::SourceBuffer>(). The first will give you a reference, the second will take ownership of the buffer.

1 Like

Thank you very much for the reply.

Could you confirm if it is normal to have to do a ‘downcast’ in this type of case? I tried to extend from other Widget and I didn’t have that problem.

I was afraid that it could be a problem when I implemented that Widget.

Thank you again.

buffer() comes from gtk::TextView and doesn’t know that SourceView always has a text buffer of that specific type, so casting is necessary just like in C and other languages… however you say that casting is not necessary in C and Vala? Can you show code for that?

1 Like

Sorry for the time I took from you.

I had the error of assuming that GtkSourceView had a get_source_buffer (...) method.

I see that in any case (or binding) the correct thing is to get the TextBuffer from the GtkSourceView and cast to GtkSourceBuffer

Again: Sorry! :sweat:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.