hgame 0.26.4

CG production management structs, e.g. of assets, personnels, progress, etc.
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
mod builder;
mod expand;
mod message_box;

use super::*;
use crate::{ticket_tally::TicketTally, user::action::Pass_u8};
pub use builder::*;
use expand::MsgExpand;
pub use message_box::{QmsBox, QueryMsgFilter};
use mkentity::Entity;

use chrono::prelude::{DateTime, Local, Utc};
use std::collections::HashSet;

#[cfg(feature = "gui")]
use crossbeam_channel::Sender;

const MSG_ACTION_CHANNEL_SEND_ERR: &str = "Failed to send MsgAction via channel";
const NO_TOPICAL_ERR: &str = "Message has no topical asset";
pub const EXCERPT_TRUNCATE_LENGTH: usize = 30;

#[derive(Debug, Clone)]
pub enum MsgAction {
    SendNew(QueryMsg),

    /// Reply only to the sender of the [`QueryMsg`].
    Reply(QueryMsg),

    /// Reply to all the recipients of the [`QueryMsg`].
    ReplyAll(QueryMsg),

    UpdateReadState(QueryMsg, ReadState),

    BatchUpdateReadState( Vec<QueryMsg>, ReadState),

    PilotAndMarkRead(QueryMsg),

    Edit(QueryMsg),

    Unsend(QueryMsg),
}

// ----------------------------------------------------------------------------
#[async_trait]
pub trait QmsChat: DynClone + fmt::Debug + Send + Sync {
    async fn message_from_bson_id(
        &mut self,
        project: &Project,
        id: &ObjectId,
        viewer: Option<&Staff>,
    ) -> Result<QueryMsg, DatabaseError>;

    async fn msg_synopsis_from_bson_id(
        &mut self,
        project: &Project,
        id: &ObjectId,
    ) -> Result<MsgExcerpt, DatabaseError>;

    /// Lists all [`QueryMsg`] that match the given filter -- usually comprising
    /// both system-sent and handwritten messages.
    async fn mixed_messages(
        &mut self,
        project: &Project,
        topics: &BTreeSet<MsgTopic>,
        qms_filter: &QueryMsgFilter,
        viewer: Option<&Staff>,
    ) -> Result<QmsBox, DatabaseError>;

    /// Lists all uninstantiated [`QueryMsg`] that match the given filter -- usually comprising
    /// both system-sent and handwritten messages. Not filtering for `topical_assets`.
    async fn uninstantiated_any_asset(
        &mut self,
        project: &Project,
        topics: &BTreeSet<MsgTopic>,
        qms_filter: &QueryMsgFilter,
        viewer: &Staff,
    ) -> Result<Vec<QueryMsg>, DatabaseError>;

    /// Lists all "handwritten" [`QueryMsg`] that match the given filter.
    async fn handwritten_messages(
        &mut self,
        project: &Project,
        qms_filter: QueryMsgFilter,
        viewer: Option<&Staff>,
    ) -> Result<QmsBox, DatabaseError>;

    /// Lists all system-sent [`QueryMsg`] that match the given filter.
    async fn system_messages(
        &mut self,
        project: &Project,
        topics: BTreeSet<MsgTopic>,
        qms_filter: QueryMsgFilter,
        viewer: Option<&Staff>,
    ) -> Result<QmsBox, DatabaseError>;

    /// Lists all [`QueryMsg`] sent by a certain person.
    async fn sent_messages(
        &mut self,
        project: &Project,
        topics: BTreeSet<MsgTopic>,
        qms_filter: QueryMsgFilter,
        viewer: Option<&Staff>,
    ) -> Result<QmsBox, DatabaseError>;

    /// Sends the given `QueryMsg` for the [`Project`].
    async fn send(&self, project: &Project, msg: QueryMsg) -> Result<(), ModificationError>;

    /// Updates the given `QueryMsg` for the [`Project`].
    async fn edit_message(
        &self,
        project: &Project,
        existing: Option<&QueryMsg>,
        updated: QueryMsg,
    ) -> Result<(), ModificationError>;

    /// Updates the [`ReadState`] for given `QueryMsg` for the [`Project`].
    async fn mark_read(
        &self,
        project: &Project,
        msg: &QueryMsg,
        target: &ReadState,
        viewer: &Staff,
    ) -> Result<(), ModificationError>;

