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
use super::*;
#[cfg(feature = "gui")]
use crossbeam_channel::Sender;

#[derive(Debug, Clone)]
/// Action performed on a [`DeliveryTemplate`].
pub enum TemplateAction {
    Create(DeliveryTemplate),
    Edit(DeliveryTemplate),
    Delete(DeliveryTemplate),
    MakeDefault(ProductionDefault),
    SetAssetStage(StageIndex),
    UnsetAssetStage(StageIndex),
}

// -------------------------------------------------------------------------------
#[async_trait]
/// Methods that allows CRUD with [`DeliveryTemplate`]s from/to DB.
pub trait DeliveryStages: DynClone + fmt::Debug + Send + Sync {
    async fn delivery_template_from_bson_id(
        &self,
        project: &Project,
        id: &ObjectId,
    ) -> Result<DeliveryTemplate, DatabaseError>;

    /// Lists all [`DeliveryTemplate`]s of the given project.
    async fn delivery_templates(
        &self,
        project: &Project,
    ) -> Result<Vec<DeliveryTemplate>, DatabaseError>;

    /// Adds a new [`DeliveryTemplate`] for the given project.
    async fn add_delivery_template(
        &self,
        project: &Project,
        template: DeliveryTemplate,
    ) -> Result<(), ModificationError>;

    /// Updates an existing [`DeliveryTemplate`].
    async fn edit_delivery_template(
        &self,
        project: &Project,
        existing: Option<DeliveryTemplate>,
        updated: DeliveryTemplate,
    ) -> Result<(), ModificationError>;

    /// Deletes an existing [`DeliveryTemplate`].
    async fn delete_delivery_template(
        &self,
        project: &Project,
        template: DeliveryTemplate,
    ) -> Result<(), ModificationError>;
}

dyn_clone::clone_trait_object!(DeliveryStages);

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryTemplate {
    #[serde(skip)]
    mode: MediaMode,

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

    pub name: String,

    pub description: String,

    /// Each `Stage` is put behind an `Option` so we can conveniently discard
    /// a `Stage` during drafting in the UI.
    pub(super) stages: Vec<Option<Stage>>,

    #[serde(skip)]
    pub template: Template,
}

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

    fn bson_id(&self) -> AnyResult<&ObjectId> {
        self.id
            .as_ref()
            .context("Bad DeliveryTemplate with no ObjectId")
    }
}

impl DeliveryTemplate {
    fn empty() -> Self {
        Self {
            mode: Default::default(),
            id: None,
            name: String::new(),
            description: String::new(),
            stages: vec![],
            template: Template::empty(),
        }
    }

    /// With name and description for the root of the graph.
    pub fn new(name: &str, description: &str) -> Self {
        Self {
            name: name.to_owned(),
            description: description.to_owned(),
            template: Template::with_root(name, description),
            ..Self::empty()
        }
    }

    #[cfg(debug_assertions)]
    pub fn add_stage(&mut self, stage: Stage) {
        self.stages.push(Some(stage));
    }

    /// Constructs a graph with root node using `Self::name` and `Self::description`.
    fn empty_graph(&self) -> StageGraph {
        StageGraph::with_root(&self.name, &self.description)
    }

    /// Assigns `Self::template::graph` with a graph containing one root node
    /// using `Self::name` and `Self::description`.
    fn reset_graph(&mut self) {
        self.template.graph = self.empty_graph();
    }

    /// Resets all `Stage::has_reference_to` values in `Self::template::stage_order`
    /// to avoid stale UI display.
    pub(super) fn reset_reference(&mut self) {
        self.template.stage_order.iter_mut().for_each(|s| {
            s.has_reference_to = false;
        });
    }

    pub fn stage_generic_purpose_mut(&mut self) {
        self.stages.iter_mut().enumerate().for_each(|(i, s)| {
            if let Some(stage) = s {
                stage.index = Some(StageIndex::Generic(i as u32));
            };
        });
    }

