fractal/session/view/content/room_history/message_toolbar/
mod.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
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
use std::collections::HashMap;

use adw::{prelude::*, subclass::prelude::*};
use futures_util::{future, lock::Mutex, pin_mut, StreamExt};
use gettextrs::{gettext, pgettext};
use gtk::{
    gdk, gio,
    glib::{self, clone},
    CompositeTemplate,
};
use matrix_sdk::{
    attachment::{AttachmentConfig, AttachmentInfo, BaseFileInfo, Thumbnail},
    room::edit::EditedContent,
};
use matrix_sdk_ui::timeline::{AttachmentSource, RepliedToInfo, TimelineItemContent};
use ruma::{
    events::{
        room::message::{
            ForwardThread, LocationMessageEventContent, MessageType, RoomMessageEventContent,
        },
        Mentions,
    },
    OwnedRoomId,
};
use tracing::{debug, error, warn};

mod attachment_dialog;
mod completion;
mod composer_parser;
mod composer_state;

pub(crate) use self::composer_state::{ComposerState, RelationInfo};
use self::{
    attachment_dialog::AttachmentDialog, completion::CompletionPopover,
    composer_parser::ComposerParser,
};
use super::message_row::MessageContent;
use crate::{
    components::{CustomEntry, LabelWithWidgets},
    gettext_f,
    prelude::*,
    session::model::{Event, Member, Room},
    spawn, spawn_tokio, toast,
    utils::{
        media::{
            filename_for_mime, image::ImageInfoLoader, load_audio_info, video::load_video_info,
            FileInfo,
        },
        template_callbacks::TemplateCallbacks,
        Location, LocationError, TokioDrop,
    },
};

/// A map of composer state per-session and per-room.
type ComposerStatesMap = HashMap<Option<String>, HashMap<Option<OwnedRoomId>, ComposerState>>;

mod imp {
    use std::{
        cell::{Cell, RefCell},
        marker::PhantomData,
    };

    use glib::subclass::InitializingObject;

    use super::*;
    use crate::Application;

