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
use super::*;

#[cfg(feature = "ticket")]
use crate::{ticket, Locale};

#[cfg(feature = "html")]
use hconf::CONVERT_PATH_TO_STR_ERR;
use mkutil::tempfile::NamedTempFile;

#[cfg(all(feature = "image_processing", feature = "gui"))]
use mkutil::clipboard;

#[cfg(feature = "html")]
use html_builder::{Buffer, Html5};
#[cfg(feature = "html")]
use std::fmt::Write;

pub(crate) const NULL_COMPOSER_ERR: &str = "Composer is null";

// ----------------------------------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct DiscardableComposer(pub(crate) Option<Composer>);

impl DiscardableComposer {
    pub fn empty() -> Self {
        Self(None)
    }

    pub fn is_some(&self) -> bool {
        self.0.is_some()
    }

    pub fn is_none(&self) -> bool {
        self.0.is_none()
    }

    pub fn new(tagline: &str) -> Self {
        Self(Some(Composer::with_tagline(tagline)))
    }

    pub fn from_note(note: &Note, tagline: &str) -> Self {
        let composer: Composer = note.into();
        Self(Some(composer.tagline(tagline)))
    }

    pub fn inner(&self) -> AnyResult<&Composer> {
        Ok(self.0.as_ref().context(NULL_COMPOSER_ERR)?)
    }

    pub fn inner_as_mut(&mut self) -> AnyResult<&mut Composer> {
        Ok(self.0.as_mut().context(NULL_COMPOSER_ERR)?)
    }

    pub fn inner_as_ref_unwrap(&self) -> &Composer {
        self.0.as_ref().expect(NULL_COMPOSER_ERR)
    }

    pub fn inner_as_mut_unwrap(&mut self) -> &mut Composer {
        self.0.as_mut().expect(NULL_COMPOSER_ERR)
    }

    #[cfg(feature = "gui")]
    pub fn draft_unwrap_with_discard_ui(&mut self, ui: &mut egui::Ui, idx: usize) {
        self.inner_as_mut_unwrap()
            .draft_text_and_images_ui(ui, format!("composer{}", idx));

        // must be invoked last
        if ui
            .button(format!("🗑 Remove #{}", idx + 1))
            .on_hover_text(
                RichText::new("Delete current draft for this subticket").color(Color32::RED),
            )
            .clicked()
        {
            // drop all the temp files
            self.inner_as_mut_unwrap().clear_all();
            self.0.take();
        };
    }
}

// ----------------------------------------------------------------------------
#[derive(Debug, Default)]
pub struct Composer {
    /// Instruction line.
    tagline: String,

    /// The text typed by user into a `egui::TextEdit`.
    text: String,

    /// Images pasted from clipboard and saved temporarily.
    pasted_images: Vec<UserImage<NamedTempFile>>,

    /// Images picked by File Dialog.
    picked_images: Vec<UserImage<PathBuf>>,
}

impl std::clone::Clone for Composer {
    fn clone(&self) -> Self {
        Self {
            tagline: self.tagline.clone(),
            text: self.text.clone(),
            // ATTENTION: lossy clone
            pasted_images: vec![],
            // ATTENTION: lossy clone
            picked_images: vec![],
        }
    }
}

impl Composer {
    pub(crate) fn with_tagline(tagline: &str) -> Self {
        Self {
            tagline: tagline.to_owned(),
            ..Default::default()
        }
    }

    fn tagline(mut self, tagline: &str) -> Self {
        self.tagline = tagline.to_owned();
        self
    }

    fn contains_no_images(&self) -> bool {
        self.picked_images.is_empty() && self.pasted_images.is_empty()
    }

    /// Whether there is no content either in the `TextEdit` or the picked|pasted images.
    /// NOTE: this is still yielding false after user discarded their image selection.
    pub fn is_empty(&self) -> bool {
        self.text.is_empty() && self.contains_no_images()
    }

    #[cfg(feature = "image_processing")]
    /// Adds new temp file whose upload process hasn't been made.
    fn push_pasted_image(&mut self, pasted: NamedTempFile) {
        self.pasted_images.push(UserImage::selecting(pasted));
    }

