weechat 0.4.0

Weechat API bindings for Rust
Documentation
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! Weechat Buffer module containing Buffer and Nick types.

mod lines;
mod nick;
mod nickgroup;

use std::{
    borrow::Cow,
    cmp::{Ord, Ordering},
    ffi::{c_void, CStr},
    marker::PhantomData,
    ptr,
};

use std::{cell::Cell, rc::Rc};

#[cfg(feature = "async")]
use async_trait::async_trait;
#[cfg(feature = "async")]
use futures::future::LocalBoxFuture;

use crate::{LossyCString, Weechat};
use libc::{c_char, c_int};
use weechat_sys::{
    t_gui_buffer, t_gui_nick, t_hdata, t_weechat_plugin, WEECHAT_RC_ERROR, WEECHAT_RC_OK,
};

pub use crate::buffer::{
    lines::{BufferLine, BufferLines, LineData},
    nick::{Nick, NickSettings},
    nickgroup::NickGroup,
};

/// A Weechat buffer.
///
/// A buffer contains the data displayed on the screen.
pub struct Buffer<'a> {
    pub(crate) inner: InnerBuffers<'a>,
}

impl<'a> std::fmt::Debug for Buffer<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Buffer")
            .field("full_name", &self.full_name())
            .finish()
    }
}

pub(crate) enum InnerBuffers<'a> {
    BorrowedBuffer(InnerBuffer<'a>),
    OwnedBuffer(InnerOwnedBuffer<'a>),
}

impl<'a> InnerBuffers<'a> {
    fn is_closing(&self) -> bool {
        match self {
            InnerBuffers::BorrowedBuffer(b) => b.closing.get(),
            InnerBuffers::OwnedBuffer(b) => b.closing.get(),
        }
    }

    fn mark_as_closing(&self) {
        match self {
            InnerBuffers::BorrowedBuffer(b) => b.closing.as_ref().replace(true),
            InnerBuffers::OwnedBuffer(b) => b.closing.as_ref().replace(true),
        };
    }
}

impl<'a> InnerBuffers<'a> {
    pub(crate) fn weechat_ptr(&self) -> *mut t_weechat_plugin {
        match self {
            InnerBuffers::BorrowedBuffer(b) => b.weechat,
            InnerBuffers::OwnedBuffer(b) => b.weechat,
        }
    }
}

pub(crate) struct InnerOwnedBuffer<'a> {
    pub(crate) weechat: *mut t_weechat_plugin,
    pub(crate) buffer_handle: &'a BufferHandle,
    closing: Rc<Cell<bool>>,
}

pub(crate) struct InnerBuffer<'a> {
    pub(crate) weechat: *mut t_weechat_plugin,
    pub(crate) ptr: *mut t_gui_buffer,
    pub(crate) weechat_phantom: PhantomData<&'a Weechat>,
    pub(crate) closing: Rc<Cell<bool>>,
}

impl PartialEq for Buffer<'_> {
    fn eq(&self, other: &Buffer) -> bool {
        self.ptr() == other.ptr()
    }
}

impl PartialOrd for Buffer<'_> {
    fn partial_cmp(&self, other: &Buffer) -> Option<Ordering> {
        self.number().partial_cmp(&other.number())
    }
}

impl Eq for Buffer<'_> {}

impl Ord for Buffer<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.number().cmp(&other.number())
    }
}

/// A handle to a buffer that was created in the current plugin.
///
/// This means that the plugin owns this buffer. Nevertheless Weechat can
/// invalidate the buffer between callbacks at any point in time.
///
/// The buffer handle can be upgraded to a buffer which can then manipulate the
/// buffer state using the `upgrade()` method.
///
/// The buffer won't be closed if this handle gets dropped, to close the buffer
/// call the close method on the upgraded buffer object.
#[derive(Clone)]
pub struct BufferHandle {
    buffer_name: Rc<String>,
    weechat: *mut t_weechat_plugin,
    buffer_ptr: Rc<Cell<*mut t_gui_buffer>>,
    closing: Rc<Cell<bool>>,
}

impl BufferHandle {
    /// Upgrade the buffer handle into a `Buffer`.
    ///
    /// This is necessary to do because the handle can be invalidated by Weechat
    /// between callbacks.
    pub fn upgrade(&self) -> Result<Buffer<'_>, ()> {
        let ptr = self.buffer_ptr.get();

        if ptr.is_null() {
            Err(())
        } else {
            let buffer = Buffer {
                inner: InnerBuffers::OwnedBuffer(InnerOwnedBuffer {
                    weechat: self.weechat,
                    buffer_handle: self,
                    closing: self.closing.clone(),
                }),
            };
            Ok(buffer)
        }
    }
}

#[cfg(feature = "async")]
pub(crate) struct BufferPointersAsync {
    pub(crate) weechat: *mut t_weechat_plugin,
    pub(crate) input_cb: Option<Box<dyn BufferInputCallbackAsync>>,
    pub(crate) close_cb: Option<Box<dyn BufferCloseCallback>>,
    pub(crate) buffer_cell: Option<Rc<Cell<*mut t_gui_buffer>>>,
}