    pub fn stage_internal_purpose_mut(&mut self) {
        self.stages.iter_mut().enumerate().for_each(|(i, s)| {
            if let Some(stage) = s {
                stage.index = Some(StageIndex::Internal(i as u32));
            };
        });
    }

    pub fn stage_outgoing_purpose_mut(&mut self) {
        self.stages.iter_mut().enumerate().for_each(|(i, s)| {
            if let Some(stage) = s {
                stage.index = Some(StageIndex::Outgoing(i as u32));
            };
        });
    }

    /// Constructs the internal DAG based on the current `Self::stages`,
    /// while also records all graph errors. Therefore, the `StageIndex` purpose
    /// should be setup prior to this.
    /// NOTE: this retains the graph root.
    pub fn construct_stage_graph(&mut self) {
        self.template.graph_mut_from_stages(&self.stages);
        self.template.stage_order_mut();
    }

    /// Constructs the internal DAG based on the current `Self::stages`, but
    /// skipping all `None` variants.
    /// NOTE: this re-create the `StageGraph` in `Self::template`.
    pub fn rewrite_graph_from_stages(&mut self) {
        // removes `None` variant
        self.stages.retain(|s| s.is_some());

        // uses current -- probably edited -- name and description
        self.reset_graph();

        // parses dependency_drafts
        // SAFETY: each element of `Self::stages` should be `is_some` by this time
        self.stages.iter_mut().for_each(|s| {
            s.as_mut().unwrap().parse_dependency_draft();
        });

        let stages = self
            .stages
            .iter()
            .map(|s| s.as_ref().unwrap())
            .collect::<Vec<&Stage>>();

        self.template.rewrite_graph_from_stages(stages.as_slice());
        self.template.stage_order_mut();
    }

    fn name_check(&self) -> AnyResult<()> {
        // don't accept empty template name
        if self.name.is_empty() {
            return Err(anyhow!("Workflow name cannot be empty"));
        };

        // don't accept empty stage names
        if self
            .stages
            .iter()
            .filter(|s| s.is_some())
            .any(|s| s.as_ref().unwrap().name.is_empty())
        {
            return Err(anyhow!("No stage name can be left blank"));
        };

        Ok(())
    }

    /// Constructs the internal DAG based on the current description,
    /// and returns `Err` if encountering any error during doing so.
    pub fn validate(&mut self) -> AnyResult<()> {
        self.name_check()?;
        self.rewrite_graph_from_stages();

        // SAFETY: `Self::template::graph_err` should be `is_some` by this time
        match self
            .template
            .graph_err
            .as_ref()
            .unwrap()
            .iter()
            .filter(|r| r.is_err())
            .next()
        {
            Some(r) => Err(anyhow!(
                "The dependency graph is not valid: {}. Please fix the Stages and try again.",
                r.as_ref().err().unwrap()
            )),
            None => Ok(()),
        }
    }
}