    /// Updates the [`InstantiationState`] for given `QueryMsg` for the [`Project`].
    async fn mark_instantiated(
        &self,
        project: &Project,
        msg: &QueryMsg,
        target: &InstantiationState,
        viewer: &Staff,
    ) -> Result<(), ModificationError>;

    /// Updates the [`ReadState`] for given &[`QueryMsg`] for the [`Project`].
    async fn batch_mark_read(
        &self,
        project: &Project,
        messages: &[QueryMsg],
        target: &ReadState,
        viewer: &Staff,
    ) -> Result<(), ModificationError>;

    /// Deletes the given `QueryMsg` for the [`Project`].
    async fn unsend(&self, project: &Project, msg: &QueryMsg) -> Result<(), ModificationError>;

    fn clear_cache(&mut self) {}
}

dyn_clone::clone_trait_object!(QmsChat);

// ----------------------------------------------------------------------------
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
/// A query message as way of internal communication about events among
/// production collaborators.
/// LEGACY DESIGN: DO NOT change field names or `serde(rename)` values.
pub struct QueryMsg {
    #[serde(skip)]
    /// All the rich types reside here and are mutated after the documents are fetched from DB.
    pub ext: MsgExpand,

    #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
    id: Option<ObjectId>,

    /// Based on this `topic` value, `QueryMsg` can be grouped into boxes of
    /// "manually composed" ones and "system-sent" ones. The `topic` values
    /// are also used by users to easily unsubscribe/opt-out from certain message types.
    #[serde(rename = "soup_format")]
    topic: MsgTopic,

    /// Put behind an [`Option`] to reduce allocation.
    project: Option<String>,

    #[serde(rename = "sender")]
    /// Original `sender` field.
    pub sender_name: String,

    subject: String,

    content: String,

    #[serde(rename = "topical_assets")]
    /// Original `topical_assets` field. The `ObjectId`s refer to the [`ProductionAsset`]s.
    pub topical_asset_bson_ids: Vec<ObjectId>,

    #[serde(rename = "as_reply_to")]
    /// Original `as_reply_to` field. The `ObjectId`s refer to the other `QueryMsg`s.
    /// Put behind an [`Option`] to reduce allocation since not all messages utilize this.
    pub as_reply_to_bson_ids: Option<Vec<ObjectId>>,

    #[serde(rename = "recipients")]
    /// Original `recipients` field.
    pub recipient_names: Vec<String>,

    /// Put behind an [`Option`] to reduce allocation since not all messages utilize this.
    hyperlinks: Option<Vec<HtmlLink>>,

    #[serde(rename = "seen_by")]
    /// Original `seen_by` field.
    pub seen_by_names: Vec<String>,

    pub instantiated_for: Vec<String>,

    #[serde(
        rename = "datetime",
        with = "bson::serde_helpers::chrono_datetime_as_bson_datetime"
    )]
    pub created_at: DateTime<Utc>,

    #[cfg(feature = "ticket")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    // Only certain types of message will include this on sending. Extended in February 2023.
    subticket_number: Option<u8>,
    // is_important: bool,
    // is_urgent: bool,
    //
    // is_plain_text: bool, // NOTE: enabling this will result in many deser fails
}

impl BsonId for QueryMsg {
    fn bson_id_as_ref(&self) -> Option<&ObjectId> {
        self.id.as_ref()
    }

    fn bson_id(&self) -> AnyResult<&ObjectId> {
        self.id
            .as_ref()
            .context("QueryMsg without BSON ObjectId")
    }
}

impl QueryMsg {
    pub fn empty() -> Self {
        Self {
            ext: MsgExpand::empty(),
            created_at: Utc::now(),
            ..Default::default()
        }
    }

    pub fn with_topic(mut self, topic: MsgTopic) -> Self {
        self.topic = topic;
        self
    }

    pub fn with_topical_asset_id(mut self, asset: Option<&AssetExcerpt>) -> AnyResult<Self> {
        let id = asset
            .context(NO_TOPICAL_ERR)?
            .id
            .context("Message without BSON ObjectId")?;
        if !self.topical_asset_bson_ids.contains(&id) {
            self.topical_asset_bson_ids.push(id.clone());
        };
        Ok(self)
    }

    pub fn with_topical_asset(mut self, asset: Option<AssetExcerpt>) -> Self {
        self.ext.topical_asset_mut(asset);
        self
    }

    #[cfg(feature = "ticket")]
    pub fn subticket_number(mut self, subticket_number: Option<u8>) -> Self {
        self.subticket_number = subticket_number;
        self
    }

