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
// 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::{prelude::*, TextBuffer, TextIter, TextTag};

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::TextBuffer>> Sealed for T {}
}

// rustdoc-stripper-ignore-next
/// Trait containing manually implemented methods of
/// [`TextBuffer`](crate::TextBuffer).
pub trait TextBufferExtManual: sealed::Sealed + 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 _,
                b"insert-text\0".as_ptr() as *mut _,
                Some(transmute(insert_text_trampoline::<Self, F> as usize)),
                Box_::into_raw(f),
            )
        }
    }
}

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(())
    }
}