pub(crate) struct BufferPointers {
    pub(crate) weechat: *mut t_weechat_plugin,
    pub(crate) input_cb: Option<Box<dyn BufferInputCallback>>,
    pub(crate) close_cb: Option<Box<dyn BufferCloseCallback>>,
    pub(crate) buffer_cell: Option<Rc<Cell<*mut t_gui_buffer>>>,
}

/// Trait for the buffer input callback
///
/// This is the sync version of the callback.
///
/// A blanket implementation for pure `FnMut` functions exists, if data needs to
/// be passed to the callback implement this over your struct.
pub trait BufferInputCallback: 'static {
    /// Callback that will be called when the buffer receives some input.
    ///
    /// # Arguments
    ///
    /// * `weechat` - A Weechat context.
    ///
    /// * `buffer` - The buffer that received the input
    ///
    /// * `input` - The input that was received.
    fn callback(&mut self, weechat: &Weechat, buffer: &Buffer, input: Cow<str>) -> Result<(), ()>;
}

impl<T: FnMut(&Weechat, &Buffer, Cow<str>) -> Result<(), ()> + 'static> BufferInputCallback for T {
    /// Callback that will be called if the user inputs something into the buffer
    /// input field.
    ///
    /// # Arguments
    ///
    /// * `weechat` - A Weechat context.
    ///
    /// * `buffer` - The buffer that the user inputed some text into.
    ///
    /// * `input` - The input that was posted by the user.
    fn callback(&mut self, weechat: &Weechat, buffer: &Buffer, input: Cow<str>) -> Result<(), ()> {
        self(weechat, buffer, input)
    }
}

/// Trait for the buffer close callback
///
/// A blanket implementation for pure `FnMut` functions exists, if data needs to
/// be passed to the callback implement this over your struct.
pub trait BufferCloseCallback {
    /// Callback that will be called before the buffer is closed.
    ///
    /// # Arguments
    ///
    /// * `weechat` - A Weechat context.
    ///
    /// * `buffer` - The buffer that will be closed.
    fn callback(&mut self, weechat: &Weechat, buffer: &Buffer) -> Result<(), ()>;
}

impl<T: FnMut(&Weechat, &Buffer) -> Result<(), ()> + 'static> BufferCloseCallback for T {
    fn callback(&mut self, weechat: &Weechat, buffer: &Buffer) -> Result<(), ()> {
        self(weechat, buffer)
    }
}

#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(r#async)))]
#[async_trait(?Send)]
/// Trait for the buffer input callback.
///
/// This is the async version of the callback.
///
/// A blanket implementation for pure `FnMut` functions exists, if data needs to
/// be passed to the callback implement this over your struct.
pub trait BufferInputCallbackAsync: 'static {
    /// Callback that will be called if the user inputs something into the buffer
    /// input field.
    ///
    /// # Arguments
    ///
    /// * `weechat` - A Weechat context.
    ///
    /// * `buffer` - The buffer that the user inputed some text into.
    ///
    /// * `input` - The input that was posted by the user.
    async fn callback(&mut self, buffer: BufferHandle, input: String);
}

#[cfg(feature = "async")]
#[async_trait(?Send)]
impl<T: FnMut(BufferHandle, String) -> LocalBoxFuture<'static, ()> + 'static>
    BufferInputCallbackAsync for T
{
    async fn callback(&mut self, buffer: BufferHandle, input: String) {
        self(buffer, input).await
    }
}

#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(r#async)))]
/// Builder for the creation of a buffer.
pub struct BufferBuilderAsync {
    pub(crate) name: String,
    pub(crate) input_callback: Option<Box<dyn BufferInputCallbackAsync>>,
    pub(crate) close_callback: Option<Box<dyn BufferCloseCallback>>,
}

/// Builder for the creation of a buffer.
pub struct BufferBuilder {
    pub(crate) name: String,
    pub(crate) input_callback: Option<Box<dyn BufferInputCallback>>,
    pub(crate) close_callback: Option<Box<dyn BufferCloseCallback>>,
}

#[cfg(feature = "async")]
impl BufferBuilderAsync {
    /// Create a new buffer builder that will create a buffer with an async
    /// input callback.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the new buffer. Needs to be unique across a
    /// plugin, otherwise the buffer creation will fail.
    ///
    /// Returns a Buffer if one has been created, otherwise an empty Error.
    ///
    /// # Panics
    ///
    /// Panics if the method is not called from the main Weechat thread.
    ///
    /// # Example
    /// ```no_run
    /// # use futures::future::{FutureExt, LocalBoxFuture};
    /// # use weechat::Weechat;
    /// # use weechat::buffer::{BufferHandle, Buffer, BufferBuilderAsync};
    /// fn input_cb(buffer: BufferHandle, input: String) -> LocalBoxFuture<'static, ()> {
    ///     async move {
    ///         let buffer = buffer.upgrade().unwrap();
    ///         buffer.print(&input);
    ///     }.boxed_local()
    /// }
    ///
    /// let buffer_handle = BufferBuilderAsync::new("test_buffer")
    ///     .input_callback(input_cb)
    ///     .close_callback(|weechat: &Weechat, buffer: &Buffer| {
    ///         Ok(())
    /// })
    ///     .build()
    ///     .expect("Can't create new buffer");
    ///
    /// let buffer = buffer_handle
    ///     .upgrade()
    ///     .expect("Can't upgrade newly created buffer");
    ///
    /// buffer.enable_nicklist();
    /// buffer.print("Hello world");
    /// ```
    pub fn new(name: &str) -> Self {
        BufferBuilderAsync {
            name: name.to_owned(),
            input_callback: None,
            close_callback: None,
        }
    }