#[cfg(feature = "gui")]
impl DeliveryTemplate {
    fn health_ui(&self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            // Graph errors
            self.template.graph_err_ui(ui);
            ui.heading(&self.name);
        });
    }

    /// Not checking for empty names.
    fn validate_button(&mut self, ui: &mut egui::Ui) {
        if ui
            .button("🛃 Validate")
            .on_hover_text("Check if the described dependency above is valid")
            .clicked()
        {
            self.rewrite_graph_from_stages();
        };
    }

    /// Submit/cancel the draft
    pub fn show_submit_draft_buttons(&mut self, ui: &mut egui::Ui, tx: &Sender<TemplateAction>) {
        if let MediaMode::WriteCompose = self.mode {
            ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                if ui.button("❌ Cancel").clicked() {
                    self.mode_mut(MediaMode::WriteSuggest);
                };
                if ui
                    .button("✔ Create")
                    .on_hover_text("Submit this Workflow Definition for current project")
                    .clicked()
                {
                    tx.send(TemplateAction::Create(self.clone())).ok();
                };
                self.validate_button(ui);
            });
        };
    }

    pub fn show_submit_edit_buttons(&mut self, ui: &mut egui::Ui, tx: &Sender<TemplateAction>) {
        if let MediaMode::WriteCompose = self.mode {
            ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                if ui
                    .button("❌ Cancel")
                    .on_hover_text("Go back to View mode")
                    .clicked()
                {
                    // this DOES NOT discard any edits made
                    self.mode_mut(MediaMode::Read);
                };
                if ui
                    .button("✔ Submit")
                    .on_hover_text(format!("Save edits for {} definition", self.name))
                    .clicked()
                {
                    tx.send(TemplateAction::Edit(self.clone())).ok();
                };
                self.validate_button(ui);
            });
        };
    }

    pub fn show_delete_button(&mut self, ui: &mut egui::Ui, tx: &Sender<TemplateAction>) {
        if ui
            .button(RichText::new("🗑").color(egui::Color32::RED))
            .on_hover_text(format!("Delete definition of workflow \"{}\"", self.name))
            .clicked()
        {
            tx.send(TemplateAction::Delete(self.clone())).ok();
        };
    }

    /// Just enables editing.
    pub fn show_edit_buttons(&mut self, ui: &mut egui::Ui) {
        match &self.mode {
            MediaMode::WriteCompose => {
                // not showing the button
            }
            _ => {
                if ui
                    .button("🖊")
                    .on_hover_text(format!("Edit definition of workflow \"{}\"", self.name))
                    .clicked()
                {
                    self.mode_mut(MediaMode::WriteCompose);
                };
            }
        }
    }

    pub fn show_make_default_buttons(&mut self, ui: &mut egui::Ui, tx: &Sender<TemplateAction>) {
        // Make default for Outgoing
        if ui
            .button(RichText::new("O").strong())
            .on_hover_text(
                RichText::new(format!(
                    "Make \"{}\" workflow default for {}",
                    self.name,
                    ProductionDefault::outgoing_as_str()
                ))
                .color(Color32::LIGHT_GREEN),
            )
            .clicked()
        {
            tx.send(TemplateAction::MakeDefault(ProductionDefault::Outgoing(
                self.clone(),
            )))
            .ok();
        };
        // Make default for Internal
        if ui
            .button(RichText::new("I").strong())
            .on_hover_text(
                RichText::new(format!(
                    "Make \"{}\" workflow default for {}",
                    self.name,
                    ProductionDefault::internal_as_str()
                ))
                .color(Color32::LIGHT_RED),
            )
            .clicked()
        {
            tx.send(TemplateAction::MakeDefault(ProductionDefault::Internal(
                self.clone(),
            )))
            .ok();
        };
    }

    /// Depending on `Self::mode` to show the UI for reading, or the UI for editing.
    pub fn ui(&mut self, ui: &mut egui::Ui) {
        match &self.mode {
            MediaMode::Read => self.read_mode_ui(ui),
            MediaMode::WriteSuggest => {
                self.write_suggest_ui(ui);
            }
            MediaMode::WriteCompose => {
                self.write_compose_ui(ui);
            }
            MediaMode::WriteEdit => {
                self.write_edit_ui(ui);
            }
        }
    }
}

impl ReadWriteSuggest for DeliveryTemplate {
    fn write_suggest() -> Self {
        let mut draft = Self {
            mode: MediaMode::WriteSuggest,
            ..Self::empty()
        };
        draft.template.graph_err = Some(vec![Err(GraphError::NotChecked)]);
        draft
    }

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

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

    fn mode_mut(&mut self, mode: MediaMode) {
        let should_init_draft = mode == MediaMode::WriteCompose;
        self.stages.iter_mut().for_each(|s| {
            if let Some(stage) = s {
                stage.mode_mut(mode.clone());
                // inits draft
                if should_init_draft {
                    stage.init_draft_from_existing();
                };
            };
        });
        self.mode = mode;
    }

    #[cfg(feature = "gui")]
    fn read_mode_ui(&mut self, ui: &mut egui::Ui) {
        ui.vertical(|ui| {
            self.health_ui(ui);
            ui.label(&self.description);
            // Stage order
            self.template.stage_order_vertical_ui(ui, &self.name);
        });
    }

