MapApp.cpp 10 KB
Newer Older
Martin Kröning's avatar
Martin Kröning committed
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
#include "MapApp.hpp"
#include "glibmm/main.h"
#include "glibmm/priorities.h"
#include "glibmm/signalproxy.h"
#include "glibmm/ustring.h"
#include "gtkmm/application.h"
#include "gtkmm/listboxrow.h"
#include "gtkmm/object.h"
#include "gtkmm/widget.h"
#include "gtkmm/window.h"
#include "sigc++/functors/mem_fun.h"
#include <algorithm>
#include <cmath>
#include <gtkmm/box.h>
#include <gtkmm/builder.h>
#include <gtkmm/comboboxtext.h>
#include <gtkmm/entry.h>
#include <gtkmm/label.h>
#include <gtkmm/listbox.h>
#include <gtkmm/viewport.h>
#include <iomanip>
#include <iostream>
#include <utility>

// Use Glib::PRIORITY_HIGH_IDLE + 10 for resizing operations
// and Glib::PRIORITY_HIGH_IDLE + 20 for redrawing operations
// https://developer.gnome.org/glibmm/2.55/namespaceGlib.html#a0c450f82b9e34689e2dda2038ba7834faf2d20696a8afab425c00268d981e9897

const std::vector<std::string> MapApp::zoomLevels = {"60%", "80%", "100%"};
30 31
Glib::RefPtr<Gtk::Application> MapApp::app = Gtk::Application::create();
std::thread MapApp::thread;
Martin Kröning's avatar
Martin Kröning committed
32

33
MapApp::MapApp(std::string windowTitle)
34
    : mapArea(junctions, roads, nameVehicleMap), listBox(nullptr),
35
      timeLabel(nullptr), laneLabel(nullptr),
Martin Kröning's avatar
Martin Kröning committed
36 37
      lanePositionPercentageLabel(nullptr), speedLabel(nullptr),
      remainingFuelLabel(nullptr), zoomComboBoxText(nullptr) {
38
  win.set_title(std::move(windowTitle));
Martin Kröning's avatar
Martin Kröning committed
39 40 41 42 43 44 45 46 47 48 49

  auto builder =
      Gtk::Builder::create_from_resource("/pi2-view/pi2-view.glade", "box");
  Gtk::Box *box;
  builder->get_widget("box", box);

  Gtk::Viewport *viewport;
  builder->get_widget("viewport", viewport);

  builder->get_widget("listBox", listBox);

50
  builder->get_widget("timeLabel", timeLabel);
Martin Kröning's avatar
Martin Kröning committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  builder->get_widget("laneLabel", laneLabel);
  builder->get_widget("lanePositionPercentageLabel",
                      lanePositionPercentageLabel);
  builder->get_widget("speedLabel", speedLabel);
  builder->get_widget("remainingFuelLabel", remainingFuelLabel);

  builder->get_widget("zoomComboBoxText", zoomComboBoxText);
  for (auto &&zoomLevel : zoomLevels) {
    zoomComboBoxText->append(zoomLevel);
  }
  zoomComboBoxText->set_active_text("100%");
  zoomComboBoxText->signal_changed().connect(
      sigc::mem_fun(*this, &MapApp::onZoomSelectionChanged));
  zoomComboBoxText->get_entry()->signal_activate().connect(
      sigc::mem_fun(*this, &MapApp::onZoomEntryActivate));

  listBox->signal_row_selected().connect(
      sigc::mem_fun(*this, &MapApp::onVehicleRowSelected));

  win.add(*box);
  viewport->add(mapArea);
  mapArea.show();

74 75 76 77 78 79 80 81 82
  if (app->get_windows().empty()) {
    thread = std::thread([this]() {
      app = Gtk::Application::create();
      app->run(win);
    });
  } else {
    app->add_window(win);
    win.show();
  }
Martin Kröning's avatar
Martin Kröning committed
83 84 85 86 87 88 89 90
}

void MapApp::onZoomEntryActivate() {
  std::string input = zoomComboBoxText->get_active_text();
  double zoom;
  std::istringstream zoomBuffer(input);
  zoomBuffer >> zoom;
  mapArea.setScale(zoom / 100);
91 92
  Glib::signal_idle().connect_once([this]() { mapArea.adaptSizeRequest(); },
                                   Glib::PRIORITY_HIGH_IDLE + 10);
Martin Kröning's avatar
Martin Kröning committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

  std::ostringstream formatBuffer;
  formatBuffer << zoom << '%';
  zoomComboBoxText->get_entry()->set_text(formatBuffer.str());
}