    #[cfg(feature = "image_processing")]
    /// Adds an existing file whose upload process hasn't been made.
    fn append_picked_images(&mut self, picked: Vec<PathBuf>) {
        self.picked_images.append(
            &mut picked
                .into_iter()
                .map(|p| UserImage::selecting(p))
                .collect(),
        )
    }

    #[cfg(debug_assertions)]
    /// Displays upload result of each file.
    fn log_uploaded(&self) {
        self.pasted_images
            .iter()
            .filter(|img| img.is_selected())
            .for_each(|img| img.log_uploaded_unwrap());

        self.picked_images
            .iter()
            .filter(|img| img.is_selected())
            .for_each(|img| img.log_uploaded_unwrap());
    }

    fn clear_images(&mut self) {
        self.pasted_images.clear();
        self.picked_images.clear();
    }

    pub fn clear_all(&mut self) {
        self.clear_images();
        self.text.clear();
    }

    /// Returns number of files uploaded successfully
    /// (files unselected by user won't be attempted for uploading).
    /// The `upload_method` gets to decide the details of the uploading, i.e.
    /// destination, file name handling, etc.
    pub fn upload_images(
        &mut self,
        project: &Project,
        asset: &ProductionAsset,
        upload: impl Fn(&Path, &Project, &ProductionAsset) -> AnyResult<PathBuf>,
    ) -> ImageUploaded {
        if self.contains_no_images() {
            info!("Found no images in Composer to upload");
            return ImageUploaded::NoTask;
        };

        let mut count: u8 = 0;

        // iterates over the clipboard images, skips all items unselected by the user
        self.pasted_images
            .iter_mut()
            .filter(|img| img.is_selected())
            .for_each(|img| {
                img.uploaded_mut(
                    upload(img.selecting_as_ref_unwrap().path(), &project, &asset),
                    &mut count,
                );
            });

        // iterates over the images picked from a File Dialog, skips all items unselected by the user
        self.picked_images
            .iter_mut()
            .filter(|img| img.is_selected())
            .for_each(|img| {
                img.uploaded_mut(
                    upload(img.selecting_as_ref_unwrap().as_path(), &project, &asset),
                    &mut count,
                );
            });

        #[cfg(debug_assertions)]
        // logs upload fails
        self.log_uploaded();

        ImageUploaded::Success(count)
    }

    #[cfg(feature = "html")]
    /// Concatenates `Self::text`, `Self::pasted_images`, and `Self::picked_images`, into HTML string.
    /// LEGACY DESIGN: `img` tag must be put inside `p` tag
    /// in order to work with `mkutil::html_scraping::grab_text_elements()`,
    /// and the HTML doc doesn't look for doctype, html, header, body, tags.
    pub fn into_html_legacy(&self) -> AnyResult<String> {
        // start a buffer
        let mut buf = Buffer::new();
        let mut div = buf.div();
        let mut p = div.p();
        // composer text
        writeln!(p, "{}", self.text)?;

        // pasted images
        self.pasted_images
            .iter()
            .filter_map(|img| img.uploaded.as_ref())
            .filter_map(|uploaded| uploaded.as_ref().ok())
            .map(|img| img.to_str().expect(CONVERT_PATH_TO_STR_ERR).to_string())
            .for_each(|path| {
                p.img().attr(&format!("src=\"{}\"", path));
            });

        // picked images
        self.picked_images
            .iter()
            .filter_map(|img| img.uploaded.as_ref())
            .filter_map(|uploaded| uploaded.as_ref().ok())
            .map(|img| img.to_str().expect(CONVERT_PATH_TO_STR_ERR).to_string())
            .for_each(|path| {
                p.img().attr(&format!("src=\"{}\"", path));
            });

        // extract the buffer
        Ok(buf.finish())
    }

    #[cfg(feature = "ticket")]
    pub(crate) fn into_subticket_multilingual_note(
        &self,
        composing_locale: &Locale,
    ) -> AnyResult<ticket::SubTicketRawNote> {
        let html = self.into_html_legacy()?;
        let mut subticket_note = ticket::SubTicketRawNote::empty();

        match composing_locale {
            Locale::EN => {
                subticket_note.en = Some(html);
            }
            Locale::VI => {
                subticket_note.vi = Some(html);
            }
            Locale::ZH => {
                subticket_note.zh = Some(html);
            }
            Locale::FR => {
                subticket_note.fr = Some(html);
            }
        };
        Ok(subticket_note)
    }
}

