]> git.tdb.fi Git - r2c2.git/blob - engineer/newvehicledialog.cpp
Don't crash if a train has no router
[r2c2.git] / engineer / newvehicledialog.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/gltk/button.h>
3 #include <msp/gltk/toggle.h>
4 #include <msp/strings/format.h>
5 #include "libr2c2/catalogue.h"
6 #include "libr2c2/layout.h"
7 #include "newvehicledialog.h"
8
9 using namespace std;
10 using namespace Msp;
11 using namespace R2C2;
12
13 static string vehicle_type_name(const VehicleType *const &vehtype)
14 {
15         return format("%s %s", vehtype->get_article_number(), vehtype->get_name());
16 }
17
18 NewVehicleDialog::NewVehicleDialog(Train &t):
19         train(t),
20         loco_types(&vehicle_type_name),
21         wagon_types(&vehicle_type_name)
22 {
23         Loader::WidgetMap widgets;
24         DataFile::load(*this, "data/newvehicledialog.ui", widgets);
25
26         dynamic_cast<GLtk::Label *>(get_item(widgets, "lbl_title"))->set_text(format("Add vehicle to %s", train.get_name()));
27
28         GLtk::List *lst_loco_types = dynamic_cast<GLtk::List *>(get_item(widgets, "lst_loco_types"));
29         lst_loco_types->set_data(loco_types);
30         active_list = lst_loco_types;
31
32         GLtk::List *lst_wagon_types = dynamic_cast<GLtk::List *>(get_item(widgets, "lst_wagon_types"));
33         lst_wagon_types->set_data(wagon_types);
34
35         dynamic_cast<GLtk::Toggle *>(get_item(widgets, "tgl_loco_types"))->signal_toggled.connect(sigc::bind(sigc::mem_fun(this, &NewVehicleDialog::toggle_list), lst_loco_types));
36         dynamic_cast<GLtk::Toggle *>(get_item(widgets, "tgl_wagon_types"))->signal_toggled.connect(sigc::bind(sigc::mem_fun(this, &NewVehicleDialog::toggle_list), lst_wagon_types));
37
38         dynamic_cast<GLtk::Button *>(get_item(widgets, "btn_add"))->signal_clicked.connect(sigc::mem_fun(this, &NewVehicleDialog::add_clicked));
39
40         const Catalogue::ObjectMap &obj_types = train.get_layout().get_catalogue().get_all();
41         for(Catalogue::ObjectMap::const_iterator i=obj_types.begin(); i!=obj_types.end(); ++i)
42                 if(const VehicleType *vt = dynamic_cast<const VehicleType *>(i->second))
43                 {
44                         if(vt->is_locomotive())
45                                 loco_types.append(vt);
46                         else
47                                 wagon_types.append(vt);
48                 }
49 }
50
51 void NewVehicleDialog::toggle_list(bool show, GLtk::List *lst)
52 {
53         lst->set_visible(show);
54         if(show)
55                 active_list = lst;
56 }
57
58 void NewVehicleDialog::add_clicked()
59 {
60         int index = active_list->get_selected_index();
61         if(index>=0)
62         {
63                 const VehicleType *vtype = static_cast<GLtk::ListDataStore<const R2C2::VehicleType *> &>(active_list->get_data()).get(index);
64                 train.add_vehicle(*vtype);
65         }
66 }