    /// Set the buffer input callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - An async function that will be called once a user inputs
    ///     data into the buffer input line.
    pub fn input_callback(mut self, callback: impl BufferInputCallbackAsync) -> Self {
        self.input_callback = Some(Box::new(callback));
        self
    }

    /// Set the close callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - The callback that should be called before a buffer is
    ///     closed.
    pub fn close_callback(mut self, callback: impl BufferCloseCallback + 'static) -> Self {
        self.close_callback = Some(Box::new(callback));
        self
    }

    /// Build the configured buffer.
    pub fn build(self) -> Result<BufferHandle, ()> {
        Weechat::buffer_new_with_async(self)
    }
}

impl BufferBuilder {
    /// Create a new buffer builder that will create a buffer with an sync input
    /// callback.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the new buffer. Needs to be unique across a
    /// plugin, otherwise the buffer creation will fail.
    ///
    /// # Panics
    ///
    /// Panics if the method is not called from the main Weechat thread.
    ///
    /// Returns a Buffer if one has been created, otherwise an empty Error.
    ///
    /// # Example
    /// ```no_run
    /// # use std::borrow::Cow;
    /// # use weechat::Weechat;
    /// # use weechat::buffer::{Buffer, BufferHandle, BufferBuilder};
    /// fn input_cb(weechat: &Weechat, buffer: &Buffer, input: Cow<str>) -> Result<(), ()> {
    ///     buffer.print(&input);
    ///     Ok(())
    /// }
    ///
    /// let buffer_handle = BufferBuilder::new("test_buffer")
    ///     .input_callback(input_cb)
    ///     .close_callback(|weechat: &Weechat, buffer: &Buffer| {
    ///         Ok(())
    /// })
    ///     .build()
    ///     .expect("Can't create new buffer");
    ///
    /// let buffer = buffer_handle
    ///     .upgrade()
    ///     .expect("Can't upgrade newly created buffer");
    ///
    /// buffer.enable_nicklist();
    /// buffer.print("Hello world");
    /// ```
    pub fn new(name: &str) -> Self {
        BufferBuilder {
            name: name.to_owned(),
            input_callback: None,
            close_callback: None,
        }
    }

    /// Set the buffer input callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - A function or a struct that implements the
    /// BufferCloseCallback trait.
    pub fn input_callback(mut self, callback: impl BufferInputCallback + 'static) -> Self {
        self.input_callback = Some(Box::new(callback));
        self
    }

    /// Set the close callback.
    ///
    /// # Arguments
    ///
    /// * `callback` - The callback that should be called before a buffer is
    pub fn close_callback(mut self, callback: impl BufferCloseCallback + 'static) -> Self {
        self.close_callback = Some(Box::new(callback));
        self
    }

    /// Build the configured buffer.
    pub fn build(self) -> Result<BufferHandle, ()> {
        Weechat::buffer_new(self)
    }
}

impl Weechat {
    /// Search a buffer by plugin and/or name.
    ///
    /// Returns a Buffer if one is found, otherwise None.
    ///
    /// # Arguments
    ///
    /// * `plugin_name` - name of a plugin, the following special value is
    ///     allowed: "==", the buffer name used is the buffers full name.
    ///
    /// * `buffer_name` - name of a buffer, if this is an empty string,
    ///     the current buffer is returned (buffer displayed by current
    ///     window); if the name starts with (?i), the search is case
    ///     insensitive.
    pub fn buffer_search(&self, plugin_name: &str, buffer_name: &str) -> Option<Buffer> {
        let buffer_search = self.get().buffer_search.unwrap();

        let plugin_name = LossyCString::new(plugin_name);
        let buffer_name = LossyCString::new(buffer_name);

        let buf_ptr = unsafe { buffer_search(plugin_name.as_ptr(), buffer_name.as_ptr()) };

        if buf_ptr.is_null() {
            None
        } else {
            Some(self.buffer_from_ptr(buf_ptr))
        }
    }

    pub(crate) fn buffer_from_ptr(&self, buffer_ptr: *mut t_gui_buffer) -> Buffer {
        Buffer {
            inner: InnerBuffers::BorrowedBuffer(InnerBuffer {
                weechat: self.ptr,
                ptr: buffer_ptr,
                weechat_phantom: PhantomData,
                closing: Rc::new(Cell::new(false)),
            }),
        }
    }

