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
|
// Suppress warnings from relm4 view! macro internals
#![allow(unused_assignments)]
mod actions;
mod constants;
mod dialogs;
mod file_registry;
mod handlers;
mod preferences;
mod stages;
mod icon_names {
include!(concat!(env!("OUT_DIR"), "/icon_names.rs"));
}
use std::cell::RefCell;
use std::path::PathBuf;
use crate::actions::Action;
use crate::icon_names::shipped::{
IMAGE_REGULAR, MENU_LARGE, SPLIT_HORIZONTAL_REGULAR, SPLIT_VERTICAL_REGULAR, ZOOM_IN_REGULAR,
ZOOM_OUT_REGULAR,
};
use cairo::ImageSurface;
use gtk::glib;
use gtk::prelude::*;
use relm4::{
Component, ComponentController, ComponentParts, ComponentSender, RelmApp, RelmWidgetExt,
SimpleComponent,
actions::{AccelsPlus, ActionablePlus, RelmAction, RelmActionGroup},
gtk,
};
use sourceview5::LanguageManager;
use sourceview5::prelude::{BufferExt, TextBufferExt, TextViewExt};
use stages::ALL_STAGE_TYPES;
use wmap_parser::{Map, parse};
use wmap_renderer::{Configuration, StageType, render_to_surface};
// Action group and action type declarations
relm4::new_action_group!(WindowActionGroup, "window");
relm4::new_stateless_action!(NewAction, WindowActionGroup, "new");
relm4::new_stateless_action!(OpenAction, WindowActionGroup, "open");
relm4::new_stateless_action!(SaveAction, WindowActionGroup, "save");
relm4::new_stateless_action!(SaveAsAction, WindowActionGroup, "save-as");
relm4::new_stateless_action!(CloseAction, WindowActionGroup, "close");
relm4::new_stateless_action!(ExportImageAction, WindowActionGroup, "export-image");
relm4::new_stateless_action!(
ChangeOrientationAction,
WindowActionGroup,
"change-orientation"
);
relm4::new_stateless_action!(ZoomInAction, WindowActionGroup, "zoom-in");
relm4::new_stateless_action!(ZoomOutAction, WindowActionGroup, "zoom-out");
relm4::new_stateless_action!(PreferencesAction, WindowActionGroup, "preferences");
/// Macro to reduce boilerplate when registering actions with accelerators.
macro_rules! register_action {
($group:expr, $app:expr, $sender:expr, $action_type:ty, $message:expr, $accelerators:expr) => {{
let sender = $sender.clone();
let action: RelmAction<$action_type> = RelmAction::new_stateless(move |_| {
sender.input($message);
});
$group.add_action(action);
$app.set_accelerators_for_action::<$action_type>($accelerators);
}};
}
fn setup_actions(window: gtk::Window, sender: ComponentSender<AppModel>) {
let application = relm4::main_application();
let mut action_group = RelmActionGroup::<WindowActionGroup>::new();
register_action!(
action_group,
application,
sender,
ZoomInAction,
Action::ZoomIn,
&["<Primary>equal", "<Primary>plus"]
);
register_action!(
action_group,
application,
sender,
ZoomOutAction,
Action::ZoomOut,
&["<Primary>minus"]
);
register_action!(
action_group,
application,
sender,
ChangeOrientationAction,
Action::ChangeOrientation,
&["<Primary>l"]
);
register_action!(
action_group,
application,
sender,
ExportImageAction,
Action::ExportImage,
&["<Primary>e"]
);
register_action!(
action_group,
application,
sender,
NewAction,
Action::New,
&["<Primary>n"]
);
register_action!(
action_group,
application,
sender,
SaveAction,
Action::Save { close_after: false },
&["<Primary>s"]
);
register_action!(
action_group,
application,
sender,
SaveAsAction,
Action::SaveAs { close_after: false },
&["<Primary><Shift>s"]
);
register_action!(
action_group,
application,
sender,
OpenAction,
Action::Open,
&["<Primary>o"]
);
register_action!(
action_group,
application,
sender,
CloseAction,
Action::CloseWindow,
&["<Primary>w"]
);
register_action!(
action_group,
application,
sender,
PreferencesAction,
Action::ShowPreferences,
&["<Primary>comma"]
);
action_group.register_for_widget(&window);
}
struct AppInit {
zoom: f64,
file_path: Option<PathBuf>,
}
struct AppModel {
orientation: gtk::Orientation,
stage_type_list: gtk::StringList,
available_stage_types: Vec<StageType>,
stage_type: StageType,
source: sourceview5::Buffer,
source_view: sourceview5::View,
map: Map,
zoom: f64,
render_configuration: Configuration,
surface: ImageSurface,
surface_width: i32,
surface_height: i32,
drawing_area: gtk::DrawingArea,
current_file: Option<PathBuf>,
modified: bool,
pending_load_events: RefCell<u32>,
initialized: bool,
window: gtk::Window,
preferences: preferences::UserPreferences,
preferences_window: Option<relm4::Controller<preferences::PreferencesWindow>>,
editor_css_provider: gtk::CssProvider,
}
impl AppModel {
fn update_image(&mut self) {
if let Ok(surface) =
render_to_surface(&self.map, &self.stage_type, &self.render_configuration)
{
self.surface_width = (surface.width() as f64 * self.zoom).round() as i32;
self.surface_height = (surface.height() as f64 * self.zoom).round() as i32;
self.surface = surface;
let zoom = self.zoom;
let surface_clone = self.surface.clone();
self.drawing_area
.set_draw_func(move |_, cr, _width, _height| {
cr.scale(zoom, zoom);
cr.set_source_surface(&surface_clone, 0.0, 0.0).ok();
cr.paint().ok();
});
self.drawing_area.set_content_width(self.surface_width);
self.drawing_area.set_content_height(self.surface_height);
self.drawing_area.queue_draw();
}
}
fn window_title(&self) -> String {
let filename = self
.current_file
.as_ref()
.and_then(|path| path.file_name())
.and_then(|name| name.to_str())
.unwrap_or("Untitled");
if self.modified {
format!("{}* - {}", filename, constants::APP_NAME)
} else {
format!("{} - {}", filename, constants::APP_NAME)
}
}
fn is_empty_document(&self) -> bool {
self.current_file.is_none() && !self.modified && self.source_text().is_empty()
}
fn source_text(&self) -> glib::GString {
self.source
.text(&self.source.start_iter(), &self.source.end_iter(), false)
}
fn set_source_text(&self, content: &str) {
*self.pending_load_events.borrow_mut() += 1;
self.source.set_text(content);
}
fn apply_preferences(&mut self) {
// Apply editor preferences
self.source_view
.set_wrap_mode(if self.preferences.soft_wrap_lines {
gtk::WrapMode::Word
} else {
gtk::WrapMode::None
});
// Build CSS for editor font
let css = if self.preferences.use_custom_editor_font {
self.source_view.set_monospace(false);
format!(
"textview {{ font-family: \"{}\"; font-size: {}pt; }}",
self.preferences.custom_editor_font_name, self.preferences.editor_font_size as i32
)
} else {
// Use monospace but still apply font size
self.source_view.set_monospace(true);
format!(
"textview {{ font-size: {}pt; }}",
self.preferences.editor_font_size as i32
)
};
// Update the CSS provider (reusing the same one avoids accumulation)
self.editor_css_provider.load_from_data(&css);
// Apply render configuration
self.render_configuration.options.smart_label_positioning =
self.preferences.use_smart_label_positioning;
self.render_configuration.options.show_background = self.preferences.show_map_background;
// Apply map font
if self.preferences.use_custom_font {
self.render_configuration.theme.fonts.face = self.preferences.custom_font_name.clone();
} else {
// Reset to default font
self.render_configuration.theme.fonts.face = String::from("sans-serif");
}
}
fn rebuild_stage_type_list(&mut self) {
// Build list: built-in stage types + custom stages from preferences
let mut stage_types: Vec<StageType> = ALL_STAGE_TYPES.to_vec();
// Add custom stages from preferences
for custom in &self.preferences.custom_stages {
stage_types.push(StageType::Custom {
name: custom.name.clone(),
i: custom.stage.i.clone(),
ii: custom.stage.ii.clone(),
iii: custom.stage.iii.clone(),
iv: custom.stage.iv.clone(),
});
}
// Update the StringList for the dropdown
// Clear existing items
while self.stage_type_list.n_items() > 0 {
self.stage_type_list.remove(0);
}
// Add all stage type names
for stage_type in &stage_types {
self.stage_type_list.append(stage_type.name());
}
self.available_stage_types = stage_types;
}
pub fn open_new_window(file_path: Option<PathBuf>) {
let controller = AppModel::builder()
.launch(AppInit {
zoom: 1.0,
file_path,
})
.detach();
let application = relm4::main_application();
let window = controller.widget();
application.add_window(window);
window.present();
file_registry::store_controller(controller);
}
}
#[relm4::component]
impl SimpleComponent for AppModel {
type Input = Action;
type Output = ();
type Init = AppInit;
view! {
#[root]
gtk::Window {
#[watch]
set_title: Some(&model.window_title()),
set_default_width: constants::DEFAULT_WINDOW_WIDTH,
set_default_height: constants::DEFAULT_WINDOW_HEIGHT,
gtk::Box {
set_orientation: gtk::Orientation::Vertical,
set_spacing: 0,
gtk::HeaderBar {
pack_start = >k::Box {
set_orientation: gtk::Orientation::Horizontal,
gtk::Button::with_label("Change Orientation") {
#[watch]
set_icon_name: match model.orientation {
gtk::Orientation::Horizontal => SPLIT_VERTICAL_REGULAR,
_ => SPLIT_HORIZONTAL_REGULAR
},
ActionablePlus::set_stateless_action::<ChangeOrientationAction>: &(),
}
},
pack_end = >k::Box {
set_orientation: gtk::Orientation::Horizontal,
gtk::Button::with_label("Export as Image") {
set_icon_name: IMAGE_REGULAR,
ActionablePlus::set_stateless_action::<ExportImageAction>: &(),
},
gtk::DropDown {
set_model: Some(&model.stage_type_list),
set_show_arrow: true,
set_selected: 0,
connect_selected_notify[sender] => move |dropdown| {
let selected = dropdown.selected();
sender.input(Action::StageTypeSelected(selected as usize));
},
},
gtk::MenuButton {
set_icon_name: MENU_LARGE,
#[wrap(Some)]
set_popover = >k::PopoverMenu::from_model(Some(&main_menu)) {}
}
}
},
gtk::Paned {
#[watch]
set_orientation: model.orientation,
set_expand: true,
#[wrap(Some)]
set_start_child = >k::ScrolledWindow {
#[local_ref]
source_view -> sourceview5::View {
set_expand: true,
set_buffer: Some(&model.source)
}
},
#[wrap(Some)]
set_end_child = >k::ScrolledWindow {
#[local_ref]
drawing_area -> gtk::DrawingArea {
#[watch]
set_content_width: model.surface_width,
#[watch]
set_content_height: model.surface_height
}
}
},
gtk::ActionBar {
pack_end = >k::Box {
set_orientation: gtk::Orientation::Horizontal,
gtk::Label {
#[watch]
set_label: &format!("{:.1}x", model.zoom),
set_margin_end: 5
},
gtk::Button::with_label("Zoom Out") {
set_icon_name: ZOOM_OUT_REGULAR,
set_margin_end: 5,
add_css_class: "flat",
add_css_class: "zoom",
add_css_class: "zoom-out",
ActionablePlus::set_stateless_action::<ZoomOutAction>: &(),
},
gtk::Scale {
set_orientation: gtk::Orientation::Horizontal,
#[watch]
set_value: model.zoom,
set_draw_value: false,
set_range: (constants::MIN_ZOOM, constants::MAX_ZOOM),
set_increments: (constants::ZOOM_STEP, constants::ZOOM_STEP),
set_value_pos: gtk::PositionType::Left,
set_width_request: 100,
connect_value_changed[sender] => move |scale| {
sender.input(Action::Zoom(scale.value()));
}
},
gtk::Button::with_label("Zoom In") {
set_icon_name: ZOOM_IN_REGULAR,
add_css_class: "flat",
add_css_class: "zoom",
add_css_class: "zoom-in",
ActionablePlus::set_stateless_action::<ZoomInAction>: &(),
},
}
}
}
}
}
menu! {
main_menu: {
"New Map" => NewAction,
"Open..." => OpenAction,
"Save" => SaveAction,
"Save As..." => SaveAsAction,
"Close" => CloseAction,
"Export Map as Image" => ExportImageAction,
section!{
match model.orientation {
gtk::Orientation::Horizontal => "Use Vertical Layout",
_ => "Use Horizontal Layout"
} => ChangeOrientationAction,
},
section! {
"Zoom In" => ZoomInAction,
"Zoom Out" => ZoomOutAction,
},
section! {
"Preferences" => PreferencesAction,
},
}
}
fn init(
init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let stage_types: Vec<&str> = ALL_STAGE_TYPES
.iter()
.map(|stage_type| stage_type.name())
.collect();
let stage_type_list = gtk::StringList::new(&stage_types);
let source = sourceview5::Buffer::new(None);
source.set_highlight_syntax(true);
let language_manager = LanguageManager::default();
if let Some(language) = language_manager.language("wmap") {
source.set_language(Some(&language));
}
let (initial_content, current_file) = if let Some(ref path) = init.file_path {
match std::fs::read_to_string(path) {
Ok(content) => (content, Some(path.clone())),
Err(_) => (String::new(), None),
}
} else {
(String::new(), None)
};
source.set_text(&initial_content);
{
let sender = sender.clone();
source.connect_changed(move |_| {
sender.input(Action::SourceChanged);
});
}
setup_actions(root.clone(), sender.clone());
// Create source view
let source_view = sourceview5::View::with_buffer(&source);
source_view.set_monospace(true);
// Create CSS provider for editor font styling
let editor_css_provider = gtk::CssProvider::new();
source_view.style_context().add_provider(
&editor_css_provider,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
let drawing_area = gtk::DrawingArea::new();
let map = parse(&initial_content);
let mut render_configuration = Configuration::default();
let stage_type = StageType::Activities;
render_configuration.options.smart_label_positioning = true;
let surface =
render_to_surface(&map, &stage_type, &render_configuration).unwrap_or_else(|_| {
ImageSurface::create(cairo::Format::ARgb32, 1, 1)
.expect("Failed to create fallback surface")
});
if let Some(ref path) = current_file {
file_registry::register_file(path, &root);
}
// Load preferences
let prefs = preferences::storage::load();
let mut model = AppModel {
orientation: gtk::Orientation::Horizontal,
stage_type_list,
available_stage_types: ALL_STAGE_TYPES.to_vec(),
stage_type,
source,
source_view: source_view.clone(),
map,
zoom: init.zoom,
render_configuration,
surface,
surface_width: 0,
surface_height: 0,
drawing_area: drawing_area.clone(),
current_file,
modified: false,
pending_load_events: RefCell::new(0),
initialized: false,
window: root.clone(),
preferences: prefs,
preferences_window: None,
editor_css_provider,
};
// Apply preferences and rebuild stage type list
model.apply_preferences();
model.rebuild_stage_type_list();
model.update_image();
// Register this window's sender for broadcasting
file_registry::register_sender(sender.input_sender().clone());
{
let sender = sender.clone();
glib::idle_add_local_once(move || {
sender.input(Action::MarkInitialized);
});
}
{
let sender = sender.clone();
root.connect_close_request(move |_| {
sender.input(Action::CloseWindow);
glib::Propagation::Stop
});
}
let widgets = view_output!();
ComponentParts { model, widgets }
}
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>) {
match message {
// View actions
Action::ChangeOrientation => handlers::view::change_orientation(self),
Action::StageTypeSelected(index) => handlers::view::stage_type_selected(self, index),
// Source changes
Action::SourceChanged => {
let pending = *self.pending_load_events.borrow();
if pending > 0 {
*self.pending_load_events.borrow_mut() -= 1;
} else if self.initialized {
self.modified = true;
}
self.map = parse(&self.source_text());
self.update_image();
}
// Zoom actions
Action::Zoom(level) => handlers::zoom::zoom(self, level),
Action::ZoomIn => handlers::zoom::zoom_in(self),
Action::ZoomOut => handlers::zoom::zoom_out(self),
// Export
Action::ExportImage => {
dialogs::show_export_dialog(&self.window, self.current_file.clone(), sender)
}
Action::ExportToFile { path, format } => {
handlers::export::export_to_file(self, path, format)
}
// File actions
Action::New => Self::open_new_window(None),
Action::Open => {
dialogs::show_open_dialog(&self.window, self.is_empty_document(), sender)
}
Action::Save { close_after } => handlers::file::save(self, close_after, &sender),
Action::SaveAs { close_after } => dialogs::show_save_dialog(
&self.window,
self.current_file.clone(),
close_after,
sender,
),
Action::LoadFile(path) => handlers::file::load_file(self, path),
Action::SaveToFile { path, close_after } => {
handlers::file::save_to_file(self, path, close_after)
}
Action::CloseWindow => handlers::file::close_window(self, &sender),
// Internal actions
Action::MarkInitialized => self.initialized = true,
// Preferences
Action::ShowPreferences => {
if self.preferences_window.is_none() {
let controller = preferences::PreferencesWindow::builder()
.transient_for(&self.window)
.launch(self.preferences.clone())
.forward(sender.input_sender(), |output| match output {
preferences::window::PreferencesOutput::PreferencesChanged(prefs) => {
Action::PreferencesChanged(prefs)
}
preferences::window::PreferencesOutput::Closed => {
Action::PreferencesWindowClosed
}
});
self.preferences_window = Some(controller);
}
if let Some(ref controller) = self.preferences_window {
controller.widget().present();
}
}
Action::PreferencesChanged(prefs) => {
self.preferences = prefs;
self.apply_preferences();
self.rebuild_stage_type_list();
self.update_image();
// Broadcast to all other windows to reload preferences
file_registry::broadcast_to_all_windows(Action::ReloadPreferences);
}
Action::PreferencesWindowClosed => {
self.preferences_window = None;
}
Action::ReloadPreferences => {
// Reload preferences from disk (another window changed them)
self.preferences = preferences::storage::load();
self.apply_preferences();
self.rebuild_stage_type_list();
self.update_image();
}
}
}
}
fn main() {
relm4_icons::initialize_icons(icon_names::GRESOURCE_BYTES, icon_names::RESOURCE_PREFIX);
let application = RelmApp::new(constants::APP_ID);
application.run::<AppModel>(AppInit {
zoom: 1.0,
file_path: None,
});
}
|