gtk4/
text_buffer.rs

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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{boxed::Box as Box_, mem::transmute, slice, str};

use glib::{
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use libc::{c_char, c_int};

use crate::{ffi, prelude::*, TextBuffer, TextIter, TextTag};

#[cfg(feature = "v4_16")]
use crate::TextBufferNotifyFlags;

// rustdoc-stripper-ignore-next
/// Trait containing manually implemented methods of
/// [`TextBuffer`](crate::TextBuffer).
pub trait TextBufferExtManual: IsA<TextBuffer> + 'static {
    // rustdoc-stripper-ignore-next
    /// # Panics
    ///
    /// If the properties don't exists or are not writeable.
    // rustdoc-stripper-ignore-next-stop
    /// Creates a tag and adds it to the tag table for @self.
    ///
    /// Equivalent to calling [`TextTag::new()`][crate::TextTag::new()] and then adding the
    /// tag to the buffer’s tag table. The returned tag is owned by
    /// the buffer’s tag table, so the ref count will be equal to one.
    ///
    /// If @tag_name is [`None`], the tag is anonymous.
    ///
    /// If @tag_name is non-[`None`], a tag called @tag_name must not already
    /// exist in the tag table for this buffer.
    ///
    /// The @first_property_name argument and subsequent arguments are a list
    /// of properties to set on the tag, as with g_object_set().
    /// ## `tag_name`
    /// name of the new tag
    /// ## `first_property_name`
    /// name of first property to set
    ///
    /// # Returns
    ///
    /// a new tag
    #[doc(alias = "gtk_text_buffer_create_tag")]
    fn create_tag(
        &self,
        tag_name: Option<&str>,
        properties: &[(&str, &dyn ToValue)],
    ) -> Option<TextTag> {
        let tag = TextTag::new(tag_name);
        tag.set_properties(properties);
        if self.as_ref().tag_table().add(&tag) {
            Some(tag)
        } else {
            None
        }
    }

    /// Inserts @text into @self at @iter, applying the list of tags to
    /// the newly-inserted text.
    ///
    /// The last tag specified must be [`None`] to terminate the list.
    /// Equivalent to calling [`TextBufferExt::insert()`][crate::prelude::TextBufferExt::insert()],
    /// then [`TextBufferExt::apply_tag()`][crate::prelude::TextBufferExt::apply_tag()] on the inserted text;
    /// this is just a convenience function.
    /// ## `iter`
    /// an iterator in @self
    /// ## `text`
    /// UTF-8 text
    /// ## `len`
    /// length of @text, or -1
    /// ## `first_tag`
    /// first tag to apply to @text
    #[doc(alias = "gtk_text_buffer_insert_with_tags")]
    fn insert_with_tags(&self, iter: &mut TextIter, text: &str, tags: &[&TextTag]) {
        let start_offset = iter.offset();
        self.as_ref().insert(iter, text);
        let start_iter = self.as_ref().iter_at_offset(start_offset);
        tags.iter().for_each(|tag| {
            self.as_ref().apply_tag(&(*tag).clone(), &start_iter, iter);
        });
    }

    /// Inserts @text into @self at @iter, applying the list of tags to
    /// the newly-inserted text.
    ///
    /// Same as [`insert_with_tags()`][Self::insert_with_tags()], but allows you
    /// to pass in tag names instead of tag objects.
    /// ## `iter`
    /// position in @self
    /// ## `text`
    /// UTF-8 text
    /// ## `len`
    /// length of @text, or -1
    /// ## `first_tag_name`
    /// name of a tag to apply to @text
    #[doc(alias = "gtk_text_buffer_insert_with_tags_by_name")]
    fn insert_with_tags_by_name(&self, iter: &mut TextIter, text: &str, tags_names: &[&str]) {
        let start_offset = iter.offset();
        self.as_ref().insert(iter, text);
        let start_iter = self.as_ref().iter_at_offset(start_offset);
        let tag_table = self.as_ref().tag_table();
        tags_names.iter().for_each(|tag_name| {
            if let Some(tag) = tag_table.lookup(tag_name) {
                self.as_ref().apply_tag(&tag, &start_iter, iter);
            } else {
                glib::g_warning!("TextBuffer", "No tag with name {}!", tag_name);
            }
        });
    }

    /// Emitted to insert text in a [`TextBuffer`][crate::TextBuffer].
    ///
    /// Insertion actually occurs in the default handler.
    ///
    /// Note that if your handler runs before the default handler
    /// it must not invalidate the @location iter (or has to
    /// revalidate it). The default signal handler revalidates
    /// it to point to the end of the inserted text.
    ///
    /// See also: [`TextBufferExt::insert()`][crate::prelude::TextBufferExt::insert()],
    /// [`TextBufferExt::insert_range()`][crate::prelude::TextBufferExt::insert_range()].
    /// ## `location`
    /// position to insert @text in @textbuffer
    /// ## `text`
    /// the UTF-8 text to be inserted
    /// ## `len`
    /// length of the inserted text in bytes
    fn connect_insert_text<F: Fn(&Self, &mut TextIter, &str) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe {
            unsafe extern "C" fn insert_text_trampoline<
                T,
                F: Fn(&T, &mut TextIter, &str) + 'static,
            >(
                this: *mut ffi::GtkTextBuffer,
                location: *mut ffi::GtkTextIter,
                text: *mut c_char,
                len: c_int,
                f: glib::ffi::gpointer,
            ) where
                T: IsA<TextBuffer>,
            {
                let mut location_copy = from_glib_none(location);
                let f: &F = &*(f as *const F);
                let text = if len <= 0 {
                    &[]
                } else {
                    slice::from_raw_parts(text as *const u8, len as usize)
                };

                f(
                    TextBuffer::from_glib_borrow(this).unsafe_cast_ref(),
                    &mut location_copy,
                    str::from_utf8(text).unwrap(),
                )
            }
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.to_glib_none().0 as *mut _,
                c"insert-text".as_ptr() as *mut _,
                Some(transmute::<usize, unsafe extern "C" fn()>(
                    insert_text_trampoline::<Self, F> as usize,
                )),
                Box_::into_raw(f),
            )
        }
    }

    /// Adds a `callback::Gtk::TextBufferCommitNotify to be called when a change
    /// is to be made to the [type@Gtk.TextBuffer].
    ///
    /// Functions are explicitly forbidden from making changes to the
    /// [type@Gtk.TextBuffer] from this callback. It is intended for tracking
    /// changes to the buffer only.
    ///
    /// It may be advantageous to use `callback::Gtk::TextBufferCommitNotify over
    /// connecting to the [`insert-text`][struct@crate::TextBuffer#insert-text] or
    /// [`delete-range`][struct@crate::TextBuffer#delete-range] signals to avoid ordering issues with
    /// other signal handlers which may further modify the [type@Gtk.TextBuffer].
    /// ## `flags`
    /// which notifications should be dispatched to @callback
    /// ## `commit_notify`
    /// a
    ///   `callback::Gtk::TextBufferCommitNotify to call for commit notifications
    ///
    /// # Returns
    ///
    /// a handler id which may be used to remove the commit notify
    ///   callback using [`TextBufferExt::remove_commit_notify()`][crate::prelude::TextBufferExt::remove_commit_notify()].
    #[cfg(feature = "v4_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_16")))]
    #[doc(alias = "gtk_text_buffer_add_commit_notify")]
    fn add_commit_notify<P: Fn(&TextBuffer, TextBufferNotifyFlags, u32, u32) + 'static>(
        &self,
        flags: TextBufferNotifyFlags,
        commit_notify: P,
    ) -> u32 {
        let commit_notify_data: Box_<P> = Box_::new(commit_notify);
        unsafe extern "C" fn commit_notify_func<
            P: Fn(&TextBuffer, TextBufferNotifyFlags, u32, u32) + 'static,
        >(
            buffer: *mut ffi::GtkTextBuffer,
            flags: ffi::GtkTextBufferNotifyFlags,
            position: std::ffi::c_uint,
            length: std::ffi::c_uint,
            user_data: glib::ffi::gpointer,
        ) {
            let buffer = from_glib_borrow(buffer);
            let flags = from_glib(flags);
            let callback = &*(user_data as *mut P);
            (*callback)(&buffer, flags, position, length)
        }
        let commit_notify = Some(commit_notify_func::<P> as _);
        unsafe extern "C" fn destroy_func<
            P: Fn(&TextBuffer, TextBufferNotifyFlags, u32, u32) + 'static,
        >(
            data: glib::ffi::gpointer,
        ) {
            let _callback = Box_::from_raw(data as *mut P);
        }
        let destroy_call4 = Some(destroy_func::<P> as _);
        let super_callback0: Box_<P> = commit_notify_data;
        unsafe {
            ffi::gtk_text_buffer_add_commit_notify(
                self.as_ref().to_glib_none().0,
                flags.into_glib(),
                commit_notify,
                Box_::into_raw(super_callback0) as *mut _,
                destroy_call4,
            )
        }
    }
}

impl<O: IsA<TextBuffer>> TextBufferExtManual for O {}

impl std::fmt::Write for TextBuffer {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        let mut iter = self.end_iter();
        self.insert(&mut iter, s);
        Ok(())
    }
}