use gtk::{ Application, ApplicationWindow, Button, GtkWindowExt, WidgetExt, ContainerExt, ButtonExt, BoxExt, }; use gio::prelude::{ ApplicationExt, ApplicationExtManual, }; use std::rc::Rc; use std::cell::RefCell; struct Legend { symbol: char, color: (f64, f64, f64), } impl Legend { fn draw_to_file(&self) { let f = std::fs::File::create("samp.svg").unwrap(); let surf = cairo::SvgSurface::for_stream( 100.0, 100.0, f, ).unwrap(); self.render(&cairo::Context::new(&surf)); surf.finish_output_stream().unwrap(); } fn render(&self, ctx: &cairo::Context) -> () { ctx.set_source_rgb(self.color.0, self.color.1, self.color.2); ctx.paint(); ctx.set_source_rgb(0., 0., 0.); ctx.move_to(0.0, -23.0); let layout = pangocairo::functions::create_layout(&ctx).unwrap(); layout.set_width(100 * 1024); layout.set_alignment(pango::Alignment::Center); let font = pango::FontDescription::from_string("Fira Sans 92"); layout.set_font_description(Some(&font)); layout.set_text(&self.symbol.to_string()); pangocairo::functions::show_layout(&ctx, &layout); } } struct AppData { legend: Legend, } #[derive(Clone)] struct App { data: Rc>, } impl App { fn new() -> App { let legend = Legend { symbol: 'X', color: (0.5, 0.5, 0.5), }; let data = Rc::new(RefCell::new(AppData { legend })); App { data } } } fn mk_app(app: >k::Application) { let window = ApplicationWindow::new(app); let app = App::new(); window.set_title("I Am Legend"); let container = gtk::Box::new(gtk::Orientation::Vertical, 4); container.pack_start(&mk_icon_choice('A', app.clone()), false, true, 0); container.pack_start(&mk_icon_choice('B', app.clone()), false, true, 0); container.pack_start(&mk_icon_choice('C', app.clone()), false, true, 0); container.pack_start(&mk_icon_choice('D', app.clone()), false, true, 0); let flow = gtk::Box::new(gtk::Orientation::Horizontal, 2); flow.pack_start(&container, false, true, 0); let button = Button::with_label("Click me!"); flow.pack_start(&button, false, true, 0); let canvas = gtk::DrawingArea::new(); let copy = app.clone(); canvas.connect_draw(move |cv, ctx| { copy.data.borrow_mut().legend.render(ctx); gtk::Inhibit(false) }); flow.pack_start(&canvas, true, true, 0); button.connect_clicked(move |_| { app.data.borrow_mut().legend.draw_to_file(); }); window.add(&flow); window.show_all(); } fn mk_icon_choice(choice: char, cell: App) -> gtk::Button { let button = gtk::Button::with_label(&choice.to_string()); button.connect_clicked(move |_| { cell.data.borrow_mut().legend.symbol = choice; println!("Choosing '{}'", choice); }); button } fn main() { let application = Application::new( Some("com.github.gtk-rs.examples.basic"), Default::default(), ).expect("failed to initialize GTK application"); application.connect_activate(|app| { mk_app(app); }); application.run(&[]); }