    #[derive(Debug, Default, CompositeTemplate, glib::Properties)]
    #[template(
        resource = "/org/gnome/Fractal/ui/session/view/content/room_history/message_toolbar/mod.ui"
    )]
    #[properties(wrapper_type = super::MessageToolbar)]
    pub struct MessageToolbar {
        #[template_child]
        main_stack: TemplateChild<gtk::Stack>,
        #[template_child]
        message_entry: TemplateChild<sourceview::View>,
        #[template_child]
        send_button: TemplateChild<gtk::Button>,
        #[template_child]
        related_event_header: TemplateChild<LabelWithWidgets>,
        #[template_child]
        related_event_content: TemplateChild<MessageContent>,
        /// The room to send messages in.
        #[property(get, set = Self::set_room, explicit_notify, nullable)]
        room: glib::WeakRef<Room>,
        send_message_permission_handler: RefCell<Option<glib::SignalHandlerId>>,
        /// Whether outgoing messages should be interpreted as markdown.
        #[property(get, set)]
        markdown_enabled: Cell<bool>,
        completion: CompletionPopover,
        /// The current composer state.
        #[property(get = Self::current_composer_state)]
        current_composer_state: PhantomData<ComposerState>,
        composer_state_handler: RefCell<Option<glib::SignalHandlerId>>,
        buffer_handlers: RefCell<Option<(glib::SignalHandlerId, glib::Binding)>>,
        /// The composer states, per-session and per-room.
        ///
        /// The fallback composer state has the `None` key.
        composer_states: RefCell<ComposerStatesMap>,
        /// A guard to avoid sending several messages at once.
        send_guard: Mutex<()>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for MessageToolbar {
        const NAME: &'static str = "MessageToolbar";
        type Type = super::MessageToolbar;
        type ParentType = adw::Bin;

        fn class_init(klass: &mut Self::Class) {
            CustomEntry::ensure_type();

            Self::bind_template(klass);
            Self::bind_template_callbacks(klass);
            TemplateCallbacks::bind_template_callbacks(klass);

            // Menu actions.
            klass.install_action_async(
                "message-toolbar.send-location",
                None,
                |obj, _, _| async move {
                    obj.imp().send_location().await;
                },
            );

            klass.install_property_action("message-toolbar.markdown", "markdown-enabled");
        }

        fn instance_init(obj: &InitializingObject<Self>) {
            obj.init_template();
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for MessageToolbar {
        fn constructed(&self) {
            self.parent_constructed();
            let obj = self.obj();

            // Markdown highlighting.
            let settings = Application::default().settings();
            settings
                .bind("markdown-enabled", &*obj, "markdown-enabled")
                .build();

            // Tab auto-completion.
            self.completion.set_parent(&*self.message_entry);
            obj.bind_property("room", &self.completion, "room")
                .sync_create()
                .build();

            // Location.
            let location = Location::new();
            obj.action_set_enabled("message-toolbar.send-location", location.is_available());
        }

        fn dispose(&self) {
            self.completion.unparent();

            if let Some(room) = self.room.upgrade() {
                if let Some(handler) = self.send_message_permission_handler.take() {
                    room.permissions().disconnect(handler);
                }
            }
        }
    }

    impl WidgetImpl for MessageToolbar {}
    impl BinImpl for MessageToolbar {}

    #[gtk::template_callbacks]
    impl MessageToolbar {
        /// Set the room currently displayed.
        fn set_room(&self, room: Option<&Room>) {
            let old_room = self.room.upgrade();
            if old_room.as_ref() == room {
                return;
            }
            let obj = self.obj();

            if let Some(room) = &old_room {
                if let Some(handler) = self.send_message_permission_handler.take() {
                    room.permissions().disconnect(handler);
                }
            }

            if let Some(room) = room {
                let send_message_permission_handler =
                    room.permissions().connect_can_send_message_notify(clone!(
                        #[weak(rename_to = imp)]
                        self,
                        move |_| {
                            imp.send_message_permission_updated();
                        }
                    ));
                self.send_message_permission_handler
                    .replace(Some(send_message_permission_handler));
            }

            self.room.set(room);

            self.send_message_permission_updated();
            self.message_entry.grab_focus();

            obj.notify_room();
            self.update_current_composer_state(old_room.as_ref());
        }

        /// Whether the user can compose a message.
        ///
        /// It depends on whether our own user has the permission to send a
        /// message in the current room.
        pub(super) fn can_compose_message(&self) -> bool {
            self.room
                .upgrade()
                .is_some_and(|r| r.permissions().can_send_message())
        }

        /// Handle an update of the permission to send a message in the current
        /// room.
        fn send_message_permission_updated(&self) {
            let page = if self.can_compose_message() {
                "enabled"
            } else {
                "disabled"
            };
            self.main_stack.set_visible_child_name(page);
        }

        /// Get the current composer state.
        fn current_composer_state(&self) -> ComposerState {
            let room = self.room.upgrade();
            self.composer_state(room.as_ref())
        }

        /// Get the composer state for the given room.
        ///
        /// If the composer state doesn't exist, it is created.
        fn composer_state(&self, room: Option<&Room>) -> ComposerState {
            self.composer_states
                .borrow_mut()
                .entry(
                    room.and_then(Room::session)
                        .map(|s| s.session_id().to_owned()),
                )
                .or_default()
                .entry(room.map(|r| r.room_id().to_owned()))
                .or_insert_with(|| ComposerState::new(room))
                .clone()
        }

        /// Update the current composer state.
        fn update_current_composer_state(&self, old_room: Option<&Room>) {
            let old_composer_state = self.composer_state(old_room);
            old_composer_state.attach_to_view(None);

            if let Some(handler) = self.composer_state_handler.take() {
                old_composer_state.disconnect(handler);
            }
            if let Some((handler, binding)) = self.buffer_handlers.take() {
                let prev_buffer = self.message_entry.buffer();
                prev_buffer.disconnect(handler);

                binding.unbind();
            }

            let composer_state = self.current_composer_state();
            let buffer = composer_state.buffer();
            let obj = self.obj();

            composer_state.attach_to_view(Some(&self.message_entry));

            // Actions on changes in message entry.
            let text_notify_handler = buffer.connect_text_notify(clone!(
                #[weak(rename_to = imp)]
                self,
                move |buffer| {
                    let (start_iter, end_iter) = buffer.bounds();
                    let is_empty = start_iter == end_iter;
                    imp.send_button.set_sensitive(!is_empty);
                    imp.send_typing_notification(!is_empty);
                }
            ));

            let (start_iter, end_iter) = buffer.bounds();
            let is_empty = start_iter == end_iter;
            self.send_button.set_sensitive(!is_empty);

            // Markdown highlighting.
            let markdown_binding = obj
                .bind_property("markdown-enabled", &buffer, "highlight-syntax")
                .sync_create()
                .build();

            self.buffer_handlers
                .replace(Some((text_notify_handler, markdown_binding)));

            // Related event.
            let composer_state_handler = composer_state.connect_related_to_changed(clone!(
                #[weak(rename_to = imp)]
                self,
                move |_| {
                    imp.update_related_event();
                }
            ));
            self.composer_state_handler
                .replace(Some(composer_state_handler));
            self.update_related_event();

            obj.notify_current_composer_state();
        }

        /// Update the displayed related event for the current state.
        fn update_related_event(&self) {
            let composer_state = self.current_composer_state();

            match composer_state.related_to() {
                Some(RelationInfo::Reply(info)) => {
                    self.update_for_reply(&info);
                }
                Some(RelationInfo::Edit(_)) => {
                    self.update_for_edit();
                }
                None => {}
            }
        }

        /// Update the displayed related event for the given reply.
        fn update_for_reply(&self, info: &RepliedToInfo) {
            let Some(room) = self.room.upgrade() else {
                return;
            };

            let sender = room
                .get_or_create_members()
                .get_or_create(info.sender().to_owned());

            let label = gettext_f(
                // Translators: Do NOT translate the content between '{' and '}',
                // this is a variable name. In this string, 'Reply' is a noun.
                "Reply to {user}",
                &[("user", LabelWithWidgets::PLACEHOLDER)],
            );
            let pill = sender.to_pill();

            self.related_event_header
                .set_label_and_widgets(label, vec![pill]);

            self.related_event_content
                .update_for_related_event(info, &sender);
            self.related_event_content.set_visible(true);
        }

        /// Update the displayed related event for the given edit.
        fn update_for_edit(&self) {
            // Translators: In this string, 'Edit' is a noun.
            let label = pgettext("room-history", "Edit");
            self.related_event_header
                .set_label_and_widgets::<gtk::Widget>(label, vec![]);

            self.related_event_content.set_visible(false);
        }

        /// Clear the related event.
        #[template_callback]
        fn clear_related_event(&self) {
            self.current_composer_state().set_related_to(None);
        }

        /// Add a mention of the given member to the message composer.
        pub(super) fn mention_member(&self, member: &Member) {
            if !self.can_compose_message() {
                return;
            }

            let buffer = self.message_entry.buffer();
            let mut insert = buffer.iter_at_mark(&buffer.get_insert());

            let pill = member.to_pill();
            self.current_composer_state().add_widget(pill, &mut insert);

            self.message_entry.grab_focus();
        }

        /// Set the event to reply to.
        pub(super) fn set_reply_to(&self, event: &Event) {
            if !self.can_compose_message() {
                return;
            }

            let Ok(info) = event.item().replied_to_info() else {
                warn!("Unsupported event type for reply");
                return;
            };

            self.current_composer_state()
                .set_related_to(Some(RelationInfo::Reply(info)));

            self.message_entry.grab_focus();
        }

        /// Set the event to edit.
        pub(super) fn set_edit(&self, event: &Event) {
            if !self.can_compose_message() {
                return;
            }

            let item = event.item();

            let Some(event_id) = item.event_id() else {
                warn!("Cannot send edit for event that is not sent yet");
                return;
            };
            let TimelineItemContent::Message(message) = item.content() else {
                warn!("Unsupported event type for edit");
                return;
            };

            self.current_composer_state()
                .set_edit_source(event_id.to_owned(), message);

            self.message_entry.grab_focus();
        }

        /// Handle when a key was pressed in the message entry.
        #[template_callback]
        fn key_pressed(
            &self,
            key: gdk::Key,
            _keycode: u32,
            modifier: gdk::ModifierType,
        ) -> glib::Propagation {
            if modifier.is_empty() && (key == gdk::Key::Return || key == gdk::Key::KP_Enter) {
                spawn!(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    async move {
                        imp.send_text_message().await;
                    }
                ));
                glib::Propagation::Stop
            } else if modifier.is_empty()
                && key == gdk::Key::Escape
                && self.current_composer_state().has_relation()
            {
                self.clear_related_event();
                glib::Propagation::Stop
            } else {
                glib::Propagation::Proceed
            }
        }

        /// Send the text message that is currently in the message entry.
        #[template_callback]
        async fn send_text_message(&self) {
            let Some(_send_guard) = self.send_guard.try_lock() else {
                return;
            };
            if !self.can_compose_message() {
                return;
            }
            let Some(room) = self.room.upgrade() else {
                return;
            };

            let composer_state = self.current_composer_state();
            let markdown_enabled = self.markdown_enabled.get();

            let Some(content) = ComposerParser::new(&composer_state, None)
                .into_message_event_content(markdown_enabled)
                .await
            else {
                return;
            };

            let matrix_timeline = room.timeline().matrix_timeline();

            // Send event depending on relation.
            match composer_state.related_to() {
                Some(RelationInfo::Reply(replied_to_info)) => {
                    let handle = spawn_tokio!(async move {
                        matrix_timeline
                            .send_reply(content, replied_to_info, ForwardThread::Yes)
                            .await
                    });
                    if let Err(error) = handle.await.unwrap() {
                        error!("Could not send reply: {error}");
                        let obj = self.obj();
                        toast!(obj, gettext("Could not send reply"));
                    }
                }
                Some(RelationInfo::Edit(event_id)) => {
                    let matrix_room = room.matrix_room().clone();
                    let handle = spawn_tokio!(async move {
                        let full_content = matrix_room
                            .make_edit_event(&event_id, EditedContent::RoomMessage(content))
                            .await
                            .map_err(matrix_sdk_ui::timeline::EditError::from)?;
                        let send_queue = matrix_room.send_queue();
                        send_queue.send(full_content).await?;
                        Ok::<(), matrix_sdk_ui::timeline::Error>(())
                    });
                    if let Err(error) = handle.await.unwrap() {
                        error!("Could not send edit: {error}");
                        let obj = self.obj();
                        toast!(obj, gettext("Could not send edit"));
                    }
                }
                _ => {
                    let handle = spawn_tokio!(async move {
                        matrix_timeline
                            .send(content.with_relation(None).into())
                            .await
                    });
                    if let Err(error) = handle.await.unwrap() {
                        error!("Could not send message: {error}");
                        let obj = self.obj();
                        toast!(obj, gettext("Could not send message"));
                    }
                }
            }

            // Clear the composer state.
            composer_state.clear();
        }

        /// Open the emoji chooser in the message entry.
        #[template_callback]
        fn open_emoji(&self) {
            if !self.can_compose_message() {
                return;
            }
            self.message_entry.emit_insert_emoji();
        }

        /// Send the current location of the user.
        ///
        /// Shows a preview of the location first and asks the user to confirm
        /// the action.
        async fn send_location(&self) {
            let Some(_send_guard) = self.send_guard.try_lock() else {
                return;
            };
            if !self.can_compose_message() {
                return;
            }
            let Some(room) = self.room.upgrade() else {
                return;
            };

            let location = Location::new();
            if !location.is_available() {
                return;
            }

            // Listen whether the user cancels before the location API is initialized.
            if let Err(error) = location.init().await {
                self.location_error_toast(error);
                return;
            }

            // Show the dialog as loading.
            let obj = self.obj();
            let dialog = AttachmentDialog::new(&gettext("Your Location"));
            let response_fut = dialog.response_future(&*obj);
            pin_mut!(response_fut);

            // Listen whether the user cancels before the location stream is ready.
            let location_stream_fut = location.updates_stream();
            pin_mut!(location_stream_fut);
            let (mut location_stream, response_fut) =
                match future::select(location_stream_fut, response_fut).await {
                    future::Either::Left((stream_res, response_fut)) => match stream_res {
                        Ok(stream) => (stream, response_fut),
                        Err(error) => {
                            dialog.close();
                            self.location_error_toast(error);
                            return;
                        }
                    },
                    future::Either::Right(_) => {
                        // The only possible response at this stage should be cancel.
                        return;
                    }
                };

            // Listen to location changes while waiting for the user's response.
            let mut response_fut_wrapper = Some(response_fut);
            let mut geo_uri_wrapper = None;
            loop {
                let response_fut = response_fut_wrapper.take().unwrap();

                match future::select(location_stream.next(), response_fut).await {
                    future::Either::Left((update, response_fut)) => {
                        if let Some(uri) = update {
                            dialog.set_location(&uri);
                            geo_uri_wrapper.replace(uri);
                        }
                        response_fut_wrapper.replace(response_fut);
                    }
                    future::Either::Right((response, _)) => {
                        // The linux location stream requires a tokio executor when dropped.
                        let stream_drop = TokioDrop::new();
                        let _ = stream_drop.set(location_stream);

                        if response == gtk::ResponseType::Ok {
                            break;
                        }

                        return;
                    }
                };
            }

            let Some(geo_uri) = geo_uri_wrapper else {
                return;
            };

            let geo_uri_string = geo_uri.to_string();
            let timestamp =
                glib::DateTime::now_local().expect("Should be able to get the local timestamp");
            let location_body = gettext_f(
                // Translators: Do NOT translate the content between '{' and '}', this is a
                // variable name.
                "User Location {geo_uri} at {iso8601_datetime}",
                &[
                    ("geo_uri", &geo_uri_string),
                    (
                        "iso8601_datetime",
                        timestamp.format_iso8601().unwrap().as_str(),
                    ),
                ],
            );

            let content = RoomMessageEventContent::new(MessageType::Location(
                LocationMessageEventContent::new(location_body, geo_uri_string),
            ))
            // To avoid triggering legacy pushrules, we must always include the mentions,
            // even if they are empty.
            .add_mentions(Mentions::default());

            let matrix_timeline = room.timeline().matrix_timeline();
            let handle = spawn_tokio!(async move { matrix_timeline.send(content.into()).await });

            if let Err(error) = handle.await.unwrap() {
                error!("Could not send location: {error}");
                let obj = self.obj();
                toast!(obj, gettext("Could not send location"));
            }
        }

        /// Show a toast for the given location error;
        fn location_error_toast(&self, error: LocationError) {
            let msg = match error {
                LocationError::Cancelled => gettext("The location request has been cancelled"),
                LocationError::Disabled => gettext("The location services are disabled"),
                LocationError::Other => gettext("Could not retrieve current location"),
            };

            let obj = self.obj();
            toast!(obj, msg);
        }

        /// Send the attachment with the given data.
        async fn send_attachment(
            &self,
            source: AttachmentSource,
            mime: mime::Mime,
            info: AttachmentInfo,
            thumbnail: Option<Thumbnail>,
        ) {
            let Some(room) = self.room.upgrade() else {
                return;
            };

            let config = AttachmentConfig::new().thumbnail(thumbnail).info(info);

            let matrix_timeline = room.timeline().matrix_timeline();

            let handle = spawn_tokio!(async move {
                matrix_timeline
                    .send_attachment(source, mime, config)
                    .use_send_queue()
                    .await
            });

            if let Err(error) = handle.await.unwrap() {
                error!("Could not send file: {error}");
                let obj = self.obj();
                toast!(obj, gettext("Could not send file"));
            }
        }

        /// Send the given texture as an image.
        ///
        /// Shows a preview of the image first and asks the user to confirm the
        /// action.
        async fn send_image(&self, image: gdk::Texture) {
            let Some(_send_guard) = self.send_guard.try_lock() else {
                return;
            };
            if !self.can_compose_message() {
                return;
            }

            let obj = self.obj();
            let filename = filename_for_mime(Some(mime::IMAGE_PNG.as_ref()), None);
            let dialog = AttachmentDialog::new(&filename);
            dialog.set_image(&image);

            if dialog.response_future(&*obj).await != gtk::ResponseType::Ok {
                return;
            }

            let bytes = image.save_to_png_bytes();
            let filesize = bytes.len().try_into().ok();

            let (mut base_info, thumbnail) = ImageInfoLoader::from(image)
                .load_info_and_thumbnail(filesize, &*obj)
                .await;
            base_info.size = filesize.map(Into::into);

            let info = AttachmentInfo::Image(base_info);
            let source = AttachmentSource::Data {
                bytes: bytes.to_vec(),
                filename,
            };
            self.send_attachment(source, mime::IMAGE_PNG, info, thumbnail)
                .await;
        }

        /// Select a file to send.
        #[template_callback]
        async fn select_file(&self) {
            let Some(_send_guard) = self.send_guard.try_lock() else {
                return;
            };
            if !self.can_compose_message() {
                return;
            }

            let obj = self.obj();
            let dialog = gtk::FileDialog::builder()
                .title(gettext("Select File"))
                .modal(true)
                .accept_label(gettext("Select"))
                .build();

            match dialog
                .open_future(obj.root().and_downcast_ref::<gtk::Window>())
                .await
            {
                Ok(file) => {
                    self.send_file_inner(file).await;
                }
                Err(error) => {
                    if error.matches(gtk::DialogError::Dismissed) {
                        debug!("File dialog dismissed by user");
                    } else {
                        error!("Could not open file: {error:?}");
                        toast!(obj, gettext("Could not open file"));
                    }
                }
            };
        }

        /// Send the given file.
        ///
        /// Shows a preview of the file first, if possible, and asks the user to
        /// confirm the action.
        pub(super) async fn send_file(&self, file: gio::File) {
            let Some(_send_guard) = self.send_guard.try_lock() else {
                return;
            };
            if !self.can_compose_message() {
                return;
            }

            self.send_file_inner(file).await;
        }

        async fn send_file_inner(&self, file: gio::File) {
            let obj = self.obj();

            let Some(path) = file.path() else {
                warn!("Could not read file: file does not have a path");
                toast!(obj, gettext("Error reading file"));
                return;
            };

            let file_info = match FileInfo::try_from_file(&file).await {
                Ok(file_info) => file_info,
                Err(error) => {
                    warn!("Could not read file info: {error}");
                    toast!(obj, gettext("Error reading file"));
                    return;
                }
            };

            let dialog = AttachmentDialog::new(&file_info.filename);
            dialog.set_file(file.clone());

            if dialog.response_future(&*obj).await != gtk::ResponseType::Ok {
                return;
            }

            let size = file_info.size.map(Into::into);
            let (info, thumbnail) = match file_info.mime.type_() {
                mime::IMAGE => {
                    let (mut info, thumbnail) = ImageInfoLoader::from(file)
                        .load_info_and_thumbnail(file_info.size, &*obj)
                        .await;
                    info.size = size;

                    (AttachmentInfo::Image(info), thumbnail)
                }
                mime::VIDEO => {
                    let (mut info, thumbnail) = load_video_info(&file, &*obj).await;
                    info.size = size;
                    (AttachmentInfo::Video(info), thumbnail)
                }
                mime::AUDIO => {
                    let mut info = load_audio_info(&file).await;
                    info.size = size;
                    (AttachmentInfo::Audio(info), None)
                }
                _ => (AttachmentInfo::File(BaseFileInfo { size }), None),
            };

            self.send_attachment(path.into(), file_info.mime, info, thumbnail)
                .await;
        }

        /// Read the file data from the clipboard and send it.
        pub(super) async fn read_clipboard_file(&self) {
            let obj = self.obj();
            let clipboard = obj.clipboard();
            let formats = clipboard.formats();

            if formats.contains_type(gdk::Texture::static_type()) {
                // There is an image in the clipboard.
                match clipboard
                    .read_value_future(gdk::Texture::static_type(), glib::Priority::DEFAULT)
                    .await
                {
                    Ok(value) => match value.get::<gdk::Texture>() {
                        Ok(texture) => {
                            self.send_image(texture).await;
                            return;
                        }
                        Err(error) => warn!("Could not get GdkTexture from value: {error}"),
                    },
                    Err(error) => warn!("Could not get GdkTexture from the clipboard: {error}"),
                }

                toast!(obj, gettext("Error getting image from clipboard"));
            } else if formats.contains_type(gio::File::static_type()) {
                // There is a file in the clipboard.
                match clipboard
                    .read_value_future(gio::File::static_type(), glib::Priority::DEFAULT)
                    .await
                {
                    Ok(value) => match value.get::<gio::File>() {
                        Ok(file) => {
                            self.send_file(file).await;
                            return;
                        }
                        Err(error) => warn!("Could not get file from value: {error}"),
                    },
                    Err(error) => warn!("Could not get file from the clipboard: {error}"),
                }

                toast!(obj, gettext("Error getting file from clipboard"));
            }
        }

        /// Handle a click on the related event.
        ///
        /// Scrolls to the corresponding event.
        #[template_callback]
        fn handle_related_event_click(&self) {
            if let Some(related_to) = self.current_composer_state().related_to() {
                self.obj()
                    .activate_action(
                        "room-history.scroll-to-event",
                        Some(&related_to.identifier().to_variant()),
                    )
                    .expect("action exists");
            }
        }

        /// Paste the content of the clipboard into the message entry.
        #[template_callback]
        fn paste_from_clipboard(&self) {
            if !self.can_compose_message() {
                return;
            }

            let formats = self.obj().clipboard().formats();

            // We only handle files and supported images.
            if formats.contains_type(gio::File::static_type())
                || formats.contains_type(gdk::Texture::static_type())
            {
                self.message_entry
                    .stop_signal_emission_by_name("paste-clipboard");
                spawn!(clone!(
                    #[weak(rename_to = imp)]
                    self,
                    async move {
                        imp.read_clipboard_file().await;
                    }
                ));
            }
        }

        /// Copy the content of the message entry to the clipboard.
        #[template_callback]
        fn copy_to_clipboard(&self) {
            self.message_entry
                .stop_signal_emission_by_name("copy-clipboard");
            self.copy_buffer_selection_to_clipboard();
        }

        /// Cut the content of the message entry to the clipboard.
        #[template_callback]
        fn cut_to_clipboard(&self) {
            self.message_entry
                .stop_signal_emission_by_name("cut-clipboard");
            self.copy_buffer_selection_to_clipboard();
            self.message_entry.buffer().delete_selection(true, true);
        }

        // Copy the selection in the message entry to the clipboard while replacing
        // mentions.
        fn copy_buffer_selection_to_clipboard(&self) {
            let buffer = self.message_entry.buffer();
            let Some((start, end)) = buffer.selection_bounds() else {
                return;
            };

            let composer_state = self.current_composer_state();
            let body = ComposerParser::new(&composer_state, Some((start, end))).into_plain_text();

            self.obj().clipboard().set_text(&body);
        }

        /// Send a typing notification for the given typing state.
        fn send_typing_notification(&self, typing: bool) {
            let Some(room) = self.room.upgrade() else {
                return;
            };
            let Some(session) = room.session() else {
                return;
            };

            if !session.settings().typing_enabled() {
                return;
            }

            room.send_typing_notification(typing);
        }
    }
}

glib::wrapper! {
    /// A toolbar with different actions to send messages.
    pub struct MessageToolbar(ObjectSubclass<imp::MessageToolbar>)
        @extends gtk::Widget, adw::Bin, @implements gtk::Accessible;
}

impl MessageToolbar {
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Add a mention of the given member to the message composer.
    pub(crate) fn mention_member(&self, member: &Member) {
        self.imp().mention_member(member);
    }

    /// Set the event to reply to.
    pub(crate) fn set_reply_to(&self, event: &Event) {
        self.imp().set_reply_to(event);
    }

    /// Set the event to edit.
    pub(crate) fn set_edit(&self, event: &Event) {
        self.imp().set_edit(event);
    }

    /// Send the given file.
    ///
    /// Shows a preview of the file first, if possible, and asks the user to
    /// confirm the action.
    pub(crate) async fn send_file(&self, file: gio::File) {
        self.imp().send_file(file).await;
    }

    /// Handle a paste action.
    pub(crate) fn handle_paste_action(&self) {
        let imp = self.imp();

        if !imp.can_compose_message() {
            return;
        }

        spawn!(clone!(
            #[weak]
            imp,
            async move {
                imp.read_clipboard_file().await;
            }
        ));
    }
}