-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathsketch_board.rs
548 lines (488 loc) · 18.4 KB
/
sketch_board.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
use anyhow::anyhow;
use femtovg::imgref::Img;
use femtovg::rgb::{ComponentBytes, RGBA};
use gdk_pixbuf::glib::Bytes;
use gdk_pixbuf::Pixbuf;
use keycode::{KeyMap, KeyMappingId};
use std::cell::RefCell;
use std::fs;
use std::io::Write;
use std::process::{Command, Stdio};
use std::rc::Rc;
use gtk::prelude::*;
use relm4::gtk::gdk::{DisplayManager, Key, ModifierType, Texture};
use relm4::{gtk, Component, ComponentParts, ComponentSender};
use crate::configuration::{Action, APP_CONFIG};
use crate::femtovg_area::FemtoVGArea;
use crate::math::Vec2D;
use crate::notification::log_result;
use crate::style::Style;
use crate::tools::{Tool, ToolEvent, ToolUpdateResult, ToolsManager};
use crate::ui::toolbars::ToolbarEvent;
type RenderedImage = Img<Vec<RGBA<u8>>>;
#[derive(Debug, Clone)]
pub enum SketchBoardInput {
InputEvent(InputEvent),
ToolbarEvent(ToolbarEvent),
RenderResult(RenderedImage, Action),
}
#[derive(Debug, Clone)]
pub enum SketchBoardOutput {
ToggleToolbarsDisplay,
}
#[derive(Debug, Clone)]
pub enum InputEvent {
Mouse(MouseEventMsg),
Key(KeyEventMsg),
KeyRelease(KeyEventMsg),
Text(TextEventMsg),
}
// from https://flatuicolors.com/palette/au
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum MouseButton {
Primary,
Secondary,
Middle,
}
#[derive(Debug, Clone, Copy)]
pub struct KeyEventMsg {
pub key: Key,
pub code: u32,
pub modifier: ModifierType,
}
#[derive(Debug, Clone)]
pub enum TextEventMsg {
Commit(String),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MouseEventType {
BeginDrag,
EndDrag,
UpdateDrag,
Click,
//Motion(Vec2D),
}
#[derive(Debug, Clone, Copy)]
pub struct MouseEventMsg {
pub type_: MouseEventType,
pub button: MouseButton,
pub modifier: ModifierType,
pub pos: Vec2D,
}
impl SketchBoardInput {
pub fn new_mouse_event(
event_type: MouseEventType,
button: u32,
modifier: ModifierType,
pos: Vec2D,
) -> SketchBoardInput {
SketchBoardInput::InputEvent(InputEvent::Mouse(MouseEventMsg {
type_: event_type,
button: button.into(),
modifier,
pos,
}))
}
pub fn new_key_event(event: KeyEventMsg) -> SketchBoardInput {
SketchBoardInput::InputEvent(InputEvent::Key(event))
}
pub fn new_key_release_event(event: KeyEventMsg) -> SketchBoardInput {
SketchBoardInput::InputEvent(InputEvent::KeyRelease(event))
}
pub fn new_text_event(event: TextEventMsg) -> SketchBoardInput {
SketchBoardInput::InputEvent(InputEvent::Text(event))
}
}
impl From<u32> for MouseButton {
fn from(value: u32) -> Self {
match value {
gtk::gdk::BUTTON_PRIMARY => MouseButton::Primary,
gtk::gdk::BUTTON_MIDDLE => MouseButton::Middle,
gtk::gdk::BUTTON_SECONDARY => MouseButton::Secondary,
_ => MouseButton::Primary,
}
}
}
impl InputEvent {
fn remap_event_coordinates(&mut self, renderer: &FemtoVGArea) {
if let InputEvent::Mouse(me) = self {
match me.type_ {
MouseEventType::BeginDrag | MouseEventType::Click => {
me.pos = renderer.abs_canvas_to_image_coordinates(me.pos)
}
MouseEventType::EndDrag | MouseEventType::UpdateDrag => {
me.pos = renderer.rel_canvas_to_image_coordinates(me.pos)
}
}
};
}
}
pub struct SketchBoard {
renderer: FemtoVGArea,
active_tool: Rc<RefCell<dyn Tool>>,
tools: ToolsManager,
style: Style,
}
impl SketchBoard {
fn refresh_screen(&mut self) {
self.renderer.queue_render();
}
fn image_to_pixbuf(image: RenderedImage) -> Pixbuf {
let (buf, w, h) = image.into_contiguous_buf();
Pixbuf::from_bytes(
&Bytes::from(buf.as_bytes()),
gdk_pixbuf::Colorspace::Rgb,
true,
8,
w as i32,
h as i32,
w as i32 * 4,
)
}
fn handle_render_result(&self, image: RenderedImage, action: Action) {
match action {
Action::SaveToClipboard => self.handle_copy_clipboard(Self::image_to_pixbuf(image)),
Action::SaveToFile => self.handle_save(Self::image_to_pixbuf(image)),
};
if APP_CONFIG.read().early_exit() {
relm4::main_application().quit();
}
}
fn handle_save(&self, image: Pixbuf) {
let output_filename = match APP_CONFIG.read().output_filename() {
None => {
println!("No Output filename specified!");
return;
}
Some(o) => o.clone(),
};
// run the output filename by "chrono date format"
let output_filename = format!("{}", chrono::Local::now().format(&output_filename));
// TODO: we could support more data types
if !output_filename.ends_with(".png") {
log_result(
"The only supported format is png, but the filename does not end in png",
!APP_CONFIG.read().disable_notifications(),
);
return;
}
let data = match image.save_to_bufferv("png", &Vec::new()) {
Ok(d) => d,
Err(e) => {
println!("Error serializing image: {e}");
return;
}
};
match fs::write(&output_filename, data) {
Err(e) => log_result(
&format!("Error while saving file: {e}"),
!APP_CONFIG.read().disable_notifications(),
),
Ok(_) => log_result(
&format!("File saved to '{}'.", &output_filename),
!APP_CONFIG.read().disable_notifications(),
),
};
}
fn save_to_clipboard(&self, texture: &impl IsA<Texture>) -> anyhow::Result<()> {
let display = DisplayManager::get()
.default_display()
.ok_or(anyhow!("Cannot open default display for clipboard."))?;
display.clipboard().set_texture(texture);
Ok(())
}
fn save_to_external_process(
&self,
texture: &impl IsA<Texture>,
command: &str,
) -> anyhow::Result<()> {
let mut child = Command::new("sh")
.arg("-c")
.arg(command)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.spawn()?;
let child_stdin = child.stdin.as_mut().unwrap();
child_stdin.write_all(texture.save_to_png_bytes().as_ref())?;
if !child.wait()?.success() {
return Err(anyhow!("Writing to process '{command}' failed."));
}
Ok(())
}
fn handle_copy_clipboard(&self, image: Pixbuf) {
let texture = Texture::for_pixbuf(&image);
let result = if let Some(command) = APP_CONFIG.read().copy_command() {
self.save_to_external_process(&texture, command)
} else {
self.save_to_clipboard(&texture)
};
match result {
Err(e) => println!("Error saving {e}"),
Ok(()) => {
log_result(
"Copied to clipboard.",
!APP_CONFIG.read().disable_notifications(),
);
// TODO: rethink order and messaging patterns
if APP_CONFIG.read().save_after_copy() {
self.handle_save(image);
};
}
}
}
fn handle_undo(&mut self) -> ToolUpdateResult {
if self.active_tool.borrow().active() {
self.active_tool.borrow_mut().handle_undo()
} else if self.renderer.undo() {
ToolUpdateResult::Redraw
} else {
ToolUpdateResult::Unmodified
}
}
fn handle_redo(&mut self) -> ToolUpdateResult {
if self.active_tool.borrow().active() {
self.active_tool.borrow_mut().handle_redo()
} else if self.renderer.redo() {
ToolUpdateResult::Redraw
} else {
ToolUpdateResult::Unmodified
}
}
// Toolbars = Tools Toolbar + Style Toolbar
fn handle_toggle_toolbars_display(
&mut self,
sender: ComponentSender<Self>,
) -> ToolUpdateResult {
sender
.output_sender()
.emit(SketchBoardOutput::ToggleToolbarsDisplay);
ToolUpdateResult::Unmodified
}
fn handle_toolbar_event(&mut self, toolbar_event: ToolbarEvent) -> ToolUpdateResult {
match toolbar_event {
ToolbarEvent::ToolSelected(tool) => {
// deactivate old tool and save drawable, if any
let mut deactivate_result = self
.active_tool
.borrow_mut()
.handle_event(ToolEvent::Deactivated);
if let ToolUpdateResult::Commit(d) = deactivate_result {
self.renderer.commit(d);
// we handle commit directly and "downgrade" to a simple redraw result
deactivate_result = ToolUpdateResult::Redraw;
}
// change active tool
self.active_tool = self.tools.get(&tool);
self.renderer.set_active_tool(self.active_tool.clone());
// send style event
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::StyleChanged(self.style));
// send activated event
let activate_result = self
.active_tool
.borrow_mut()
.handle_event(ToolEvent::Activated);
match activate_result {
ToolUpdateResult::Unmodified => deactivate_result,
_ => activate_result,
}
}
ToolbarEvent::ColorSelected(color) => {
self.style.color = color;
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::StyleChanged(self.style))
}
ToolbarEvent::SizeSelected(size) => {
self.style.size = size;
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::StyleChanged(self.style))
}
ToolbarEvent::SaveFile => {
self.renderer.request_render(Action::SaveToFile);
ToolUpdateResult::Unmodified
}
ToolbarEvent::CopyClipboard => {
self.renderer.request_render(Action::SaveToClipboard);
ToolUpdateResult::Unmodified
}
ToolbarEvent::Undo => self.handle_undo(),
ToolbarEvent::Redo => self.handle_redo(),
ToolbarEvent::ToggleFill => {
self.style.fill = !self.style.fill;
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::StyleChanged(self.style))
}
}
}
}
#[relm4::component(pub)]
impl Component for SketchBoard {
type CommandOutput = ();
type Input = SketchBoardInput;
type Output = SketchBoardOutput;
type Init = Pixbuf;
view! {
gtk::Box {
#[local_ref]
area -> FemtoVGArea {
set_vexpand: true,
set_hexpand: true,
grab_focus: (),
add_controller = gtk::GestureDrag {
set_button: 0,
connect_drag_begin[sender] => move |controller, x, y| {
sender.input(SketchBoardInput::new_mouse_event(
MouseEventType::BeginDrag,
controller.current_button(),
controller.current_event_state(),
Vec2D::new(x as f32, y as f32)));
},
connect_drag_update[sender] => move |controller, x, y| {
sender.input(SketchBoardInput::new_mouse_event(
MouseEventType::UpdateDrag,
controller.current_button(),
controller.current_event_state(),
Vec2D::new(x as f32, y as f32)));
},
connect_drag_end[sender] => move |controller, x, y| {
sender.input(SketchBoardInput::new_mouse_event(
MouseEventType::EndDrag,
controller.current_button(),
controller.current_event_state(),
Vec2D::new(x as f32, y as f32)
));
}
},
add_controller = gtk::GestureClick {
set_button: 0,
connect_pressed[sender] => move |controller, _, x, y| {
sender.input(SketchBoardInput::new_mouse_event(
MouseEventType::Click,
controller.current_button(),
controller.current_event_state(),
Vec2D::new(x as f32, y as f32)));
}
},
}
},
}
fn update(&mut self, msg: SketchBoardInput, sender: ComponentSender<Self>, _root: &Self::Root) {
// handle resize ourselves, pass everything else to tool
let result = match msg {
SketchBoardInput::InputEvent(mut ie) => {
if let InputEvent::Key(ke) = ie {
if ke.is_one_of(Key::z, KeyMappingId::UsZ)
&& ke.modifier == ModifierType::CONTROL_MASK
{
self.handle_undo()
} else if ke.is_one_of(Key::y, KeyMappingId::UsY)
&& ke.modifier == ModifierType::CONTROL_MASK
{
self.handle_redo()
} else if ke.is_one_of(Key::t, KeyMappingId::UsT)
&& ke.modifier == ModifierType::CONTROL_MASK
{
self.handle_toggle_toolbars_display(sender)
} else if ke.is_one_of(Key::s, KeyMappingId::UsS)
&& ke.modifier == ModifierType::CONTROL_MASK
{
self.renderer.request_render(Action::SaveToFile);
ToolUpdateResult::Unmodified
} else if ke.is_one_of(Key::c, KeyMappingId::UsC)
&& ke.modifier == ModifierType::CONTROL_MASK
{
self.renderer.request_render(Action::SaveToClipboard);
ToolUpdateResult::Unmodified
} else if ke.key == Key::Escape {
relm4::main_application().quit();
// this is only here to make rust happy. The application should exit with the previous call
ToolUpdateResult::Unmodified
} else if ke.key == Key::Return || ke.key == Key::KP_Enter {
// First, let the tool handle the event. If the tool does nothing, we can do our thing (otherwise require a second Enter)
// Relying on ToolUpdateResult::Unmodified is probably not a good idea, but it's the only way at the moment. See discussion in #144
let result: ToolUpdateResult = self
.active_tool
.borrow_mut()
.handle_event(ToolEvent::Input(ie));
if let ToolUpdateResult::Unmodified = result {
self.renderer
.request_render(APP_CONFIG.read().action_on_enter());
}
result
} else {
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::Input(ie))
}
} else {
ie.remap_event_coordinates(&self.renderer);
self.active_tool
.borrow_mut()
.handle_event(ToolEvent::Input(ie))
}
}
SketchBoardInput::ToolbarEvent(toolbar_event) => {
self.handle_toolbar_event(toolbar_event)
}
SketchBoardInput::RenderResult(img, action) => {
self.handle_render_result(img, action);
ToolUpdateResult::Unmodified
}
};
//println!("Event={:?} Result={:?}", msg, result);
match result {
ToolUpdateResult::Commit(drawable) => {
self.renderer.commit(drawable);
self.refresh_screen();
}
ToolUpdateResult::Unmodified => (),
ToolUpdateResult::Redraw => self.refresh_screen(),
};
}
fn init(
image: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let config = APP_CONFIG.read();
let tools = ToolsManager::new();
let mut model = Self {
renderer: FemtoVGArea::default(),
active_tool: tools.get(&config.initial_tool()),
style: Style::default(),
tools,
};
let area = &mut model.renderer;
area.init(
sender.input_sender().clone(),
model.tools.get_crop_tool(),
model.active_tool.clone(),
image,
);
let widgets = view_output!();
ComponentParts { model, widgets }
}
}
impl KeyEventMsg {
pub fn new(key: Key, code: u32, modifier: ModifierType) -> Self {
Self {
key,
code,
modifier,
}
}
/// Matches one of providen keys. The modifier is not considered.
/// And the key has more priority over keycode.
fn is_one_of(&self, key: Key, code: KeyMappingId) -> bool {
// INFO: on linux the keycode from gtk4 is evdev keycode, so need to match by him if need
// to use layout-independent shortcuts. And notice that there is substraction by 8, it's
// because of x11 compatibility in which the keycodes are in range [8,255]. So need shift
// them to get correct evdev keycode.
let keymap = KeyMap::from(code);
self.key == key || self.code as u16 - 8 == keymap.evdev
}
}