    /// Used to reset the "manually composed" message.
    pub fn empty_draft() -> Self {
        Self::empty().with_mode(MediaMode::WriteCompose)
    }

    /// Use this as starter for "system" -- automatically sent -- messages.
    pub fn sent_by_current_user(user: Staff) -> Self {
        let mut msg = Self::empty();

        // remember to deal primarily with rich types
        msg.ext.sender = user;
        msg
    }

    pub fn content(&self) -> &String {
        &self.content
    }

    // /// NOTE: this checks by name in `String`.
    // fn instantiated_for(&self, viewer: Option<&Staff>) -> bool {
    //     if let Some(viewer) = viewer {
    //         self.instantiated_for.contains(viewer.name_unwrap())
    //     } else {
    //         false
    //     }
    // }

    pub fn topical(&self) -> AnyResult<&AssetExcerpt> {
        Ok(self.ext.topical_asset().context(NO_TOPICAL_ERR)?)
    }

    pub fn topical_owned(self) -> AnyResult<AssetExcerpt> {
        Ok(self.ext.topical_asset.context(NO_TOPICAL_ERR)?)
    }

    pub fn is_handwritten(&self) -> bool {
        self.topic.is_handwritten()
    }

    /// Consumes the given `QueryMsg` from the `MsgAction::Reply(_)` or `MsgAction::ReplyAll(_)`.
    /// Used in [`MediaMode::WriteCompose`] to keep track of what original message
    /// we're replying to.
    pub fn inherit_from_reply(&mut self, msg: Self) {
        // inherits topical asset
        if let Some(asset) = msg.ext.topical_asset() {
            self.ext.topical_asset_mut(Some(asset.clone()));
        };
        // original message goes to `as_reply_to`
        self.ext.as_reply_to = Some(msg.into());
    }

    #[cfg(feature = "alert")]
    fn alert_subject(&self, project: &Project) -> String {
        if self.topic.is_handwritten() {
            format!("{}/{}:", project, self.ext.sender.name_unwrap())
        } else {
            format!("{}: {}", project, self.subject)
        }
    }

    #[cfg(feature = "alert")]
    pub fn notify(&self, project: &Project) -> AnyResult<()> {
        use mkutil::notify::notify_platform;
        notify_platform(&self.alert_subject(project), &self.content, "Chat")
    }

    #[cfg(feature = "alert")]
    pub fn pop_up(&self, project: &Project) -> bool {
        use mkutil::dialog;
        dialog::info_dialog(&self.alert_subject(project), &self.content)
    }
}

#[cfg(feature = "gui")]
/// All UI-related methods.
impl QueryMsg {
    #[cfg(feature = "ticket")]
    fn subticket_number_ui(&self, ui: &mut egui::Ui) {
        if let Some(number) = &self.subticket_number {
            ui.heading(format!("🎫 Subticket #{}", number));
        };
    }

    fn content_ui(&self, ui: &mut egui::Ui) {
        if !self.content.is_empty() {
            ui.label(&self.content);
        };
    }

