mod actions; mod constants; mod dialogs; mod file_registry; mod handlers; 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"); /// 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) { let application = relm4::main_application(); let mut action_group = RelmActionGroup::::new(); register_action!( action_group, application, sender, ZoomInAction, Action::ZoomIn, &["equal", "plus"] ); register_action!( action_group, application, sender, ZoomOutAction, Action::ZoomOut, &["minus"] ); register_action!( action_group, application, sender, ChangeOrientationAction, Action::ChangeOrientation, &["l"] ); register_action!( action_group, application, sender, ExportImageAction, Action::ExportImage, &["e"] ); register_action!( action_group, application, sender, NewAction, Action::New, &["n"] ); register_action!( action_group, application, sender, SaveAction, Action::Save { close_after: false }, &["s"] ); register_action!( action_group, application, sender, SaveAsAction, Action::SaveAs { close_after: false }, &["s"] ); register_action!( action_group, application, sender, OpenAction, Action::Open, &["o"] ); register_action!( action_group, application, sender, CloseAction, Action::CloseWindow, &["w"] ); action_group.register_for_widget(&window); } struct AppInit { zoom: f64, file_path: Option, } struct AppModel { orientation: gtk::Orientation, stage_type_list: gtk::StringList, stage_type: StageType, source: sourceview5::Buffer, map: Map, zoom: f64, render_configuration: Configuration, surface: ImageSurface, surface_width: i32, surface_height: i32, drawing_area: gtk::DrawingArea, current_file: Option, modified: bool, pending_load_events: RefCell, initialized: bool, window: gtk::Window, } 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); } pub fn open_new_window(file_path: Option) { 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::: &(), } }, 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::: &(), }, 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 { sourceview5::View { set_expand: true, set_monospace: 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::: &(), }, 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::: &(), }, } } } } } 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, }, } } fn init( init: Self::Init, root: Self::Root, sender: ComponentSender, ) -> ComponentParts { 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()); 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); } let mut model = AppModel { orientation: gtk::Orientation::Horizontal, stage_type_list, stage_type, source, 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(), }; model.update_image(); { 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) { 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 (not yet implemented) Action::ExportImage => { // TODO: Implement image export functionality // - Show save dialog with PNG/SVG format picker // - Default filename: current file name with .png or .svg extension // - Call renderer's render_to_png() or render_to_svg() based on selection } // 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, } } } fn main() { relm4_icons::initialize_icons(icon_names::GRESOURCE_BYTES, icon_names::RESOURCE_PREFIX); let application = RelmApp::new(constants::APP_ID); application.run::(AppInit { zoom: 1.0, file_path: None, }); }