#[cfg(feature = "gui")]
impl Composer {
    fn show_selected_images(&mut self, ui: &mut egui::Ui, id_source: impl std::hash::Hash) {
        if self.contains_no_images() {
            return;
        };

        egui::Grid::new(id_source).show(ui, |ui| {
            self.pasted_images
                .iter_mut()
                .enumerate()
                .for_each(|(i, img)| {
                    img.hint_saved_ui(ui, i);
                    ui.end_row();
                });

            self.picked_images.iter_mut().for_each(|img| {
                img.hint_selected_ui(ui);
                ui.end_row();
            });
        });
    }

    fn show_upload_images_buttons(&mut self, ui: &mut egui::Ui) {
        if ui
            .button("⊗ Clear All")
            .on_hover_text("Remove all saved clipboard-images and all chosen images for this draft")
            .clicked()
        {
            self.clear_images();
        };

        #[cfg(feature = "image_processing")]
        if ui
            .button(if cfg!(target_os = "windows") {
                RichText::new("📋 Pixels").weak()
            } else {
                RichText::new("📋 Paste")
            })
            .on_hover_text(if cfg!(target_os = "windows") {
                "Paste image from clipboard (when using with Windows + Shift + S)"
            } else {
                "Paste image from clipboard"
            })
            .clicked()
        {
            if let Ok(img) = clipboard::save_temp_image(None) {
                self.push_pasted_image(img);
            };
        };

        #[cfg(feature = "image_processing")]
        // File Dialog
        if ui
            .button("📁 Image")
            .on_hover_text("Browse to existing images")
            .clicked()
        {
            if let Some(picked) = mkutil::dialog::pick_images_sync() {
                self.append_picked_images(picked);
            };
        };
    }

    fn menu_ui(&mut self, ui: &mut egui::Ui, _easy_mark_help: bool) {
        ui.horizontal(|ui| {
            ui.label(&self.tagline);

            ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                #[cfg(feature = "easy_mark")]
                if _easy_mark_help {
                    crate::locale::easy_mark_syntax_help(ui);
                };

                self.show_upload_images_buttons(ui);
            });
        });
    }

    pub fn draft_text_and_images_ui(&mut self, ui: &mut egui::Ui, id_source: impl std::hash::Hash) {
        ui.vertical(|ui| {
            self.menu_ui(ui, true);

            // let response =
            ui.add(egui::TextEdit::multiline(&mut self.text).desired_width(f32::INFINITY));

            // if let Some(mut _state) = egui::TextEdit::load_state(ui.ctx(), response.id) {
            // 	shortcuts(ui, &mut composer.text);
            // };

            self.show_selected_images(ui, id_source);
        });
    }

    pub fn draft_images_only_ui(&mut self, ui: &mut egui::Ui, id_source: impl std::hash::Hash) {
        ui.vertical(|ui| {
            self.menu_ui(ui, false);
            self.show_selected_images(ui, id_source);
        });
    }
}

impl From<&Note> for Composer {
    /// All paths of the embedded images inside the `Note` are cloned
    /// into the `Composer::picked_images`.
    fn from(note: &Note) -> Self {
        Self {
            text: note.text.trim().to_owned(), // also removes whitespaces
            picked_images: match note.embed_layout.img_paths_as_ref() {
                Some(paths) => paths
                    .iter()
                    .map(|p| UserImage::selecting(p.clone()))
                    .collect(),
                None => vec![],
            },
            // `Self::pasted_images` is left empty
            ..Default::default()
        }
    }
}

// // ----------------------------------------------------------------------------
// fn shortcuts(
// 	ui: &egui::Ui,
// 	_text: &mut dyn TextBuffer,
// 	//  ccursor_range: &mut CCursorRange
// ) -> bool {
// 	let mut any_change = false;
// 	for event in &ui.input().events {
// 		if let egui::Event::Key {
// 			key,
// 			pressed: true,
// 			modifiers,
// 		} = event
// 		{
// 			if modifiers.command_only() {
// 				match &key {
// 					egui::Key::V => {
// 						any_change = true;
// 					}
// 					_ => {}
// 				}
// 			}
// 		}
// 	}
// 	any_change
// }