    /// For `MsgAction::Reply` no authorization must be checked.
    /// Must be added within a egui menu.
    fn show_reply_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        if ui.button("⮪ Reply").clicked() {
            tx.send(MsgAction::Reply(self.clone()))
                .expect(MSG_ACTION_CHANNEL_SEND_ERR);
            ui.close_menu();
        };
    }

    /// For `MsgAction::ReplyAll` no authorization must be checked.
    /// Must be added within a egui menu.
    fn show_reply_all_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        if ui.button("⮪ Reply All").clicked() {
            tx.send(MsgAction::ReplyAll(self.clone()))
                .expect(MSG_ACTION_CHANNEL_SEND_ERR);
            ui.close_menu();
        };
    }

    // /// For `MsgAction::MarkRead` no authorization must be checked.
    // /// Must be added within a egui menu.
    // fn show_mark_read_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
    //     if !self.ext.seen_by_self && ui.button("👁 Mark As Read").clicked() {
    //         tx.send(MsgAction::UpdateReadState(self.clone(), ReadState::Read))
    //             .expect(MSG_ACTION_CHANNEL_SEND_ERR);
    //         ui.close_menu();
    //     };
    // }

    /// For `MsgAction::MarkUnread` no authorization must be checked.
    /// Must be added within a egui menu.
    fn show_mark_unread_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        if self.ext.seen_by_self && ui.button("― Mark As Unread").clicked() {
            tx.send(MsgAction::UpdateReadState(self.clone(), ReadState::Unread))
                .expect(MSG_ACTION_CHANNEL_SEND_ERR);
            ui.close_menu();
        };
    }

    /// Must be added within a egui menu.
    fn show_edit_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        if !MsgActionPerm::authorized(&self.ext.perm(), &MsgActionPerm::Edit) {
            return;
        }
        if ui.button("✏ Edit").clicked() {
            tx.send(MsgAction::Edit(MsgEditBuilder::new(self.clone()).finish()))
                .expect(MSG_ACTION_CHANNEL_SEND_ERR);
            ui.close_menu();
        };
    }

    /// Must be added within a egui menu.
    fn show_unsend_button(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        if !MsgActionPerm::authorized(&self.ext.perm(), &MsgActionPerm::Unsend) {
            return;
        };
        if ui.button("🗙 Unsend").clicked() {
            tx.send(MsgAction::Unsend(self.clone()))
                .expect(MSG_ACTION_CHANNEL_SEND_ERR);
            ui.close_menu();
        };
    }

    fn show_unsend_menu(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        ui.menu_button("", |ui| {
            self.show_unsend_button(ui, tx);
            self.recipients_preview_ui(ui);
        });
    }

    fn recipients_preview_ui(&self, ui: &mut egui::Ui) {
        ui.label("👥 Recipients")
            .on_hover_text(self.recipient_names.join(", "));
    }

    /// Display of the topical asset in read mode.
    fn topical_asset_ui(&self, ui: &mut egui::Ui) {
        // #[cfg(debug_assertions)]
        // {
        //     ui.horizontal_wrapped(|ui| {
        //         ui.colored_label(
        //             Color32::RED,
        //             format!("Topical Asset(s): {:?}", self.topical_asset_bson_ids),
        //         );
        //     });
        // }

        if let Some(asset) = &self.ext.topical_asset {
            asset.preview_name(ui);
        };
    }

    fn mixed_msg_ui(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        match self.is_handwritten() {
            true => {
                self.handwritten_msg_ui(ui, tx);
            }
            false => {
                self.system_msg_ui(ui, tx);
            }
        };
    }

    fn handwritten_msg_ui(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        self.ext.color_unread_frame(ui);

        ui.group(|ui| {
            ui.vertical(|ui| {
                ui.horizontal(|ui| {
                    let mut title = RichText::new("");
                    if !self.ext.seen_by_self {
                        title = title.color(Color32::YELLOW);
                    };
                    // `MsgAction` menu
                    ui.menu_button(title, |ui| {
                        self.show_reply_button(ui, tx);
                        self.show_reply_all_button(ui, tx);
                        // NOTE: marking read by double-clicking in the `Ui::group`
                        self.show_mark_unread_button(ui, tx);
                        self.show_edit_button(ui, tx);
                        self.show_unsend_button(ui, tx);
                        self.recipients_preview_ui(ui);
                    });
                    self.topical_asset_ui(ui);
                });
                self.ext.reply_hint_ui(ui);
                // sender, no need to show subject
                ui.strong(&self.sender_name);
                // content
                self.content_ui(ui);
                self.ext.seen_by_ui(ui);
                self.ext.created_at_ui(ui);

                self.pilot_if_double_clicked_in_rect(ui, tx);
            })
        });
    }

    fn system_msg_ui(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        self.ext.color_unread_frame(ui);

        ui.group(|ui| {
            ui.vertical(|ui| {
                // no need to show original reply
                ui.horizontal_wrapped(|ui| {
                    let mut title = RichText::new("");
                    if !self.ext.seen_by_self {
                        title = title.color(Color32::LIGHT_GREEN);
                    };
                    // `MsgAction` menu
                    ui.menu_button(title, |ui| {
                        // NOTE: A mistake in the past made all legacy system messages
                        // not containing topical assets, so we're disabling reply
                        // function for system messages.

                        // self.reply_button(ui, tx);
                        // self.reply_all_button(ui, tx);

                        // NOTE: marking read by double-clicking in the `Ui::group`
                        self.show_mark_unread_button(ui, tx);
                        self.show_unsend_button(ui, tx);
                        self.recipients_preview_ui(ui);
                    });

                    // ui.vertical(|ui| {
                        // // LEGACY: We're still showing the topical asset for specific types of
                        // // system messages, in case user chooses to display messages about "Any Assets".
                        // // TODO@retire: remove this after retiring all legacy clients, e.g. Python Hunter
                        // self.topical_asset_ui(ui);

                    // subject
                    ui.label(&self.subject);

                    // });
                });

                // content
                #[cfg(feature = "ticket")]
                self.subticket_number_ui(ui);

                self.content_ui(ui);
                self.ext.seen_by_ui(ui);
                self.ext.created_at_ui(ui);

                self.pilot_if_double_clicked_in_rect(ui, tx);
            });
        });
    }

    fn sent_msg_ui(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        ui.group(|ui| {
            ui.vertical(|ui| {
                // no need to show reply
                self.ext.sent_at_ui(ui);

                // subject if a system message
                if !self.is_handwritten() {
                    ui.horizontal_wrapped(|ui| {
                        // `MsgAction` menu
                        self.show_unsend_menu(ui, tx);
                        ui.label(&self.subject);
                    });

                    #[cfg(feature = "ticket")]
                    self.subticket_number_ui(ui);
                } else {
                    self.show_unsend_menu(ui, tx);
                };

                if self.topic.is_handwritten() {
                    self.topical_asset_ui(ui);
                };

                // content
                self.content_ui(ui);
                self.ext.seen_by_ui(ui);

                self.pilot_if_double_clicked_in_rect(ui, tx);
            });
        });
    }

    fn pilot_if_double_clicked_in_rect(&self, ui: &mut egui::Ui, tx: &Sender<MsgAction>) {
        ui.ctx().input(|i| {
            let pointer_state = &i.pointer;
            if let Some(pos) = pointer_state.hover_pos() {
                if pointer_state.button_double_clicked(egui::PointerButton::Primary)
                    && ui.min_rect().contains(pos)
                {
                    tx.send(MsgAction::PilotAndMarkRead(self.clone())).ok();
                };
            };
        });
    }
}

