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
//! Higher level of a project's "review verdicts", by retaining only review items
//! of `Reviewed::No`, and counting the assets belonging to such group.

use super::*;
#[cfg(feature = "gui")]
use crossbeam_channel::Sender;
#[cfg(feature = "gui")]
use mkutil::record_binary_state;

#[derive(Debug, Clone)]
/// The total stats -- sum of all `PanProject members`' stats.
pub struct PanProjectReviewTotal(pub ProjReviewStats);

impl From<&PanProjectReviewStats> for PanProjectReviewTotal {
    fn from(pp_stats: &PanProjectReviewStats) -> Self {
        let total = |typ: Supervision| {
            let series = pp_stats
                .0
                .iter()
                .map(|(_, proj_stats)| match &typ {
                    Supervision::Wip => &proj_stats.wip,
                    Supervision::Feedback => &proj_stats.feedback,
                    Supervision::Approval => &proj_stats.approval,
                    Supervision::Client => &proj_stats.client,
                })
                .collect::<Vec<&SupervisionStats>>();
            SupervisionStats::total(&series, typ)
        };
        Self(ProjReviewStats {
            wip: total(Supervision::Wip),
            feedback: total(Supervision::Feedback),
            approval: total(Supervision::Approval),
            client: total(Supervision::Client),
        })
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// Series of individual [`ProjReviewStats`]. The [`Project`]s -- `PanProject members` -- are expected
/// to be passed to each `SupervisionStats::ui` function, and through which they are passed down to
/// each [`panproject_pilot_button`] to provide piloting (making active) any assets of any `PanProject members`.
pub struct PanProjectReviewStats(pub Vec<(Project, ProjReviewStats)>);

impl Default for PanProjectReviewStats {
    /// Empty content.
    fn default() -> Self {
        Self(vec![])
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// Per project, per review item type, supervision stats, where we only concern ourselves with
/// binary review state of assets: either they are reviewed, or they are not.
/// In UI this serves as a cell in the `NoticeMaster` table.
pub struct SupervisionStats {
    /// Passed to a `BTreeSet<String>` for keeping track of windows' open states.
    id: String,

    typ: Supervision,

    #[cfg(feature = "gui")]
    /// Position to initially show the window.
    window_pos: egui::Pos2,

    /// All assets which have the review item in question of `Reviewed::Yes`.
    reviewed: BinaryStats,

    /// All assets which have the review item in question of `Reviewed::No`.
    not_reviewed: BinaryStats,

    /// Text with pre-calculated reviewed stats.
    stats_line: StatsLine,
}

impl SupervisionStats {
    fn id(project: &Project, typ: &Supervision) -> String {
        format!("{} {}", project, typ.as_ref())
    }

    fn from_project_verdicts(
        project: &Project,
        verdicts: &ProjReviewVerdict,
        typ: Supervision,
    ) -> SupervisionStats {
        let mut reviewed = vec![];
        let mut not_reviewed = vec![];
        verdicts.iter().for_each(|(asset, verdict)| {
            match verdict.review_item(&typ) {
                Reviewed::Yes => {
                    reviewed.push(asset.clone());
                }
                Reviewed::No => {
                    not_reviewed.push(asset.clone());
                }
                _ => {
                    // we're excluding `Reviewed::NoSubmission` and `Reviewed::Inapplicable`
                }
            }
        });
        // sorts alphabetically
        reviewed.sort_by(|a, b| a.partial_cmp(b).unwrap());
        not_reviewed.sort_by(|a, b| a.partial_cmp(b).unwrap());

        let stats_line = StatsLine::from_count(reviewed.len(), not_reviewed.len());

        SupervisionStats {
            id: Self::id(project, &typ),
            typ: typ,
            #[cfg(feature = "gui")]
            window_pos: Default::default(),
            reviewed: BinaryStats::Reviewed(Stats::with_assets(reviewed)),
            not_reviewed: BinaryStats::NotReviewed(Stats::with_assets(not_reviewed)),
            stats_line,
        }
    }

    /// Makes a sum of all elements in the `series` into a "total stats".
    fn total(series: &[&Self], typ: Supervision) -> Self {
        let reviewed: usize = series.iter().map(|s| s.reviewed.inner().count).sum();
        let not_reviewed: usize = series.iter().map(|s| s.not_reviewed.inner().count).sum();
        let stats_line = StatsLine::total_from_count(reviewed, not_reviewed);
        Self {
            // this is actually not used
            id: String::new(),
            typ,
            #[cfg(feature = "gui")]
            // this won't be use as we won't create windows for "Total" cells
            window_pos: Default::default(),
            // inner asset excerpts is blank
            reviewed: BinaryStats::Reviewed(Stats::count_only(reviewed)),
            // inner asset excerpts is blank
            not_reviewed: BinaryStats::NotReviewed(Stats::count_only(not_reviewed)),
            stats_line,
        }
    }

    fn debug_count(&self) -> String {
        format!(
            "Not Reviewed ({}): {}\nReviewed ({}): {}",
            self.not_reviewed.count(),
            AssetExcerpt::debug_name(&self.not_reviewed.inner().assets),
            self.reviewed.count(),
            AssetExcerpt::debug_name(&self.reviewed.inner().assets)
        )
    }
}

#[cfg(feature = "gui")]
impl SupervisionStats {
    /// Serves as a cell in the stats table.
    pub fn show_summary_label(
        &mut self,
        ui: &mut egui::Ui,
        project: &Project,
        trim: &DateRange,
        tx: &Sender<ReviewAction>,
        open_state: &mut BTreeSet<String>,
    ) {
        match &self.stats_line {
            StatsLine::Zero(_) => {
                // no need for details UI
                ui.label(self.stats_line.text());
            }
            _ => {
                let mut show_details = open_state.contains(&self.id);
                let response = ui.toggle_value(&mut show_details, self.stats_line.text());

                // updates the position everytime, in case user toggles other UI panels during usage
                if response.clicked() {
                    if let Some(pos) = response.ctx.input(|i| i.pointer.interact_pos()) {
                        self.window_pos = pos;
                    };
                };

                // `egui_extras::Strip` does not grow with its children, so we cannot embed the
                // children UI directly here.
                self.details_ui(&mut show_details, ui, project, trim, tx);

                record_binary_state(open_state, &self.id, show_details);
            }
        }
    }

    /// A floating window.
    fn details_ui(
        &mut self,
        show_details: &mut bool,
        ui: &mut egui::Ui,
        project: &Project,
        trim: &DateRange,
        tx: &Sender<ReviewAction>,
    ) {
        egui::Window::new(&self.id)
            .open(show_details)
            // `resizable` and `min_height` won't work
            // `vscroll` helps us avoid `egui::ScrollArea`s manually
            .vscroll(true)
            .default_pos(self.window_pos)
            .show(ui.ctx(), |ui| {
                // title
                ui.vertical_centered(|ui| {
                    ui.label(
                        RichText::new(format!("Showing {}-day range", trim.days_difference()))
                            .small()
                            .strong(),
                    );
                });
                ui.separator();

                // two columns, each containing all review items of the same reviewed state
                egui::Grid::new("stats_grid")
                    .min_col_width(150.)
                    .show(ui, |ui| {
                        let Self {
                            id,
                            typ,
                            window_pos: _,
                            reviewed,
                            not_reviewed,
                            stats_line,
                        } = self;

                        if let StatsLine::All(_) = stats_line {
                            not_reviewed.ui(ui, project, &Header::NOT_REVIEWED_EMPTY, typ, id, tx);
                        } else {
                            not_reviewed.ui(ui, project, &Header::NOT_REVIEWED, typ, id, tx);
                        };

                        reviewed.ui(ui, project, &Header::REVIEWED, typ, id, tx);

                        ui.end_row();
                    });
            });
    }

    /// No need for details UI.
    pub fn total_ui(&self, ui: &mut egui::Ui) {
        ui.label(self.stats_line.total_text());
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// [`Supervision`] (aka. review type) -centric map to series of assets.
pub struct ProjReviewStats {
    pub wip: SupervisionStats,
    pub feedback: SupervisionStats,
    pub approval: SupervisionStats,
    pub client: SupervisionStats,
}

impl ProjReviewStats {
    /// Converts the `ProjReviewVerdict` into stats.
    pub fn new(project: &Project, verdicts: &ProjReviewVerdict) -> Self {
        Self {
            wip: SupervisionStats::from_project_verdicts(project, verdicts, Supervision::Wip),
            feedback: SupervisionStats::from_project_verdicts(
                project,
                verdicts,
                Supervision::Feedback,
            ),
            approval: SupervisionStats::from_project_verdicts(
                project,
                verdicts,
                Supervision::Approval,
            ),
            client: SupervisionStats::from_project_verdicts(project, verdicts, Supervision::Client),
        }
    }

    pub fn debug_count(&self) {
        eprintln!("\n👀 Wip: {}", self.wip.debug_count());
        eprintln!("\n👀 Feedback: {}", self.feedback.debug_count());
        eprintln!("\n👀 Approval: {}", self.approval.debug_count());
        eprintln!("\n👀 Client: {}", self.client.debug_count());
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// Depending on the variants, we'll show different buttons. Representing
/// whether a review item is viewed or not.
enum BinaryStats {
    Reviewed(Stats),

    NotReviewed(Stats),
}

impl BinaryStats {
    fn inner(&self) -> &Stats {
        match &self {
            Self::Reviewed(inner) | Self::NotReviewed(inner) => inner,
        }
    }

    fn count(&self) -> &usize {
        match &self {
            Self::Reviewed(inner) | Self::NotReviewed(inner) => &inner.count,
        }
    }

    /// Whether it's a `Reviewed(_)` variant.
    fn is_positive(&self) -> bool {
        matches!(&self, Self::Reviewed(_))
    }

    #[cfg(feature = "gui")]
    fn ui(
        &self,
        ui: &mut egui::Ui,
        project: &Project,
        header: &Header,
        typ: &Supervision,
        window_id: &String,
        tx: &Sender<ReviewAction>,
    ) {
        ui.vertical(|ui| {
            ui.label(header.text());
            ui.separator();
            egui::Grid::new(header.inner())
                .striped(true)
                .min_col_width(150.)
                .show(ui, |ui| {
                    let is_reviewed_group = self.is_positive();
                    for asset in self.inner().assets.iter() {
                        ui.horizontal(|ui| {
                            // pilot button
                            panproject_pilot_button(ui, project, asset, tx);

                            if is_reviewed_group {
                                // button to mark as "not viewed"
                                panproject_mark_not_viewed_button(ui, project, asset, typ, tx);
                            } else {
                                // button to mark as "viewed"
                                panproject_mark_viewed_button(
                                    ui,
                                    project,
                                    asset,
                                    typ,
                                    self.count(),
                                    window_id,
                                    tx,
                                );
                            };

                            #[cfg(debug_assertions)]
                            panproject_debug_notice_sequence_button(ui, project, asset, tx);

                            // asset name
                            asset.preview_name(ui);
                        });
                        ui.end_row();
                    }
                });
        });
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// Assets of a specific stats, e.g. reviewed or not, with a baked count of `len`.
struct Stats {
    /// These are used to allow "piloting" any [`ProductionAsset`].
    assets: Vec<AssetExcerpt>,
    count: usize,
}

impl Stats {
    fn with_assets(assets: Vec<AssetExcerpt>) -> Self {
        Self {
            count: assets.len(),
            assets,
        }
    }

    /// No `Self::inner` of [`AssetExcerpt`] is stored.
    fn count_only(count: usize) -> Self {
        Self {
            assets: vec![],
            count,
        }
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
/// String showing ratio of viewed and total.
enum StatsLine {
    Zero(&'static str),

    Partial(String),

    All(String),
}

impl StatsLine {
    fn from_count(reviewed: usize, not_reviewed: usize) -> Self {
        let total = reviewed + not_reviewed;
        if total == 0 {
            return Self::Zero("Nothing to review");
        };
        if reviewed == total {
            Self::All(format!("🍻 All {} reviewed", total))
        } else {
            Self::Partial(format!("Reviewed {} of {}", reviewed, total))
        }
    }

    fn total_from_count(reviewed: usize, not_reviewed: usize) -> Self {
        let total = reviewed + not_reviewed;
        if total == 0 {
            return Self::Zero("None");
        };
        if reviewed == total {
            Self::All(format!("🍻 All {} cleared", total))
        } else {
            Self::Partial(format!("{} of {} left", not_reviewed, total))
        }
    }

    #[cfg(feature = "gui")]
    fn text(&self) -> RichText {
        match self {
            Self::Zero(line) => RichText::new(*line).weak().small(),
            Self::Partial(line) => RichText::new(line).color(Color32::LIGHT_RED),
            Self::All(line) => RichText::new(line).color(Color32::LIGHT_GREEN).small(),
        }
    }

    #[cfg(feature = "gui")]
    fn total_text(&self) -> RichText {
        match self {
            Self::Zero(line) => RichText::new(*line).weak(),
            Self::Partial(line) => RichText::new(line).color(Color32::LIGHT_RED),
            Self::All(line) => RichText::new(line).color(Color32::LIGHT_GREEN),
        }
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
/// Inner string used as ID source for [`egui::Grid`].
enum Header {
    Reviewed(&'static str),

    /// Having some items to be reviewed. Red header text, indicating that supervisor should pay attention to.
    NotReviewed(&'static str),

    /// Having no items to be reviewed. Gray header text, indicating that supervisor need not to pay attention to.
    NotReviewedEmpty(&'static str),
}

impl Header {
    const REVIEWED: Header = Self::Reviewed("Reviewed");
    const NOT_REVIEWED: Header = Self::NotReviewed("Not Reviewed");
    const NOT_REVIEWED_EMPTY: Header = Self::NotReviewedEmpty("Not Reviewed");

    fn inner(&self) -> &'static str {
        match self {
            Self::Reviewed(txt) | Self::NotReviewed(txt) | Self::NotReviewedEmpty(txt) => txt,
        }
    }

    #[cfg(feature = "gui")]
    fn text(&self) -> RichText {
        match self {
            Self::Reviewed(txt) => RichText::new(*txt).color(Color32::LIGHT_GREEN).strong(),
            Self::NotReviewed(txt) => RichText::new(*txt).color(Color32::LIGHT_RED).strong(),
            Self::NotReviewedEmpty(txt) => RichText::new(*txt),
        }
    }
}

#[cfg(feature = "gui")]
fn panproject_pilot_button(
    ui: &mut egui::Ui,
    project: &Project,
    asset: &AssetExcerpt,
    tx: &Sender<ReviewAction>,
) {
    if ui
        .button(
            RichText::new("")
                .color(Color32::BLACK)
                .background_color(Color32::LIGHT_GRAY),
        )
        .on_hover_text(RichText::new("Pilot this asset").color(Color32::YELLOW))
        .clicked()
    {
        tx.send(ReviewAction::pilot(project, asset))
            .expect(&format!(
                "Failed to send ReviewAction::Pilot via channel for {:?}",
                asset
            ));
    };
}

#[cfg(feature = "gui")]
fn panproject_mark_viewed_button(
    ui: &mut egui::Ui,
    project: &Project,
    asset: &AssetExcerpt,
    typ: &Supervision,
    existing_unreviewed: &usize,
    window_id: &String,
    tx: &Sender<ReviewAction>,
) {
    if ui
        .button("Y")
        .on_hover_text(RichText::new("Mark this asset as reviewed").color(Color32::LIGHT_GREEN))
        .clicked()
    {
        tx.send(ReviewAction::mark_reviewed(
            project,
            asset,
            typ,
            existing_unreviewed,
            window_id,
        ))
        .expect(&format!(
            "Failed to send ReviewAction::MarkReviewed via channel for {:?}",
            asset
        ));
    };
}

#[cfg(feature = "gui")]
fn panproject_mark_not_viewed_button(
    ui: &mut egui::Ui,
    project: &Project,
    asset: &AssetExcerpt,
    typ: &Supervision,
    tx: &Sender<ReviewAction>,
) {
    if ui
        .button("N")
        .on_hover_text(RichText::new("Mark this asset as NOT reviewed").color(Color32::LIGHT_RED))
        .clicked()
    {
        tx.send(ReviewAction::mark_not_reviewed(project, asset, typ))
            .expect(&format!(
                "Failed to send ReviewAction::MarkNotReviewed via channel for {:?}",
                asset
            ));
    };
}

#[cfg(debug_assertions)]
#[cfg(feature = "gui")]
fn panproject_debug_notice_sequence_button(
    ui: &mut egui::Ui,
    project: &Project,
    asset: &AssetExcerpt,
    tx: &Sender<ReviewAction>,
) {
    if ui
        .button(RichText::new("👓").color(Color32::RED))
        .on_hover_text("Examine this asset's NoticeSequence")
        .clicked()
    {
        tx.send(ReviewAction::debug_notice_sequence(project, asset))
            .expect(&format!(
                "Failed to send ReviewAction::DebugNoticeSequence via channel for {:?}",
                asset
            ));
    };
}