void MapApp::onZoomSelectionChanged() {
  std::string selection = zoomComboBoxText->get_active_text();
  auto levelResult = std::find(zoomLevels.begin(), zoomLevels.end(), selection);
  if (levelResult != zoomLevels.end()) {
    zoomComboBoxText->set_active_text(selection);
    double zoom;
    std::istringstream zoomBuffer(selection);
    zoomBuffer >> zoom;
    mapArea.setScale(zoom / 100);
108 109
    Glib::signal_idle().connect_once([this]() { mapArea.adaptSizeRequest(); },
                                     Glib::PRIORITY_HIGH_IDLE + 10);
Martin Kröning's avatar
Martin Kröning committed
110 111 112 113 114 115 116 117
  }
}

void MapApp::refreshArea(int x, int y, int width, int height) {
  mapArea.queue_draw_area(x, y, width, height);
}

MapApp::~MapApp() {
118 119
  app->remove_window(win);
  if (thread.joinable() && app->get_windows().empty()) {
Martin Kröning's avatar
Martin Kröning committed
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
    thread.join();
  }
}

void MapApp::onVehicleRowSelected(Gtk::ListBoxRow *row) {
  auto &label = dynamic_cast<Gtk::Label &>(*row->get_child());
  auto &vehicle = nameVehicleMap.at(label.get_text());
  refreshVehicleLabels(vehicle);
}

void MapApp::refreshVehicleLabels(const DrawableVehicle &vehicle) {
  laneLabel->set_text(vehicle.getLaneName());

  std::ostringstream lanePisitionPercentageBuffer;
  lanePisitionPercentageBuffer << std::setfill('0') << std::setw(2)
                               << std::round(vehicle.getPositionOnLane() * 100);
  lanePositionPercentageLabel->set_text(lanePisitionPercentageBuffer.str());

  std::ostringstream speedBuffer;
  speedBuffer << std::setprecision(3) << vehicle.getSpeed();
  speedLabel->set_text(speedBuffer.str());

  std::ostringstream remainingFuelBuffer;
  remainingFuelBuffer << std::showpoint << std::setprecision(3)
                      << vehicle.getRemainingFuel();
  remainingFuelLabel->set_text(remainingFuelBuffer.str());
}

148 149 150
void MapApp::setTimeLabel(const std::chrono::minutes minutes) {
  std::ostringstream timeBuffer;
  timeBuffer
Martin Kröning's avatar
Martin Kröning committed
151 152 153 154
      << std::setfill('0') << std::setw(2)
      << std::chrono::duration_cast<std::chrono::hours>(minutes).count() << ':'
      << std::setw(2) << minutes.count() % 60;
  Glib::signal_idle().connect_once(
155 156
      [this, timeString = timeBuffer.str()]() mutable {
        timeLabel->set_text(std::move(timeString));
Martin Kröning's avatar
Martin Kröning committed
157 158 159 160 161 162
      },
      Glib::PRIORITY_HIGH_IDLE + 20);
}

void MapApp::addJunction(const double x, const double y) {
  auto &junction = junctions.emplace_back(x, y);
163 164 165 166 167 168
  Glib::signal_idle().connect_once(
      [this]() {
        mapArea.adaptSizeRequest();
        resizeWindow();
      },
      Glib::PRIORITY_HIGH_IDLE + 10);
Martin Kröning's avatar
Martin Kröning committed
169 170 171 172 173 174 175 176 177 178 179 180
  int xRegion, yRegion, widthRegion, heightRegion;
  junction.getRegion(xRegion, yRegion, widthRegion, heightRegion);
  Glib::signal_idle().connect_once(
      [this, xRegion, yRegion, widthRegion, heightRegion]() {
        mapArea.queue_draw_area(xRegion, yRegion, widthRegion, heightRegion);
      },
      Glib::PRIORITY_HIGH_IDLE + 20);
}