impl ReadWriteSuggest for QueryMsg {
    fn write_suggest() -> Self {
        Self::empty().with_mode(MediaMode::WriteSuggest)
    }

    fn with_mode(mut self, mode: MediaMode) -> Self {
        self.mode_mut(mode);
        self
    }

    fn mode(&self) -> &MediaMode {
        &self.ext.mode
    }

    /// Its current `MediaMode` setter. Optional.
    fn mode_mut(&mut self, mode: MediaMode) {
        self.ext.mode = mode;
    }

    #[cfg(feature = "gui")]
    /// UI for actual composing process, or for editing existing data. Optional.
    fn write_compose_ui(&mut self, ui: &mut egui::Ui) {
        self.ext.recipients_hint_ui(ui);
        self.ext.reply_hint_mut_ui(ui);
        ui.add(
            egui::TextEdit::multiline(&mut self.content)
                .desired_width(f32::INFINITY)
                .hint_text("Type your message..."),
        );
    }
}

// ----------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "mongo", derive(Serialize, Deserialize))]
/// DO NOT alter field names or `serde(rename)` values.
pub struct MsgExcerpt {
    #[cfg_attr(
        feature = "mongo",
        serde(rename = "_id", skip_serializing_if = "Option::is_none")
    )]
    id: Option<ObjectId>,
    #[cfg_attr(feature = "mongo", serde(rename = "sender"))]
    sender_name: String,
    pub content: String,
}

#[cfg(feature = "gui")]
impl MsgExcerpt {
    /// Hint for a draft we're composing.
    fn reply_draft_ui(&self, ui: &mut egui::Ui) {
        ui.label(format!(
            "⮪ Replying to {}'s: {} [...]",
            self.sender_name, self.content
        ));
    }

    /// Hint for a message we're reading.
    fn reply_read_ui(&self, ui: &mut egui::Ui) {
        ui.label(
            RichText::new(format!(
                "⮪ Reply to {}'s: {} [...]",
                self.sender_name, self.content
            ))
            .weak()
            .small(),
        );
    }
}

impl From<QueryMsg> for MsgExcerpt {
    fn from(mut msg: QueryMsg) -> Self {
        msg.content.truncate(EXCERPT_TRUNCATE_LENGTH);
        Self {
            id: msg.id,
            sender_name: msg.sender_name,
            content: msg.content,
        }
    }
}

// -------------------------------------------------------------------------------
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumIter)]
/// Permission to perform [`MsgAction`]. Should keep the amount of variants correlated from both sides.
/// For fast checking if certain [`MsgAction`]s are allowed, each [`QueryMsg`] will contain a
/// "permission sum" which is calculated by comparing if its sender is the active user.
pub enum MsgActionPerm {
    New = 2_u8.pow(0),
    Reply = 2_u8.pow(1),
    ReplyAll = 2_u8.pow(3),
    MarkRead = 2_u8.pow(4),
    MarkUnread = 2_u8.pow(5),
    Edit = 2_u8.pow(6),
    Unsend = 2_u8.pow(7),
}