    /// Get the currently open buffer
    pub fn current_buffer(&self) -> Buffer {
        let buffer_search = self.get().buffer_search.unwrap();

        let buf_ptr = unsafe { buffer_search(ptr::null(), ptr::null()) };
        if buf_ptr.is_null() {
            panic!("No open buffer found");
        } else {
            self.buffer_from_ptr(buf_ptr)
        }
    }

    #[cfg(feature = "async")]
    #[cfg_attr(feature = "docs", doc(cfg(r#async)))]
    fn buffer_new_with_async(builder: BufferBuilderAsync) -> Result<BufferHandle, ()> {
        unsafe extern "C" fn c_input_cb(
            pointer: *const c_void,
            _data: *mut c_void,
            buffer: *mut t_gui_buffer,
            input_data: *const c_char,
        ) -> c_int {
            let input_data = CStr::from_ptr(input_data).to_string_lossy();

            let pointers: &mut BufferPointersAsync =
                { &mut *(pointer as *mut BufferPointersAsync) };

            let weechat = Weechat::from_ptr(pointers.weechat);
            let buffer = weechat.buffer_from_ptr(buffer);
            let buffer_cell = pointers
                .buffer_cell
                .as_ref()
                .expect("Buffer cell wasn't initialized properly")
                .clone();

            let buffer_handle = BufferHandle {
                buffer_name: Rc::new(buffer.full_name().to_string()),
                weechat: pointers.weechat,
                buffer_ptr: buffer_cell,
                closing: Rc::new(Cell::new(false)),
            };
            if let Some(cb) = pointers.input_cb.as_mut() {
                let future = cb.callback(buffer_handle, input_data.to_string());
                Weechat::spawn_buffer_cb(buffer.full_name().to_string(), future).detach();
            }

            WEECHAT_RC_OK
        }

        unsafe extern "C" fn c_close_cb(
            pointer: *const c_void,
            _data: *mut c_void,
            buffer: *mut t_gui_buffer,
        ) -> c_int {
            // We use from_raw() here so that the box gets deallocated at the
            // end of this scope.
            let pointers = Box::from_raw(pointer as *mut BufferPointersAsync);
            let weechat = Weechat::from_ptr(pointers.weechat);
            let buffer = weechat.buffer_from_ptr(buffer);
            buffer.mark_as_closing();

            let ret = if let Some(mut cb) = pointers.close_cb {
                cb.callback(&weechat, &buffer).is_ok()
            } else {
                true
            };

            // Invalidate the buffer pointer now.
            pointers
                .buffer_cell
                .as_ref()
                .expect("Buffer cell wasn't initialized properly")
                .replace(ptr::null_mut());

            if ret {
                WEECHAT_RC_OK
            } else {
                WEECHAT_RC_ERROR
            }
        }

        Weechat::check_thread();
        let weechat = unsafe { Weechat::weechat() };

        let c_input_cb: Option<WeechatInputCbT> = match builder.input_callback {
            Some(_) => Some(c_input_cb),
            None => None,
        };

        // We create a box and use leak to stop rust from freeing our data,
        // we are giving Weechat ownership over the data and will free it in
        // the buffer close callback.
        let buffer_pointers = Box::new(BufferPointersAsync {
            weechat: weechat.ptr,
            input_cb: builder.input_callback,
            close_cb: builder.close_callback,
            buffer_cell: None,
        });

        let buffer_pointers_ref = Box::leak(buffer_pointers);

        let buf_new = weechat.get().buffer_new.unwrap();
        let c_name = LossyCString::new(builder.name);

        let buf_ptr = unsafe {
            buf_new(
                weechat.ptr,
                c_name.as_ptr(),
                c_input_cb,
                buffer_pointers_ref as *const _ as *const c_void,
                ptr::null_mut(),
                Some(c_close_cb),
                buffer_pointers_ref as *const _ as *const c_void,
                ptr::null_mut(),
            )
        };

        if buf_ptr.is_null() {
            unsafe { Box::from_raw(buffer_pointers_ref) };
            return Err(());
        }

        let pointers: &mut BufferPointersAsync =
            unsafe { &mut *(buffer_pointers_ref as *mut BufferPointersAsync) };

        let buffer = weechat.buffer_from_ptr(buf_ptr);
        let buffer_cell = Rc::new(Cell::new(buf_ptr));

        pointers.buffer_cell = Some(buffer_cell.clone());

        Ok(BufferHandle {
            buffer_name: Rc::new(buffer.full_name().to_string()),
            weechat: weechat.ptr,
            buffer_ptr: buffer_cell,
            closing: Rc::new(Cell::new(false)),
        })
    }