void MapApp::addRoad(std::string laneThereName, std::string laneBackName,
                     std::vector<std::valarray<double>> coordinates) {
  auto &road = roads.emplace_back(laneThereName, laneBackName, coordinates);
181 182 183 184 185 186
  Glib::signal_idle().connect_once(
      [this]() {
        mapArea.adaptSizeRequest();
        resizeWindow();
      },
      Glib::PRIORITY_HIGH_IDLE + 10);
Martin Kröning's avatar
Martin Kröning committed
187 188 189 190 191 192 193 194 195
  int xRegion, yRegion, widthRegion, heightRegion;
  road.getRegion(xRegion, yRegion, widthRegion, heightRegion);
  Glib::signal_idle().connect_once(
      [this, xRegion, yRegion, widthRegion, heightRegion]() {
        mapArea.queue_draw_area(xRegion, yRegion, widthRegion, heightRegion);
      },
      Glib::PRIORITY_HIGH_IDLE + 20);
}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
void MapApp::addOrReplaceBicycle(const std::string &vehicleName,
                                 const std::string &laneName,
                                 const double positionOnLane,
                                 const double speed) {
  addOrReplaceVehicle(vehicleName, laneName, positionOnLane, speed, 0, 0, 1, 0);
}

void MapApp::addOrReplaceCar(const std::string &vehicleName,
                             const std::string &laneName,
                             const double positionOnLane, const double speed,
                             const double remainingFuel) {
  addOrReplaceVehicle(vehicleName, laneName, positionOnLane, speed,
                      remainingFuel, 1, 0, 0);
}

Martin Kröning's avatar
Martin Kröning committed
211 212
void MapApp::addOrReplaceVehicle(const std::string &vehicleName,
                                 const std::string &laneName,
213 214 215
                                 const double positionOnLane,
                                 const double speed, const double remainingFuel,
                                 double red, double green, double blue) {
Martin Kröning's avatar
Martin Kröning committed
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
  auto &road = *std::find_if(roads.begin(), roads.end(),
                             [&laneName](const DrawableRoad &road) {
                               return road.contains(laneName);
                             });
  auto selectedRow = listBox->get_selected_row();
  if (selectedRow != nullptr) {
    auto selectedVehicleName =
        dynamic_cast<Gtk::Label &>(*selectedRow->get_child()).get_text();
    if (selectedVehicleName == vehicleName) {
      red = green = blue = 1;
    }
  }

  auto search = nameVehicleMap.find(vehicleName);
  int oldX = 0;
  int oldY = 0;
  int oldWidth = 0;
  int oldHeight = 0;
  if (search != nameVehicleMap.end()) {
    auto &foundVehicle = (*search).second;
    foundVehicle.getRegion(oldX, oldY, oldWidth, oldHeight);
  }

  auto insertion = nameVehicleMap.insert_or_assign(
      vehicleName, DrawableVehicle(vehicleName, laneName, road, positionOnLane,
                                   speed, remainingFuel, red, green, blue));

  auto &insertedVehicle = insertion.first->second;
  int newX, newY, newWidth, newHeight;
  insertedVehicle.getRegion(newX, newY, newWidth, newHeight);

  Glib::signal_idle().connect_once(
      [this, newX, newY, newWidth, newHeight, oldX, oldY, oldWidth,
       oldHeight]() {
        mapArea.queue_draw_area(newX, newY, newWidth, newHeight);
        mapArea.queue_draw_area(oldX, oldY, oldWidth, oldHeight);
      },
      Glib::PRIORITY_HIGH_IDLE + 20);

  if (selectedRow != nullptr) {
    auto selectedVehicleName =
        dynamic_cast<Gtk::Label &>(*selectedRow->get_child()).get_text();
    if (selectedVehicleName == vehicleName) {
      Glib::signal_idle().connect_once(
          [this, &insertedVehicle]() { refreshVehicleLabels(insertedVehicle); },
          Glib::PRIORITY_HIGH_IDLE + 20);
    }
  }

  if (insertion.second) {
266 267
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
    auto *label = Gtk::manage(new Gtk::Label());
Martin Kröning's avatar
Martin Kröning committed
268
    label->set_text(vehicleName);
269 270
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
    auto *listBoxRow = Gtk::manage(new Gtk::ListBoxRow());
Martin Kröning's avatar
Martin Kröning committed
271 272 273 274 275 276
    listBoxRow->add(*label);
    listBox->append(*listBoxRow);
    listBox->show_all_children();
    listBox->select_row(*listBoxRow);
  }
}
277 278 279 280 281 282 283

void MapApp::resizeWindow() {
  Gtk::Requisition minimumSize, naturalSize;
  win.get_preferred_size(minimumSize, naturalSize);
  win.resize(static_cast<int>(naturalSize.width),
             static_cast<int>(naturalSize.height));
}