impl MsgActionPerm {
    fn default() -> impl Iterator<Item = u8> {
        [
            Self::New,
            Self::Reply,
            Self::ReplyAll,
            Self::MarkRead,
            Self::MarkUnread,
        ]
        .into_iter()
        .map(|a| a as u8)
    }

    pub fn default_sum() -> u8 {
        Self::default().sum()
    }

    fn edit() -> u8 {
        Self::default_sum() + Self::Edit as u8
    }

    pub fn edit_and_unsend() -> u8 {
        Self::default_sum()
            + [Self::Edit, Self::Unsend]
                .into_iter()
                .map(|a| a as u8)
                .sum::<u8>()
    }

    fn all() -> u8 {
        Self::iter().map(|a| a as u8).sum()
    }

    pub fn per_role(viewer: &Staff, sender: &Staff) -> u8 {
        match viewer.role {
            ProductionRole::TechSupport => {
                if viewer == sender {
                    // all permissions
                    Self::all()
                } else {
                    // edit permission of all messages
                    Self::edit()
                }
            }
            // all other roles
            _ => {
                if viewer == sender {
                    // senders can delete their own messages
                    Self::edit_and_unsend()
                } else {
                    Self::default_sum()
                }
            }
        }
    }
}

impl Pass_u8<MsgActionPerm> for MsgActionPerm {
    fn authorized(perm: &u8, action: &MsgActionPerm) -> bool {
        (perm & (*action as u8)) != 0
    }
}

// ----------------------------------------------------------------------------
impl MsgAction {
    // pub fn bson_id(&self) -> Option<&ObjectId> {
    //     match &self {
    //         Self::New(inner)
    //         | Self::Reply(inner)
    //         | Self::ReplyAll(inner)
    //         | Self::MarkRead(inner)
    //         | Self::MarkUnread(inner)
    //         | Self::Edit(inner)
    //         | Self::Unsend(inner) => inner.id.as_ref(),
    //     }
    // }

    /// The current composer -- active user -- is NOT included.
    pub fn recipients(&self) -> HashSet<Staff> {
        match &self {
            // only the original sender
            Self::Reply(inner) => HashSet::from([inner.ext.sender.clone()]),

            // original recipients AND sender
            Self::ReplyAll(inner) => {
                let mut r = inner.ext.recipients_owned();
                r.insert(inner.ext.sender.clone());
                r
            }

            // all the original recipients
            Self::Edit(inner)
            // Although these likely would never be used, we're still returning it for consistency.
            | Self::SendNew(inner)
            | Self::Unsend(inner)
            | Self::UpdateReadState(inner, _) 
            | Self::PilotAndMarkRead(inner)
            => inner.ext.recipients_owned(),

            Self::BatchUpdateReadState(_, _) => {
                unimplemented!()
            }
        }
    }

    // pub fn topical_assets(&self) -> &Vec<ObjectId> {
    //     match &self {
    //         Self::SendNew(inner)
    //         | Self::Reply(inner)
    //         | Self::ReplyAll(inner)
    //         | Self::UpdateReadState(inner, _)
    //         | Self::PilotAndMarkRead(inner)
    //         | Self::Edit(inner)
    //         | Self::Unsend(inner) => &inner.topical_asset_bson_ids,

    //         Self::BatchUpdateReadState(_, _) => {
    //             unimplemented!()
    //         }
    //     }
    // }
}

// ----------------------------------------------------------------------------
#[cfg(feature = "gui")]
/// Shows warning when no topical asset is present
fn no_topical_asset_warning(ui: &mut egui::Ui) {
    ui.colored_label(Color32::LIGHT_RED, "▪ None");
}

// ----------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn msg_action_perm() {
        let perm = MsgActionPerm::default_sum();
        assert_eq!(MsgActionPerm::authorized(&perm, &MsgActionPerm::New), true);
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::Reply),
            true
        );
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::ReplyAll),
            true
        );
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::MarkRead),
            true
        );
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::MarkUnread),
            true
        );
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::Edit),
            false
        );
        assert_eq!(
            MsgActionPerm::authorized(&perm, &MsgActionPerm::Unsend),
            false
        );
    }
}