    fn buffer_new(builder: BufferBuilder) -> Result<BufferHandle, ()> {
        unsafe extern "C" fn c_input_cb(
            pointer: *const c_void,
            _data: *mut c_void,
            buffer: *mut t_gui_buffer,
            input_data: *const c_char,
        ) -> c_int {
            let input_data = CStr::from_ptr(input_data).to_string_lossy();

            let pointers: &mut BufferPointers = { &mut *(pointer as *mut BufferPointers) };

            let weechat = Weechat::from_ptr(pointers.weechat);
            let buffer = weechat.buffer_from_ptr(buffer);

            let ret = if let Some(ref mut cb) = pointers.input_cb.as_mut() {
                cb.callback(&weechat, &buffer, input_data).is_ok()
            } else {
                true
            };

            if ret {
                WEECHAT_RC_OK
            } else {
                WEECHAT_RC_ERROR
            }
        }

        unsafe extern "C" fn c_close_cb(
            pointer: *const c_void,
            _data: *mut c_void,
            buffer: *mut t_gui_buffer,
        ) -> c_int {
            // We use from_raw() here so that the box gets freed at the end
            // of this scope.
            let pointers = Box::from_raw(pointer as *mut BufferPointers);
            let weechat = Weechat::from_ptr(pointers.weechat);
            let buffer = weechat.buffer_from_ptr(buffer);
            buffer.mark_as_closing();

            let ret = if let Some(mut cb) = pointers.close_cb {
                cb.callback(&weechat, &buffer).is_ok()
            } else {
                true
            };

            // Invalidate the buffer pointer now.
            pointers
                .buffer_cell
                .as_ref()
                .expect("Buffer cell wasn't initialized properly")
                .replace(ptr::null_mut());

            if ret {
                WEECHAT_RC_OK
            } else {
                WEECHAT_RC_ERROR
            }
        }

        Weechat::check_thread();
        let weechat = unsafe { Weechat::weechat() };

        let c_input_cb: Option<WeechatInputCbT> = match builder.input_callback {
            Some(_) => Some(c_input_cb),
            None => None,
        };

        // We create a box and use leak to stop rust from freeing our data,
        // we are giving weechat ownership over the data and will free it in
        // the buffer close callback.
        let buffer_pointers = Box::new(BufferPointers {
            weechat: weechat.ptr,
            input_cb: builder.input_callback,
            close_cb: builder.close_callback,
            buffer_cell: None,
        });
        let buffer_pointers_ref = Box::leak(buffer_pointers);

        let buf_new = weechat.get().buffer_new.unwrap();
        let c_name = LossyCString::new(builder.name);

        let buf_ptr = unsafe {
            buf_new(
                weechat.ptr,
                c_name.as_ptr(),
                c_input_cb,
                buffer_pointers_ref as *const _ as *const c_void,
                ptr::null_mut(),
                Some(c_close_cb),
                buffer_pointers_ref as *const _ as *const c_void,
                ptr::null_mut(),
            )
        };

        if buf_ptr.is_null() {
            unsafe { Box::from_raw(buffer_pointers_ref) };
            return Err(());
        }

        let pointers: &mut BufferPointers =
            unsafe { &mut *(buffer_pointers_ref as *mut BufferPointers) };

        let buffer = weechat.buffer_from_ptr(buf_ptr);
        let buffer_cell = Rc::new(Cell::new(buf_ptr));

        pointers.buffer_cell = Some(buffer_cell.clone());

        Ok(BufferHandle {
            buffer_name: Rc::new(buffer.full_name().to_string()),
            weechat: weechat.ptr,
            buffer_ptr: buffer_cell,
            closing: Rc::new(Cell::new(false)),
        })
    }
}

pub(crate) type WeechatInputCbT = unsafe extern "C" fn(
    pointer: *const c_void,
    data: *mut c_void,
    buffer: *mut t_gui_buffer,
    input_data: *const c_char,
) -> c_int;