    #[cfg(feature = "gui")]
    fn write_suggest_ui(&mut self, ui: &mut egui::Ui) {
        ui.vertical_centered(|ui| {
            if ui.button("➕ New Workflow Definition").clicked() {
                self.mode_mut(MediaMode::WriteCompose);
            };
        });
    }

    #[cfg(feature = "gui")]
    fn write_compose_ui(&mut self, ui: &mut egui::Ui) {
        ui.vertical(|ui| {
            // name
            ui.horizontal(|ui| {
                // Graph errors
                self.template.graph_err_ui(ui);

                ui.label("Workflow name:");
                ui.add(egui::TextEdit::singleline(&mut self.name).desired_width(150.));
            });
            // description
            ui.horizontal(|ui| {
                ui.label("Description:");
                ui.text_edit_singleline(&mut self.description);
            });
            // stages
            egui::ScrollArea::vertical()
                .id_source(&self.name)
                .min_scrolled_height(500.)
                .max_height(900.)
                .show(ui, |ui| {
                    self.stages
                        .iter_mut()
                        .filter(|s| s.is_some())
                        .for_each(|s| {
                            ui.group(|ui| {
                                s.as_mut().unwrap().ui(ui);
                                // must be invoked last
                                if ui
                                    .button("🗑 Remove")
                                    .on_hover_text(
                                        if self.name.is_empty() {
                                            RichText::new("Delete this Stage")
                                        } else {
                                            RichText::new(format!("Delete \"{}\" stage", self.name))
                                        }
                                        .color(Color32::RED),
                                    )
                                    .clicked()
                                {
                                    s.take();
                                };
                            });
                        });
                });
            // add stage
            ui.horizontal(|ui| {
                if ui
                    .button(RichText::new("➕ Add Stage").strong())
                    .on_hover_text("Add one more Stage to this Workflow")
                    .clicked()
                {
                    self.stages.push(Some(Stage::draft()));
                };
            });
        });
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug)]
pub struct DeliTemplateReadBuilder(DeliveryTemplate);

impl DeliTemplateReadBuilder {
    pub fn new(template: DeliveryTemplate) -> Self {
        Self(template)
    }

    /// Filters out all non-internal [`Stage`]s.
    pub fn internal_stages_only(mut self) -> Self {
        self.0.template.stage_order = self
            .0
            .template
            .stage_order
            .into_iter()
            .filter(|s| s.is_internal)
            .collect();
        self
    }

    /// Filters out all internal [`Stage`]s.
    pub fn outgoing_stages_only(mut self) -> Self {
        self.0.template.stage_order = self
            .0
            .template
            .stage_order
            .into_iter()
            .filter(|s| !s.is_internal)
            .collect();
        self
    }

    pub fn construct_generic_stage_graph(mut self) -> Self {
        // must construct root node first
        self.0.reset_graph();
        self.0.stage_generic_purpose_mut();
        // adds `Stage`s to internal DAG
        self.0.construct_stage_graph();
        self
    }

    pub fn construct_internal_stage_graph(mut self) -> Self {
        // must construct root node first
        self.0.reset_graph();
        self.0.stage_internal_purpose_mut();
        // adds `Stage`s to internal DAG
        self.0.construct_stage_graph();
        self
    }

    pub fn construct_outgoing_stage_graph(mut self) -> Self {
        // must construct root node first
        self.0.reset_graph();
        self.0.stage_outgoing_purpose_mut();
        // adds `Stage`s to internal DAG
        self.0.construct_stage_graph();
        self
    }

    pub fn finish(self) -> DeliveryTemplate {
        self.0
    }
}

// -------------------------------------------------------------------------------
pub struct DeliTemplateWriteBuilder(DeliveryTemplate);

impl DeliTemplateWriteBuilder {
    pub fn new(template: DeliveryTemplate) -> Self {
        Self(template)
    }

    pub fn finish(mut self) -> DeliveryTemplate {
        // trims name and description
        self.0.name = self.0.name.trim().to_owned();
        self.0.description = self.0.description.trim().to_owned();
        self.0
    }
}