impl Buffer<'_> {
    fn weechat(&self) -> Weechat {
        let ptr = match &self.inner {
            InnerBuffers::BorrowedBuffer(b) => b.weechat,
            InnerBuffers::OwnedBuffer(b) => b.weechat,
        };

        Weechat::from_ptr(ptr)
    }

    pub(crate) fn ptr(&self) -> *mut t_gui_buffer {
        match &self.inner {
            InnerBuffers::BorrowedBuffer(b) => b.ptr,
            InnerBuffers::OwnedBuffer(b) => {
                let ptr = b.buffer_handle.buffer_ptr.get();

                if ptr.is_null() {
                    panic!("Buffer {} has been closed.", b.buffer_handle.buffer_name)
                } else {
                    ptr
                }
            }
        }
    }

    fn is_closing(&self) -> bool {
        self.inner.is_closing()
    }

    fn mark_as_closing(&self) {
        self.inner.mark_as_closing()
    }

    /// Display a message on the buffer.
    pub fn print(&self, message: &str) {
        let weechat = self.weechat();
        let printf_date_tags = weechat.get().printf_date_tags.unwrap();

        let fmt_str = LossyCString::new("%s");
        let c_message = LossyCString::new(message);

        unsafe {
            printf_date_tags(
                self.ptr(),
                0,
                ptr::null(),
                fmt_str.as_ptr(),
                c_message.as_ptr(),
            )
        }
    }

    /// Display a message on the buffer with attached date and tags
    ///
    /// # Arguments
    ///
    /// * `date` - A unix time-stamp representing the date of the message, 0
    ///     means now.
    ///
    /// * `tags` - A list of tags that will be applied to the printed line.
    ///
    /// * `message` - The message that will be displayed.
    pub fn print_date_tags(&self, date: i64, tags: &[&str], message: &str) {
        let weechat = self.weechat();
        let printf_date_tags = weechat.get().printf_date_tags.unwrap();

        let fmt_str = LossyCString::new("%s");
        let tags = tags.join(",");
        let tags = LossyCString::new(tags);
        let message = LossyCString::new(message);

        unsafe {
            printf_date_tags(
                self.ptr(),
                date,
                tags.as_ptr(),
                fmt_str.as_ptr(),
                message.as_ptr(),
            )
        }
    }

    /// Search for a nicklist group by name
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the nicklist that should be searched for.
    ///
    /// Returns a NickGroup if one is found, None otherwise.
    pub fn search_nicklist_group(&self, name: &str) -> Option<NickGroup> {
        let weechat = self.weechat();

        let nicklist_search_group = weechat.get().nicklist_search_group.unwrap();

        let name = LossyCString::new(name);

        let group = unsafe { nicklist_search_group(self.ptr(), ptr::null_mut(), name.as_ptr()) };

        if group.is_null() {
            None
        } else {
            Some(NickGroup {
                ptr: group,
                buf_ptr: self.ptr(),
                weechat_ptr: self.weechat().ptr,
                buffer: PhantomData,
            })
        }
    }

    /// Search for a nick in the whole nicklist.
    ///
    /// # Arguments
    ///
    /// * `nick` - The name of the nick that should be found.
    ///
    /// Returns a `Nick` if one is found, None otherwise.
    pub fn search_nick(&self, nick: &str) -> Option<Nick> {
        let weechat = self.weechat();
        let nick = Buffer::search_nick_helper(&weechat, self.ptr(), nick, None);

        if nick.is_null() {
            None
        } else {
            Some(Nick {
                ptr: nick,
                buf_ptr: self.ptr(),
                weechat_ptr: weechat.ptr,
                buffer: PhantomData,
            })
        }
    }

    fn search_nick_helper(
        weechat: &Weechat,
        buffer_ptr: *mut t_gui_buffer,
        nick: &str,
        group: Option<&NickGroup>,
    ) -> *mut t_gui_nick {
        let nicklist_search_nick = weechat.get().nicklist_search_nick.unwrap();

        let nick = LossyCString::new(nick);
        let group_ptr = group.map(|g| g.ptr).unwrap_or(ptr::null_mut());

        unsafe { nicklist_search_nick(buffer_ptr, group_ptr, nick.as_ptr()) }
    }

    /// Create and add a new nick to the buffer nicklist.
    ///
    /// This will add the nick to the root nick group.
    ///
    /// # Arguments
    ///
    /// * `nick_settings` - Nick arguments struct for the nick that should be
    ///     added.
    ///
    /// Returns the newly created nick if one is created successfully, an empty
    /// error otherwise.
    pub fn add_nick(&self, nick_settings: NickSettings) -> Result<Nick, ()> {
        let weechat = self.weechat();
        let nick_ptr = Buffer::add_nick_helper(&weechat, self.ptr(), nick_settings, None);

        if nick_ptr.is_null() {
            return Err(());
        }

        Ok(Nick {
            ptr: nick_ptr,
            buf_ptr: self.ptr(),
            weechat_ptr: self.weechat().ptr,
            buffer: PhantomData,
        })
    }

    /// Removes a group from the nicklist.
    ///
    /// # Arguments
    ///
    /// * `group_name` - The name of the group that should be removed.
    ///
    /// Returns `true` if a group was found and removed, `false` otherwise.
    pub fn remove_nicklist_group(&self, group_name: &str) -> bool {
        let weechat = self.weechat();

        let group = self.search_nicklist_group(group_name);

        match group {
            Some(group) => {
                let nicklist_remove_group = weechat.get().nicklist_remove_group.unwrap();

                unsafe {
                    nicklist_remove_group(self.ptr(), group.ptr);
                }
                true
            }
            None => false,
        }
    }

    /// Removes a nick from the nicklist.
    ///
    /// # Arguments
    ///
    /// * `nick` - The name of the nick that should be removed.
    ///
    /// Returns `true` if a nick was found and removed, `false` otherwise.
    pub fn remove_nick(&self, nick: &str) -> bool {
        let weechat = self.weechat();

        let nick = self.search_nick(nick);

        match nick {
            Some(nick) => {
                let nicklist_remove_nick = weechat.get().nicklist_remove_nick.unwrap();

                unsafe {
                    nicklist_remove_nick(self.ptr(), nick.ptr);
                }
                true
            }
            None => false,
        }
    }

    fn add_nick_helper(
        weechat: &Weechat,
        buffer_ptr: *mut t_gui_buffer,
        nick_settings: NickSettings,
        group: Option<&NickGroup>,
    ) -> *mut t_gui_nick {
        let c_nick = LossyCString::new(nick_settings.name);
        let color = LossyCString::new(nick_settings.color);
        let prefix = LossyCString::new(nick_settings.prefix);
        let prefix_color = LossyCString::new(nick_settings.prefix_color);

        let add_nick = weechat.get().nicklist_add_nick.unwrap();

        let group_ptr = match group {
            Some(g) => g.ptr,
            None => ptr::null_mut(),
        };

        unsafe {
            add_nick(
                buffer_ptr,
                group_ptr,
                c_nick.as_ptr(),
                color.as_ptr(),
                prefix.as_ptr(),
                prefix_color.as_ptr(),
                nick_settings.visible as i32,
            )
        }
    }

    /// Create and add a new nicklist group to the buffers nicklist.
    ///
    /// * `name` - Name of the new group.
    ///
    /// * `color` - Color of the new group.
    ///
    /// * `visible` - Should the group be visible in the nicklist.
    ///
    /// * `parent_group` - Parent group that the group should be added to.
    ///     If no group is provided the group is added to the root group.
    ///
    /// Returns the new nicklist group. The group is not removed if the object
    /// is dropped.
    pub fn add_nicklist_group(
        &self,
        name: &str,
        color: &str,
        visible: bool,
        parent_group: Option<&NickGroup>,
    ) -> Result<NickGroup, ()> {
        let weechat = self.weechat();
        let add_group = weechat.get().nicklist_add_group.unwrap();

        let c_name = LossyCString::new(name);
        let c_color = LossyCString::new(color);

        let group_ptr = match parent_group {
            Some(g) => g.ptr,
            None => ptr::null_mut(),
        };

        let group_ptr = unsafe {
            add_group(
                self.ptr(),
                group_ptr,
                c_name.as_ptr(),
                c_color.as_ptr(),
                visible as i32,
            )
        };

        if group_ptr.is_null() {
            return Err(());
        }

        Ok(NickGroup {
            ptr: group_ptr,
            buf_ptr: self.ptr(),
            weechat_ptr: self.weechat().ptr,
            buffer: PhantomData,
        })
    }

    fn set(&self, property: &str, value: &str) {
        let weechat = self.weechat();

        let buffer_set = weechat.get().buffer_set.unwrap();
        let option = LossyCString::new(property);
        let value = LossyCString::new(value);

        unsafe { buffer_set(self.ptr(), option.as_ptr(), value.as_ptr()) };
    }

    fn get_string(&self, property: &str) -> Option<Cow<str>> {
        let weechat = self.weechat();

        let buffer_get = weechat.get().buffer_get_string.unwrap();
        let property = LossyCString::new(property);

        unsafe {
            let value = buffer_get(self.ptr(), property.as_ptr());
            if value.is_null() {
                None
            } else {
                Some(CStr::from_ptr(value).to_string_lossy())
            }
        }
    }

    fn get_integer(&self, property: &str) -> i32 {
        let weechat = self.weechat();

        let buffer_get = weechat.get().buffer_get_integer.unwrap();
        let property = LossyCString::new(property);

        unsafe { buffer_get(self.ptr(), property.as_ptr()) }
    }

    /// Get the value of a buffer localvar
    ///
    /// # Arguments
    ///
    /// * `property` - The name of the property for which the value should be
    ///     fetched.
    pub fn get_localvar(&self, property: &str) -> Option<Cow<str>> {
        self.get_string(&format!("localvar_{}", property))
    }

    /// Set the value of a buffer localvar
    ///
    /// # Arguments
    ///
    /// * `property` - The property that should be set.
    ///
    /// * `value` - The value that the property should get.
    pub fn set_localvar(&self, property: &str, value: &str) {
        self.set(&format!("localvar_set_{}", property), value)
    }

    /// Get the full name of the buffer.
    pub fn full_name(&self) -> Cow<str> {
        self.get_string("full_name").unwrap()
    }

    /// Set the full name of the buffer
    ///
    /// # Arguments
    ///
    /// * `name` - The new full name that should be set.
    pub fn set_full_name(&self, name: &str) {
        self.set("full_name", name);
    }

    /// Get the name of the buffer.
    pub fn name(&self) -> Cow<str> {
        self.get_string("name").unwrap()
    }

    /// Set the name of the buffer.
    ///
    /// # Arguments
    ///
    /// * `name` - The new name that should be set.
    pub fn set_name(&self, name: &str) {
        self.set("name", name);
    }

    /// Get the short_name of the buffer.
    pub fn short_name(&self) -> Cow<str> {
        self.get_string("short_name").unwrap()
    }

    /// Set the short_name of the buffer.
    ///
    /// # Arguments
    ///
    /// * `name` - The new short name that should be set.
    pub fn set_short_name(&self, name: &str) {
        self.set("short_name", name);
    }

    /// Get the plugin name of the plugin that owns this buffer.
    pub fn plugin_name(&self) -> Cow<str> {
        self.get_string("plugin").unwrap()
    }

    /// Hide time for all lines in the buffer.
    pub fn disable_time_for_each_line(&self) {
        self.set("time_for_each_line", "0");
    }

    /// Disable the nicklist for this buffer.
    pub fn disable_nicklist(&self) {
        self.set("nicklist", "0")
    }

    /// Enable the nicklist for this buffer.
    pub fn enable_nicklist(&self) {
        self.set("nicklist", "1")
    }

    /// Get the title of the buffer
    pub fn title(&self) {
        self.get_string("title");
    }

    /// Set the title of the buffer.
    ///
    /// # Arguments
    ///
    /// * `title` - The new title that will be set.
    pub fn set_title(&self, title: &str) {
        self.set("title", title);
    }

    /// Disable logging for this buffer.
    pub fn disable_log(&self) {
        self.set("localvar_set_no_log", "1");
    }

    /// Clear buffer contents
    pub fn clear(&self) {
        let weechat = self.weechat();

        let buffer_clear = weechat.get().buffer_clear.unwrap();
        unsafe { buffer_clear(self.ptr()) }
    }

    /// Close the buffer.
    ///
    /// Note that this will only queue up the buffer to be closed. The close
    /// callback will first be run, only then will the buffer be closed.
    ///
    /// Multiple calls to this method will result in a nop.
    pub fn close(&self) {
        if !self.is_closing() {
            let weechat = self.weechat();

            let buffer_close = weechat.get().buffer_close.unwrap();
            unsafe { buffer_close(self.ptr()) };
            self.mark_as_closing();
        }
    }

    /// Get the contents of the input
    pub fn input(&self) -> Cow<str> {
        self.get_string("input").unwrap()
    }

    /// Set the content of the buffer input.
    pub fn set_input(&self, input: &str) {
        self.set("input", input)
    }

    /// Get the position of the cursor in the buffer input.
    pub fn input_position(&self) -> i32 {
        self.get_integer("input_pos")
    }

    /// Set the position of the input buffer.
    ///
    /// # Arguments
    ///
    /// * `position` - The new position of the input.
    pub fn set_input_position(&self, position: i32) {
        self.set("input_pos", &position.to_string())
    }

    /// Get the number of the buffer.
    pub fn number(&self) -> i32 {
        self.get_integer("number")
    }

    /// Switch to the buffer
    pub fn switch_to(&self) {
        self.set("display", "1");
    }

    /// Run the given command in the buffer.
    ///
    /// # Arguments
    ///
    /// * `command` - The command that should run.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use weechat::Weechat;
    /// # use weechat::buffer::BufferBuilder;
    /// # let buffer_handle = BufferBuilder::new("test")
    /// #    .build()
    /// #    .unwrap();
    /// # let buffer = buffer_handle.upgrade().unwrap();
    ///
    /// // Switch to the core buffer using a command.
    /// buffer.run_command("/buffer core");
    /// ```
    pub fn run_command(&self, command: &str) -> Result<(), ()> {
        let command = LossyCString::new(command);
        let weechat = self.weechat();
        let run_command = weechat.get().command.unwrap();

        let ret = unsafe { run_command(weechat.ptr, self.ptr(), command.as_ptr()) };

        match ret {
            WEECHAT_RC_OK => Ok(()),
            WEECHAT_RC_ERROR => Err(()),
            _ => unreachable!(),
        }
    }

    fn hdata_pointer(&self) -> *mut t_hdata {
        let weechat = self.weechat();

        unsafe { weechat.hdata_get("buffer") }
    }

    fn own_lines(&self) -> *mut c_void {
        let weechat = self.weechat();

        let hdata = self.hdata_pointer();

        unsafe { weechat.hdata_pointer(hdata, self.ptr() as *mut c_void, "own_lines") }
    }

    /// Get the number of lines that the buffer has printed out.
    pub fn num_lines(&self) -> i32 {
        let weechat = self.weechat();
        let own_lines = self.own_lines();

        unsafe {
            let lines = weechat.hdata_get("lines");
            weechat.hdata_integer(lines, own_lines, "lines_count")
        }
    }

    /// Get the lines of the buffer.
    ///
    /// This returns an iterator over all the buffer lines, the iterator can be
    /// traversed forwards (from the first line of the buffer, to the last) as
    /// well as backwards (from the last line of the buffer to the first).
    ///
    /// # Example
    /// ```no_run
    /// # use weechat::Weechat;
    /// # use weechat::buffer::BufferBuilder;
    /// # let buffer_handle = BufferBuilder::new("test")
    /// #    .build()
    /// #    .unwrap();
    /// # let buffer = buffer_handle.upgrade().unwrap();
    ///
    /// let lines = buffer.lines();
    ///
    /// for line in lines {
    ///     Weechat::print(&format!("{:?}", line.tags()));
    /// }
    /// ```
    pub fn lines(&self) -> BufferLines {
        let weechat = self.weechat();

        let own_lines = self.own_lines();

        let (first_line, last_line) = unsafe {
            let lines = weechat.hdata_get("lines");

            (
                weechat.hdata_pointer(lines, own_lines, "first_line"),
                weechat.hdata_pointer(lines, own_lines, "last_line"),
            )
        };

        BufferLines {
            weechat_ptr: self.weechat().ptr,
            first_line,
            last_line,
            buffer: PhantomData,
            done: false,
        }
    }
}