OpenCPN Partial API docs
Loading...
Searching...
No Matches
connections_dlg.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * Copyright (C) 2025 Alec Leamas *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
23
24#include <array>
25#include <algorithm>
26#include <sstream>
27#include <string>
28#include <vector>
29
30#include "gl_headers.h" // Must be included before anything using GL stuff
31
32#include <wx/arrstr.h>
33#include <wx/bitmap.h>
34#include <wx/grid.h>
35#include <wx/panel.h>
36#include <wx/sizer.h>
37#include <wx/spinctrl.h>
38#include <wx/textctrl.h>
39#include <wx/window.h>
40
41#include "libgui/expand_panel.h"
42
43#include "model/base_platform.h"
45#include "model/comm_util.h"
46#include "model/config_vars.h"
47#include "model/conn_params.h"
48#include "model/conn_states.h"
49#include "model/gui_events.h"
51
52#include "connections_dlg.h"
53
54#include "color_handler.h"
55#include "color_types.h"
56#include "connection_edit.h"
57#include "conn_params_panel.h"
58#include "gui_lib.h"
59#include "navutil.h"
60#include "options.h"
61#include "priority_gui.h"
62#include "std_filesystem.h"
63
64static constexpr auto TopScrollWindowName = "TopScroll";
65
66static const char* kInfoHeader = _("OpenCPN help").c_str();
67static const char* kInfo = _(R"---(
68Normally OpenCPN sends the RMB (distance and heading to waypoint
69etc) and RMC (position, heading etc.) sentences when there is an
70active waypoint. The talker ID is by default EC.
71
72In certain cases these messages (ECRMB and ECRMC) are required
73also when there is no active waypoint. This option enables this.
74
75Obviously, this option carries risks for vessels which have an
76autopilot which is not engaged manually -- the "fake" RMB messages
77could possibly initiate the autopilot in dangerous ways.
78
79Devices needing this includes the NASA Clipper GPS Repeater. In this
80case the output must also be filtered so that ECRMB and ECRMC are
81the only transmitted messages.
82)---")
83 .c_str();
84
85static const char* kInterfaceExistsMessage =
86 _("Warning: A driver using this interface already exists.").c_str();
87
88static wxString UtfArrowDown() {
89 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u25bc"));
90}
91static wxString UtfArrowRight() {
92 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u25ba"));
93}
94static wxString UtfCheckMark() {
95 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u2713"));
96}
97static wxString UtfGear() {
98 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u2699"));
99}
100static wxString UtfFilledCircle() {
101 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u25cf"));
102}
103static wxString UtfOpenCircle() {
104 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\u25c8"));
105}
106static wxString UtfWastebasket() {
107 return wxString::FromUTF8(reinterpret_cast<const char*>(u8"\U0001f5d1"));
108}
109
110static bool IsWindows() {
111 return wxPlatformInfo::Get().GetOperatingSystemId() & wxOS_WINDOWS;
112}
113
114static bool IsAndroid() {
115#ifdef ANDROID
116 return true;
117#else
118 return false;
119#endif
120}
121
122static std::string BitsToDottedMask(const unsigned bits) {
123 const uint32_t mask = 0xffffffff << (32 - bits);
124 std::stringstream ss;
125 ss << ((mask & 0xff000000) >> 24) << ".";
126 ss << ((mask & 0x00ff0000) >> 16) << ".";
127 ss << ((mask & 0x0000ff00) >> 8) << ".";
128 ss << (mask & 0x000000ff);
129 return ss.str();
130}
131
132static ConnectionParams* FindConnectionByIface(const ConnectionParams* new_cp) {
133 for (const auto& cp : TheConnectionParams()) {
134 if (cp->type != new_cp->type) continue;
135 switch (cp->type) {
136 case SERIAL:
137 if (cp->serial_port != new_cp->serial_port) continue;
138 return cp;
139 break;
140 case NETWORK:
141 if (cp->net_protocol != new_cp->net_protocol) continue;
142 if (cp->network_address != new_cp->network_address) continue;
143 if (cp->network_port != new_cp->network_port) continue;
144 return cp;
145 break;
146 case INTERNAL_GPS:
147 return cp;
148 break;
149 case INTERNAL_BT:
150 return cp;
151 break;
152 case SOCKETCAN:
153 if (cp->socket_can_port != new_cp->socket_can_port) continue;
154 return cp;
155 break;
156 case CANABLE:
157 if (cp->serial_port != new_cp->serial_port) continue;
158 return cp;
159 break;
160 default:
161 continue;
162 }
163 }
164 return nullptr;
165}
166
167static ConnectionParams* FindConnectionByIface(
168 const std::unique_ptr<ConnectionParams>& cp) {
169 return FindConnectionByIface(cp.get());
170}
171
172namespace {
173
178class BitmapEnableCellRenderer : public wxGridCellBoolRenderer {
179public:
180 BitmapEnableCellRenderer(int _size, ColorScheme cs) : size(_size), m_cs(cs) {}
181
182 [[nodiscard]] BitmapEnableCellRenderer* Clone() const override {
183 return new BitmapEnableCellRenderer(size, m_cs);
184 }
185
186 wxSize GetBestSize(wxGrid& grid, wxGridCellAttr& attr, wxDC& dc, int row,
187 int col) override {
188 return {size, size};
189 }
190
191private:
192 int size;
193 ColorScheme m_cs;
194};
195
197class ConnCompare {
198public:
199 explicit ConnCompare(int col) : m_col(col) {}
200
201 bool operator()(const ConnectionParams* p1,
202 const ConnectionParams* p2) const {
203 switch (m_col) {
204 case 0:
205 return static_cast<int>(p1->is_enabled) >
206 static_cast<int>(p2->is_enabled);
207 case 1:
208 return p1->GetCommProtocol() < p2->GetCommProtocol();
209 case 2:
211 case 3:
212 return p1->GetStrippedDSPort() < p2->GetStrippedDSPort();
213 default:
214 return false;
215 }
216 }
217
218private:
219 const int m_col;
220};
221
225class ApplyCancel {
226public:
230 virtual ~ApplyCancel() = default;
231
233 virtual void Apply() = 0;
234
238 virtual void Cancel() = 0;
239};
240
242class AddConnectionButton final : public wxButton {
243public:
244 AddConnectionButton(wxWindow* parent, obs::EventVar& evt_add_connection,
245 const std::function<void(ConnectionParams* p,
246 bool editing)>& _start_edit_conn)
247 : wxButton(parent, wxID_ANY, _("Add new connection...")),
248 m_evt_add_connection(evt_add_connection),
249 m_start_edit_conn(_start_edit_conn) {
250 Bind(wxEVT_COMMAND_BUTTON_CLICKED,
251 [&](wxCommandEvent&) { OnAddConnection(); });
252 }
253
254private:
255 void OnAddConnection() const { m_start_edit_conn(nullptr, false); }
256
257 obs::EventVar& m_evt_add_connection;
258 std::function<void(ConnectionParams* p, bool editing)> m_start_edit_conn;
259};
260
262class Connections final : public wxGrid {
263public:
264 Connections(wxWindow* parent,
265 const std::vector<ConnectionParams*>& connections,
266 obs::EventVar& on_conn_update,
267 const std::function<void(ConnectionParams* p, bool editing)>&
268 on_edit_conn)
269 : wxGrid(parent, wxID_ANY),
270 m_connections(connections),
271 m_header_column_widths({0, 0, 0, 0, 0, 0, 0}),
272 m_last_tooltip_cell(100),
273 m_cs(GLOBAL_COLOR_SCHEME_DAY),
274 m_on_conn_delete(on_conn_update),
275 m_on_edit_conn(on_edit_conn) {
276 ShowScrollbars(wxSHOW_SB_NEVER, wxSHOW_SB_NEVER);
277 SetTable(new wxGridStringTable(), true);
278 GetTable()->AppendCols(8);
279 HideCol(7);
280 if (IsAndroid()) {
281 SetDefaultRowSize(wxWindow::GetCharHeight() * 2);
282 SetColLabelSize(wxWindow::GetCharHeight() * 2);
283 }
284 static const std::array<wxString, 7> headers = {
285 "", _("Protocol") + " ", _("In/Out"), _("Data port"), _("Status"), "",
286 ""};
287 int ic = 0;
288 for (auto hdr = headers.begin(); hdr != headers.end(); hdr++, ic++) {
289 SetColLabelValue(static_cast<int>(hdr - headers.begin()), *hdr);
290 unsigned col_width = hdr->Length() * wxWindow::GetCharWidth();
291 col_width = wxMax(col_width, 6 * wxWindow::GetCharWidth());
292 m_header_column_widths[ic] = static_cast<int>(col_width);
293 SetColSize(ic, static_cast<int>(col_width));
294 }
295
296 if (IsWindows()) {
297 SetLabelBackgroundColour(GetGlobalColor("DILG1"));
298 SetLabelTextColour(GetGlobalColor("DILG3"));
299 }
300 HideRowLabels();
301 SetColAttributes(parent);
302
303 OnColorChange();
304 ReloadGrid(connections);
305 DisableDragColSize();
306 DisableDragRowSize();
307 wxWindow::Show(GetNumberRows() > 0);
308
309 GetGridWindow()->Bind(wxEVT_MOTION, [&](wxMouseEvent& ev) {
310 OnMouseMove(ev);
311 ev.Skip();
312 });
313 GetGridWindow()->Bind(wxEVT_MOUSEWHEEL,
314 [&](wxMouseEvent& ev) { OnWheel(ev); });
315 // wxGridEvent.GetCol() and GetRow() are not const until wxWidgets 3.2
316 Bind(wxEVT_GRID_LABEL_LEFT_CLICK,
317 [&](wxGridEvent& ev) { HandleSort(ev.GetCol()); });
318 Bind(wxEVT_GRID_CELL_LEFT_CLICK,
319 [&](wxGridEvent& ev) { OnClickCell(ev.GetRow(), ev.GetCol()); });
320 Bind(wxEVT_PAINT, [&](wxPaintEvent& ev) {
321 SetColAttributes(dynamic_cast<const wxWindow*>(ev.GetEventObject()));
322 ev.Skip();
323 });
324 Bind(wxEVT_SYS_COLOUR_CHANGED,
325 [&](wxSysColourChangedEvent& ev) { OnColorChange(ev); });
326 conn_change_lstnr.Init(
327 m_conn_states.evt_conn_status_change,
328 [&](ObservedEvt&) { OnConnectionChange(m_connections); });
329 }
330
331 void SetColorScheme(const ColorScheme cs) {
332 m_cs = cs;
333 ReloadGrid(m_connections);
334 }
335
336 void OnColorChange() {
337 auto foreground = wxSystemSettings::GetColour(wxSYS_COLOUR_MENUTEXT);
338 auto background = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
339 SetLabelBackgroundColour(background);
340 SetLabelTextColour(foreground);
341 for (int row = 0; row <= GetNumberRows(); row++) {
342 for (unsigned col = 0; col < 7; col++) {
343 SetCellBackgroundColour(row, col, background);
344 SetCellTextColour(row, col, foreground);
345 }
346 }
347 }
348
349 void OnColorChange(wxSysColourChangedEvent& ev) {
350 OnColorChange();
351 ev.Skip();
352 }
353
354 wxSize GetEstimatedSize() const {
355 unsigned rs = 0;
356 for (auto s : m_header_column_widths) rs += s;
357 return {static_cast<int>(rs), -1};
358 }
359
361 void OnWheel(wxMouseEvent& ev) {
362 if (!IsShown()) {
363 ev.Skip();
364 return;
365 }
366 auto w =
367 dynamic_cast<wxScrolledWindow*>(FindWindowByName(TopScrollWindowName));
368 if (!w) return;
369 int xpos;
370 int ypos;
371 w->GetViewStart(&xpos, &ypos);
372 int x;
373 int y;
374 w->GetScrollPixelsPerUnit(&x, &y);
375 // Not sure where the factor "4" comes from...
376 const int dir = ev.GetWheelRotation();
377 w->Scroll(-1, ypos - dir / y / 4);
378 }
379
381 void ReloadGrid(const std::vector<ConnectionParams*>& connections) {
382 ClearGrid();
383
384 for (auto it = connections.begin(); it != connections.end(); ++it) {
385 const auto row = static_cast<int>(it - connections.begin());
386 EnsureRows(row);
387 SetCellValue(row, 0, (*it)->is_enabled ? "1" : "");
388 if ((*it)->is_enabled)
389 m_tooltips[row][0] = _("Enabled, click to disable");
390 else
391 m_tooltips[row][0] = _("Disabled, click to enable");
392 std::string protocol = NavAddr::BusToString((*it)->GetCommProtocol());
393 SetCellValue(row, 1, protocol);
394 SetCellValue(row, 2, (*it)->GetPortDirectionValueStr());
395 SetCellValue(row, 3, (*it)->GetStrippedDSPort());
396 m_tooltips[row][3] = (*it)->user_comment;
397 SetCellValue(row, 5, UtfGear());
398 m_tooltips[row][5] = _("Edit connection");
399 SetCellValue(row, 6, UtfWastebasket());
400 m_tooltips[row][6] = _("Delete connection");
401 SetCellValue(row, 7, (*it)->GetKey());
402
403 if (IsAndroid()) {
404 wxString sp(protocol);
405 unsigned size = sp.Length() * wxWindow::GetCharWidth();
406 m_header_column_widths[1] = std::max(m_header_column_widths[1], size);
407 size = (*it)->GetPortDirectionValueStr().Length() *
408 wxWindow::GetCharWidth();
409 m_header_column_widths[2] = std::max(m_header_column_widths[2], size);
410 sp = wxString((*it)->GetStrippedDSPort());
411 size = sp.Length() * wxWindow::GetCharWidth();
412 m_header_column_widths[3] = std::max(m_header_column_widths[3], size);
413 }
414 }
415 OnConnectionChange(m_connections);
416 OnColorChange();
417
418 if (IsAndroid()) {
419 int ic = 0;
420 for (auto val : m_header_column_widths) {
421 SetColSize(ic, static_cast<int>(val));
422 ic++;
423 }
424 } else
425 AutoSize();
426 }
427
429 class ConnStateCompare {
430 public:
431 explicit ConnStateCompare(Connections* connections)
432 : m_conns(connections) {}
433 bool operator()(const ConnectionParams* p1,
434 const ConnectionParams* p2) const {
435 int row1 = m_conns->FindConnectionIndex(p1);
436 int row2 = m_conns->FindConnectionIndex(p2);
437 if (row1 == -1 && row2 == -1) return false;
438 if (row1 == -1) return false;
439 if (row2 == -1) return true;
440 const int v1 = m_conns->GetCellValue(row1, 4)[0];
441 const int v2 = m_conns->GetCellValue(row2, 4)[0];
442 return v1 < v2;
443 }
444 Connections* m_conns;
445 };
446
451 int FindConnectionIndex(const ConnectionParams* cp) const {
452 using namespace std;
453 auto key = cp->GetKey();
454 auto found = find_if(
455 m_connections.begin(), m_connections.end(),
456 [key](const ConnectionParams* cp) { return cp->GetKey() == key; });
457 if (found == m_connections.end()) return -1;
458 return static_cast<int>(found - m_connections.begin());
459 }
460
461private:
466 ConnectionParams* FindRowConnection(const int row) const {
467 auto found = find_if(m_connections.begin(), m_connections.end(),
468 [&](const ConnectionParams* p) {
469 return GetCellValue(row, 7) == p->GetKey();
470 });
471 return found != m_connections.end() ? *found : nullptr;
472 }
473
478 void EnsureRows(size_t rows) {
479 for (unsigned i = m_tooltips.size(); i <= rows; i++)
480 m_tooltips.emplace_back(std::vector<std::string>(7));
481 for (unsigned i = GetNumberRows(); i <= rows; i++) AppendRows(1, false);
482 }
483
485 void SetColAttributes(const wxWindow* parent) {
486 if (IsWindows()) {
487 // Set all cells to global color scheme
488 SetDefaultCellBackgroundColour(GetGlobalColor("DILG1"));
489 }
490 auto enable_attr = new wxGridCellAttr();
491 enable_attr->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
492
493 if (IsAndroid())
494 enable_attr->SetRenderer(
495 new BitmapEnableCellRenderer(wxWindow::GetCharWidth() * 3 / 2, m_cs));
496 else
497 enable_attr->SetRenderer(new wxGridCellBoolRenderer());
498
499 enable_attr->SetEditor(new wxGridCellBoolEditor());
500 if (IsWindows()) enable_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
501 SetColAttr(0, enable_attr);
502
503 auto protocol_attr = new wxGridCellAttr();
504 protocol_attr->SetAlignment(wxALIGN_LEFT, wxALIGN_CENTRE);
505 protocol_attr->SetReadOnly(true);
506 if (IsWindows())
507 protocol_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
508 SetColAttr(1, protocol_attr);
509
510 auto in_out_attr = new wxGridCellAttr();
511 in_out_attr->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
512 in_out_attr->SetReadOnly(true);
513 if (IsWindows()) in_out_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
514 SetColAttr(2, in_out_attr);
515
516 auto port_attr = new wxGridCellAttr();
517 port_attr->SetAlignment(wxALIGN_LEFT, wxALIGN_CENTRE);
518 port_attr->SetReadOnly(true);
519 if (IsWindows()) port_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
520 SetColAttr(3, port_attr);
521
522 auto status_attr = new wxGridCellAttr();
523 status_attr->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
524 status_attr->SetReadOnly(true);
525 status_attr->SetFont(parent->GetFont().Scale(1.3));
526 if (IsWindows()) status_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
527 SetColAttr(4, status_attr);
528
529 auto edit_attr = new wxGridCellAttr();
530 edit_attr->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE);
531 edit_attr->SetFont(parent->GetFont().Scale(1.3));
532 edit_attr->SetReadOnly(true);
533 if (IsWindows()) edit_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
534 SetColAttr(5, edit_attr);
535
536 auto delete_attr = new wxGridCellAttr();
537 delete_attr->SetAlignment(wxALIGN_LEFT, wxALIGN_CENTRE);
538 delete_attr->SetFont(parent->GetFont().Scale(1.3));
539 delete_attr->SetTextColour(*wxRED);
540 delete_attr->SetReadOnly(true);
541 if (IsWindows()) delete_attr->SetBackgroundColour(GetGlobalColor("DILG1"));
542 SetColAttr(6, delete_attr);
543 }
544
546 void OnClickCell(int row, int col) {
547 if (col == 0)
548 HandleEnable(row);
549 else if (col == 5) {
550 HandleEdit(row);
551 } else if (col == 6) {
552 HandleDelete(row);
553 }
554 }
555
557 void OnMouseMove(wxMouseEvent& ev) {
558 if (!IsShown()) return;
559 const wxPoint pt = ev.GetPosition();
560 int row = YToRow(pt.y);
561 int col = XToCol(pt.x);
562 if (col < 0 || col >= 7 || row < 0 || row >= GetNumberRows()) return;
563 if (row * 7 + col == m_last_tooltip_cell) return;
564 m_last_tooltip_cell = row * 7 + col;
565 GetGridWindow()->SetToolTip(m_tooltips[row][col]);
566 ev.Skip();
567 }
568
570 void OnConnectionChange(const std::vector<ConnectionParams*>& connections) {
571 bool refresh_needed = false;
572 for (auto it = connections.begin(); it != connections.end(); ++it) {
573 ConnState state = m_conn_states.GetDriverState(
574 (*it)->GetCommProtocol(), (*it)->GetStrippedDSPort());
575 if (!(*it)->is_enabled) state = ConnState::Disabled;
576 auto row = static_cast<int>(it - connections.begin());
577 EnsureRows(row);
578 switch (state) {
579 case ConnState::Disabled:
580 SetCellValue(row, 4, UtfFilledCircle());
581 m_tooltips[row][4] = _("Disabled");
582 refresh_needed = true;
583 break;
584 case ConnState::NoStats:
585 SetCellValue(row, 4, UtfOpenCircle());
586 m_tooltips[row][4] = _("No driver statistics available");
587 refresh_needed = true;
588 break;
589 case ConnState::NoData:
590 SetCellValue(row, 4, "!");
591 m_tooltips[row][4] = _("No data flowing through connection");
592 refresh_needed = true;
593 break;
594 case ConnState::Unavailable:
595 SetCellValue(row, 4, "X");
596 m_tooltips[row][4] = _("The device is unavailable");
597 refresh_needed = true;
598 break;
599 case ConnState::Ok:
600 SetCellValue(row, 4, UtfCheckMark());
601 m_tooltips[row][4] = _("Data is flowing");
602 refresh_needed = true;
603 break;
604 }
605 }
606 if (refresh_needed) ForceRefresh();
607 }
608
610 void SetSortingColumn(int col) {
611 if (GetSortingColumn() != wxNOT_FOUND) {
612 int old_col = GetSortingColumn();
613 auto label = GetColLabelValue(old_col);
614 if (label[0] == UtfArrowDown()[0])
615 SetColLabelValue(old_col, label.substr(2));
616 }
617 auto label = GetColLabelValue(col);
618 if (label[0] != UtfArrowDown()[0])
619 SetColLabelValue(col, UtfArrowDown() + " " + label);
620 wxGrid::SetSortingColumn(col);
621 Fit();
622 }
623
625 void HandleSort(int col) {
626 if (col > 4) return;
627 auto& params = TheConnectionParams();
628 if (col < 4)
629 std::sort(params.begin(), params.end(), ConnCompare(col));
630 else // col == 4
631 std::sort(params.begin(), params.end(), ConnStateCompare(this));
632 ReloadGrid(TheConnectionParams());
633 SetSortingColumn(col);
634 }
635
637 void HandleEnable(int row) {
638 ConnectionParams* cp = FindRowConnection(row);
639 if (!cp) return;
640 cp->is_enabled = !cp->is_enabled;
641 cp->is_setup = FALSE; // trigger a rebuild/takedown of the connection
642 SetCellValue(row, 0, cp->is_enabled ? "1" : "");
643 if (cp->is_enabled)
644 m_tooltips[row][0] = _("Enabled, click to disable");
645 else
646 m_tooltips[row][0] = _("Disabled, click to enable");
647 DriverStats stats;
648 stats.driver_iface = cp->GetStrippedDSPort();
649 stats.driver_bus = cp->GetCommProtocol();
650 m_conn_states.HandleDriverStats(stats);
651 StopAndRemoveCommDriver(cp->GetStrippedDSPort(), cp->GetCommProtocol());
652 if (cp->is_enabled) MakeCommDriver(cp);
653 cp->is_setup = true;
654 if (!cp->is_enabled) {
655 SetCellValue(row, 4, UtfFilledCircle());
656 // ForceRefresh() apparently broken, see #4648
657 ReloadGrid(TheConnectionParams());
658 }
659 }
660
662 void HandleEdit(int row) {
663 if (ConnectionParams* cp = FindRowConnection(row)) {
664 Show(GetNumberRows() > 0);
665 m_on_edit_conn(cp, true);
666 }
667 }
668
670 void HandleDelete(int row) {
671 ConnectionParams* cp = FindRowConnection(row);
672 auto found = std::find(m_connections.begin(), m_connections.end(), cp);
673 if (found != m_connections.end()) {
674 std::stringstream ss;
675 ss << _("Ok to delete connection on ") << (*found)->GetStrippedDSPort();
676 int rcode = OCPNMessageBox(this, ss.str(), _("Delete connection?"),
677 wxOK | wxCANCEL);
678 if (rcode != wxID_OK && rcode != wxID_YES) return;
679 delete (*found)->options_panel;
680 StopAndRemoveCommDriver((*found)->GetStrippedDSPort(),
681 (*found)->GetCommProtocol());
682 TheConnectionParams().erase(found);
683 if (GetNumberRows() > static_cast<int>(m_connections.size()))
684 DeleteRows(GetNumberRows() - 1);
685 m_on_conn_delete.Notify();
686 }
687 }
688
689 obs::Listener conn_change_lstnr;
690 std::vector<std::vector<std::string>> m_tooltips;
691 ConnStates m_conn_states;
692 const std::vector<ConnectionParams*>& m_connections;
693 std::array<unsigned, 7> m_header_column_widths;
694 int m_last_tooltip_cell;
695 ColorScheme m_cs;
696 obs::EventVar& m_on_conn_delete;
697 std::function<void(ConnectionParams* p, bool editing)> m_on_edit_conn;
698};
699
701class GeneralPanel : public wxPanel {
702public:
703 explicit GeneralPanel(wxWindow* parent) : wxPanel(parent, wxID_ANY) {
704 auto sizer = new wxStaticBoxSizer(wxVERTICAL, this, _("General"));
705 SetSizer(sizer);
706 auto flags = wxSizerFlags().Border();
707 m_upload_options = new UploadOptionsChoice(this);
708 sizer->Add(m_upload_options, flags);
709 sizer->Add(new PrioritiesBtn(this), flags);
710 }
711
712 void SetColorScheme(ColorScheme) {
713 DimeControl(m_upload_options);
714 Refresh();
715 }
716
717private:
719 class PrioritiesBtn final : public wxButton {
720 public:
721 explicit PrioritiesBtn(wxWindow* parent)
722 : wxButton(parent, wxID_ANY, _("Adjust Nav data priorities...")) {
723 Bind(wxEVT_COMMAND_BUTTON_CLICKED, [&](wxCommandEvent&) {
724 PriorityDlg dialog(this->GetParent());
725 dialog.ShowModal();
726 });
727 }
728 };
729
731 class UploadOptionsChoice final : public wxRadioBox, public ApplyCancel {
732 public:
733 explicit UploadOptionsChoice(wxWindow* parent) : wxRadioBox() {
734 wxArrayString wx_choices;
735 for (auto& c : choices) wx_choices.Add(c);
736 Create(parent, wxID_ANY, _("Upload Format"), wxDefaultPosition,
737 wxDefaultSize, wx_choices, 0, wxRA_SPECIFY_ROWS);
738 DimeControl(this);
739 UploadOptionsChoice::Cancel();
740 }
741
742 void Cancel() override {
743 if (g_bGarminHostUpload)
744 SetSelection(1);
745 else if (g_GPS_Ident == "FurunoGP3X")
746 SetSelection(2);
747 else
748 SetSelection(0);
749 }
750
751 void Apply() override {
752 switch (GetSelection()) {
753 case 0:
754 g_bGarminHostUpload = false;
755 g_GPS_Ident = "Generic";
756 break;
757 case 1:
758 g_bGarminHostUpload = true;
759 g_GPS_Ident = "Generic";
760 break;
761 case 2:
762 g_bGarminHostUpload = false;
763 g_GPS_Ident = "FurunoGP3X";
764 break;
765 default:
766 assert(false && "Invalid upload case option");
767 }
768 }
769
770 const std::array<wxString, 3> choices = {
771 _("Generic NMEA 0183"), _("Garmin Host mode"), _("Furuno GP4X")};
772 };
773
774 UploadOptionsChoice* m_upload_options;
775};
776
778class AdvancedPanel : public wxPanel {
779public:
780 explicit AdvancedPanel(wxWindow* parent) : wxPanel(parent, wxID_ANY) {
781 auto sizer = new wxStaticBoxSizer(wxVERTICAL, this, "");
782 sizer->Add(new BearingsCheckbox(this), wxSizerFlags().Expand());
783 sizer->Add(new ExtraRmbRmcLine(this), wxSizerFlags().Expand());
784 sizer->Add(new NmeaFilterRow(this), wxSizerFlags().Expand());
785 sizer->Add(new TalkerIdRow(this), wxSizerFlags().Expand());
786 sizer->Add(new NetmaskRow(this), wxSizerFlags().Expand());
787 SetSizer(sizer);
788 }
789
790private:
792 class BearingsCheckbox : public wxCheckBox, public ApplyCancel {
793 public:
794 explicit BearingsCheckbox(wxWindow* parent)
795 : wxCheckBox(parent, wxID_ANY,
796 _("Use magnetic bearing in output sentence APB")) {
797 wxCheckBox::SetValue(g_bMagneticAPB);
798 }
799
800 void Apply() override { g_bMagneticAPB = GetValue(); }
801 void Cancel() override { SetValue(g_bMagneticAPB); }
802 };
803
804 class ExtraRmbRmcLine : public wxPanel {
805 class RmbRmcCheckbox : public wxCheckBox, public ApplyCancel {
806 public:
807 explicit RmbRmcCheckbox(wxWindow* parent)
808 : wxCheckBox(parent, wxID_ANY,
809 _("Always send RMB and RMC NMEA0183 data")) {
810 wxCheckBox::SetValue(g_always_send_rmb_rmc);
811 }
812
813 void Apply() override { g_always_send_rmb_rmc = GetValue(); }
814 void Cancel() override { SetValue(g_always_send_rmb_rmc); }
815 };
816
817 public:
818 explicit ExtraRmbRmcLine(wxWindow* parent) : wxPanel(parent, wxID_ANY) {
819 auto hbox = new wxBoxSizer(wxHORIZONTAL);
820 hbox->Add(new RmbRmcCheckbox(this), wxSizerFlags().Expand());
821 hbox->Add(1, 1, 1, wxEXPAND);
822 hbox->Add(new InfoButton(this, g_btouch, kInfoHeader, kInfo),
823 wxSizerFlags().Border());
824 SetSizer(hbox);
825 wxWindow::Layout();
826 wxWindow::Show();
827 }
828 };
829
830 class ExtraRmbRmcCheckbox final : public wxCheckBox, public ApplyCancel {
831 public:
832 explicit ExtraRmbRmcCheckbox(wxWindow* parent)
833 : wxCheckBox(parent, wxID_ANY,
834 _("Always send RMB and RMC NMEA0183 data")) {
835 wxCheckBox::SetValue(g_always_send_rmb_rmc);
836 }
837
838 void Apply() override { g_always_send_rmb_rmc = GetValue(); }
839 void Cancel() override { SetValue(g_always_send_rmb_rmc); }
840 };
841
843 class NmeaFilterRow : public wxPanel, public ApplyCancel {
844 wxCheckBox* checkbox;
845 wxTextCtrl* filter_period;
846
847 public:
848 explicit NmeaFilterRow(wxWindow* parent) : wxPanel(parent) {
849 auto hbox = new wxBoxSizer(wxHORIZONTAL);
850 checkbox = new wxCheckBox(
851 this, wxID_ANY,
852 _("Filter NMEA course and speed data. Filter period: "));
853 checkbox->SetValue(g_bfilter_cogsog);
854 hbox->Add(checkbox, wxSizerFlags().Align(wxALIGN_CENTRE));
855 filter_period =
856 new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition,
857 wxSize(50, 3 * wxWindow::GetCharWidth()), 0);
858 filter_period->SetValue(std::to_string(g_COGFilterSec));
859 hbox->Add(filter_period, wxSizerFlags().Border());
860 SetSizer(hbox);
861 NmeaFilterRow::Cancel();
862 }
863
864 void Apply() override {
865 std::stringstream ss;
866 ss << filter_period->GetValue();
867 ss >> g_COGFilterSec;
868 g_bfilter_cogsog = checkbox->GetValue();
869 }
870
871 void Cancel() override {
872 std::stringstream ss;
873 ss << g_COGFilterSec;
874 filter_period->SetValue(ss.str());
875 checkbox->SetValue(g_bfilter_cogsog);
876 }
877 };
878
880 class TalkerIdRow : public wxPanel, public ApplyCancel {
881 wxTextCtrl* text_ctrl;
882
883 public:
884 explicit TalkerIdRow(wxWindow* parent) : wxPanel(parent) {
885 auto hbox = new wxBoxSizer(wxHORIZONTAL);
886 hbox->Add(new wxStaticText(this, wxID_ANY, _("NMEA 0183 Talker Id: ")),
887 wxSizerFlags().Align(wxALIGN_CENTRE_VERTICAL).Border());
888 text_ctrl = new wxTextCtrl(
889 this, wxID_ANY, "", wxDefaultPosition,
890 wxSize(4 * wxWindow::GetCharWidth(), 3 * wxWindow::GetCharWidth()));
891 text_ctrl->SetToolTip(
892 _("Enter a two-letter talker ID to override the default ID in NMEA "
893 "sentences generated by OpenCPN (e.g., GP, HC, EC). This affects "
894 "only sentences created by OpenCPN, not those forwarded from other "
895 "devices."));
896 text_ctrl->SetValue(g_TalkerIdText);
897 hbox->Add(text_ctrl, wxSizerFlags().Border());
898 SetSizer(hbox);
899 TalkerIdRow::Cancel();
900 }
901
902 void Apply() override { g_TalkerIdText = text_ctrl->GetValue(); }
903 void Cancel() override { text_ctrl->SetValue(g_TalkerIdText); }
904 };
905
907 class NetmaskRow : public wxPanel, public ApplyCancel {
908 public:
909 explicit NetmaskRow(wxWindow* parent)
910 : wxPanel(parent),
911 m_spin_ctrl(new wxSpinCtrl(this, wxID_ANY)),
912 m_text(new wxStaticText(this, wxID_ANY, "")) {
913 m_spin_ctrl->SetRange(8, 32);
914 auto hbox = new wxBoxSizer(wxHORIZONTAL);
915 auto flags = wxSizerFlags().Align(wxALIGN_CENTRE_VERTICAL).Border();
916 hbox->Add(new wxStaticText(this, wxID_ANY, _("Netmask: ")), flags);
917 hbox->Add(m_text, flags);
918 hbox->Add(new wxStaticText(this, wxID_ANY, _("length (bits): ")), flags);
919 hbox->Add(m_spin_ctrl, flags);
920 SetSizer(hbox);
921 NetmaskRow::Cancel();
922
923 Bind(wxEVT_SPINCTRL, [&](wxSpinEvent&) {
924 m_text->SetLabel(BitsToDottedMask(m_spin_ctrl->GetValue()));
925 Layout();
926 });
927 }
928
929 void Apply() override { g_netmask_bits = m_spin_ctrl->GetValue(); }
930
931 void Cancel() override {
932 m_spin_ctrl->SetValue(g_netmask_bits);
933 m_text->SetLabel(BitsToDottedMask(m_spin_ctrl->GetValue()));
934 Layout();
935 }
936
937 private:
938 wxSpinCtrl* m_spin_ctrl;
939 wxStaticText* m_text;
940 };
941};
942
944class TopPanel : public wxPanel {
945public:
946 TopPanel(wxWindow* parent, const std::vector<ConnectionParams*>& connections,
947 obs::EventVar& evt_add_connection,
948 const std::function<void(ConnectionParams* p, bool editing)>&
949 on_edit_conn)
950 : wxPanel(parent, wxID_ANY),
951 m_evt_add_connection(evt_add_connection),
952 m_connections(connections) {
953 auto vbox = new wxBoxSizer(wxVERTICAL);
954 auto conn_grid = new Connections(this, m_connections, m_evt_add_connection,
955 on_edit_conn);
956 vbox->AddSpacer(wxWindow::GetCharHeight());
957 auto conn_flags = wxSizerFlags().Border();
958 if (IsAndroid()) conn_flags = wxSizerFlags().Border().Expand();
959 vbox->Add(conn_grid, conn_flags);
960 vbox->Add(new AddConnectionButton(this, m_evt_add_connection, on_edit_conn),
961 wxSizerFlags().Border());
962 vbox->Add(0, wxWindow::GetCharHeight()); // Expanding spacer
963 auto panel_flags =
964 wxSizerFlags().Border(wxLEFT | wxDOWN | wxRIGHT).Expand();
965 m_general_panel = new GeneralPanel(this);
966 m_general_panel->SetMinSize(m_general_panel->GetBestSize());
967 vbox->Add(m_general_panel, panel_flags);
968
969 auto advanced_panel = new AdvancedPanel(this);
970 m_advanced_panel = advanced_panel;
971 auto adv_box = new wxBoxSizer(wxHORIZONTAL);
972 adv_box->Add(new wxStaticText(this, wxID_ANY, _("Advanced")));
973 adv_box->Add(new ExpandablePanel(this, advanced_panel,
974 [&] { GetParent()->Layout(); }));
975 vbox->Add(adv_box, wxSizerFlags().Border());
976 vbox->Add(advanced_panel,
977 wxSizerFlags().Border().ReserveSpaceEvenIfHidden());
978
979 SetSizer(vbox);
980 vbox->SetSizeHints(this);
981 vbox->Fit(this);
982 wxWindow::Fit();
983 wxWindow::Show();
984
985 auto on_evt_update_connections = [&, conn_grid](ObservedEvt&) {
986 conn_grid->ReloadGrid(TheConnectionParams());
987 conn_grid->Show(conn_grid->GetNumberRows() > 0);
988 Layout();
989 FitInside();
990 };
991 m_add_connection_lstnr.Init(m_evt_add_connection,
992 on_evt_update_connections);
993 m_conn_grid = conn_grid;
994 }
995
996 void SetColorScheme(const ColorScheme cs) const {
997 m_conn_grid->SetColorScheme(cs);
998 m_general_panel->SetColorScheme(cs);
999 }
1000 [[nodiscard]] Connections* GetConnectionsGrid() const { return m_conn_grid; }
1001
1002 obs::EventVar& m_evt_add_connection;
1003
1004private:
1005 const std::vector<ConnectionParams*>& m_connections;
1006 obs::Listener m_add_connection_lstnr;
1007 Connections* m_conn_grid;
1008 GeneralPanel* m_general_panel;
1009 AdvancedPanel* m_advanced_panel;
1010};
1011
1012} // anonymous namespace
1013
1015class EditPanel : public wxScrolled<wxPanel> {
1016public:
1017 EditPanel(wxWindow* parent, const std::vector<ConnectionParams*>& connections,
1018 obs::EventVar& evt_add_connection)
1019 : wxScrolled<wxPanel>(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,
1020 wxVSCROLL | wxHSCROLL),
1021 m_edited_connection(nullptr),
1022 m_edit_panel(nullptr) {
1023 auto vbox = new wxBoxSizer(wxVERTICAL);
1024 SetSizer(vbox);
1025
1026 auto on_edit_connection = [&](ConnectionParams* p, bool editing) {
1027 if (editing)
1028 HandleEdit(p);
1029 else
1030 HandleNew(p);
1031 };
1032
1033 m_top_panel =
1034 new TopPanel(this, connections, evt_add_connection, on_edit_connection);
1035 vbox->Add(m_top_panel, wxSizerFlags(1).Expand());
1036 auto on_cancel = [&] { SwitchToGrid(); };
1037
1038 auto on_edit_click = [&](std::unique_ptr<ConnectionParams> params,
1039 bool new_mode) {
1040 HandleEditFinish(std::move(params), new_mode);
1041 };
1042
1043 m_edit_panel =
1044 AbstractConnectionEditDlg::Create(this, on_cancel, on_edit_click);
1045 vbox->Add(m_edit_panel, wxSizerFlags(1).Expand());
1046 wxWindowBase::Layout();
1047 m_edit_panel->Hide();
1048
1049 if (IsAndroid())
1050 SetScrollRate(1, 1);
1051 else
1052 SetScrollRate(10, 10);
1053 }
1054
1055 void SetColorScheme(ColorScheme cs) const {
1056 if (m_top_panel) m_top_panel->SetColorScheme(cs);
1057 }
1058
1059 void HandleEdit(ConnectionParams* p) {
1060 m_edited_connection = p;
1061 m_edit_panel->SetParams(std::make_unique<ConnectionParams>(*p));
1062 SwitchToEditor();
1063 }
1064
1065 void HandleNew(ConnectionParams*) {
1066 m_edit_panel->SetParams(nullptr);
1067 SwitchToEditor();
1068 }
1069
1070 void SwitchToEditor() {
1071 ShowScrollbars(wxSHOW_SB_NEVER, wxSHOW_SB_NEVER);
1072 m_top_panel->Hide(); // TopPanel
1073 m_edit_panel->Scroll(0, 0);
1074 DimeControl(m_edit_panel);
1075 m_edit_panel->Show();
1076 g_options->ShowOKButtons(false);
1077 Layout();
1078 }
1079
1080 void SwitchToGrid() {
1081 m_edit_panel->Hide();
1082 m_top_panel->GetConnectionsGrid()->ReloadGrid(TheConnectionParams());
1083 g_options->ShowOKButtons(true);
1084 m_top_panel->Show();
1085 Layout();
1086 FitInside();
1087 Scroll(0, 0);
1088 ShowScrollbars(wxSHOW_SB_DEFAULT, wxSHOW_SB_DEFAULT);
1089 }
1090
1091 void HandleEditFinish(std::unique_ptr<ConnectionParams> new_params,
1092 bool new_mode) {
1093 if (!new_mode) {
1094 // OK from EDIT mode
1095 StopAndRemoveCommDriver(m_edited_connection->GetStrippedDSPort(),
1096 m_edited_connection->GetCommProtocol());
1097 assert(m_edited_connection && "No edited connection");
1098 int index = m_top_panel->GetConnectionsGrid()->FindConnectionIndex(
1099 m_edited_connection);
1100 assert(index != -1 && "Cannot look up connection index");
1101 *TheConnectionParams()[index] = *new_params;
1102 TheConnectionParams()[index]->is_setup = false; // Trigger new stream
1103 m_edited_connection = nullptr;
1104 } else {
1105 // OK from NEW mode
1106 ConnectionParams cp = m_edit_panel->GetEditedParams();
1107 if (FindConnectionByIface(&cp)) {
1108 wxMessageDialog dialog(this, kInterfaceExistsMessage,
1109 _("Driver creation warning"),
1110 wxOK | wxCENTRE | wxICON_WARNING);
1111 dialog.ShowModal();
1112 }
1113 if (cp.IsPortValid()) {
1114 // Trigger new stream
1115 cp.is_setup = false;
1116 // transfer ownership FIXME use smart pointers
1117 auto new_cp = new ConnectionParams(cp);
1118 TheConnectionParams().push_back(new_cp);
1119 } else {
1120 wxString msg =
1121 _("Unable to create a connection as configured. "
1122 "Connected port or address was missing.");
1123 auto& noteman = NotificationManager::GetInstance();
1124 noteman.AddNotification(NotificationSeverity::kWarning,
1125 msg.ToStdString(), 60);
1126 }
1127 UpdateDatastreams();
1128 m_top_panel->m_evt_add_connection.Notify();
1129 }
1130
1131 SwitchToGrid();
1132 UpdateDatastreams();
1133 }
1134
1135private:
1136 const ConnectionParams* m_edited_connection;
1137 AbstractConnectionEditDlg* m_edit_panel;
1138 TopPanel* m_top_panel;
1139};
1140
1143 wxWindow* parent, const std::vector<ConnectionParams*>& connections)
1144 : wxPanel(parent, wxID_ANY), m_connections(connections) {
1145 const auto vbox = new wxBoxSizer(wxVERTICAL);
1146 vbox->Add(new EditPanel(this, connections, m_evt_add_connection),
1147 wxSizerFlags(1).Expand());
1148 SetSizer(vbox);
1149 wxWindow::Layout();
1150 wxWindow::Show();
1151}
1152
1153void ConnectionsDlg::DoApply(wxWindow* root) {
1154 for (wxWindow* child : root->GetChildren()) {
1155 if (auto widget = dynamic_cast<ApplyCancel*>(child)) widget->Apply();
1156 DoApply(child);
1157 }
1158}
1159
1160void ConnectionsDlg::DoCancel(wxWindow* root) {
1161 for (wxWindow* child : root->GetChildren()) {
1162 if (auto widget = dynamic_cast<ApplyCancel*>(child)) widget->Cancel();
1163 DoCancel(child);
1164 }
1165}
1166
1167void ConnectionsDlg::ApplySettings() { DoApply(this); }
1168
1169void ConnectionsDlg::CancelSettings() { DoCancel(this); }
1170
1171void ConnectionsDlg::SetColorScheme(ColorScheme cs) {
1172 auto w = dynamic_cast<EditPanel*>(FindWindowByName(TopScrollWindowName));
1173 if (w) w->SetColorScheme(cs);
1174}
Basic platform specific support utilities without GUI deps.
Dialog editing existing or new connection parameters.
Connection data container close to a POD struct.
Definition conn_params.h:76
bool IsPortValid() const
Return true if port data like com port or network address are sane.
std::string GetStrippedDSPort() const
Return port string with possible windows extra data removed, in some cases empty.
std::string GetKey() const
Return string unique for each instance.
wxString GetPortDirectionValueStr() const
Return translated name for direction, like _("Input").
NavAddr::Bus GetCommProtocol() const
Return NavAddr::Bus corresponding to network address/port or serial parameters.
void ApplySettings()
Make dialog's settings the active ones, usually by updating globals.
ConnectionsDlg(wxWindow *parent, const std::vector< ConnectionParams * > &connections)
Create a new ConnectionsDlg instance.
void CancelSettings()
Restore dialog settings from currently used values, usually globals.
Top window.
Generic event handling between for example MVC Model and Controller based on a shared EventVar variab...
Definition evtvar.h:78
Global color handling by name.
void MakeCommDriver(const ConnectionParams *params)
Create and register a driver for given connection.
Communication drivers factory and support.
Misc driver utilities.
bool g_always_send_rmb_rmc
Always send RMB and RMC n0183 messages even if there is no active route.
Global variables stored in configuration file.
std::vector< ConnectionParams * > & TheConnectionParams()
Return global list of connections.
Connection parameters.
Panel for editing a connection.
Runtime connection/driver state definitions.
Dialog and support code for editing a connection.
Options | Connections GUI tab managing connections
Platform independent GL includes.
Misc GUI event vars, a singleton.
General purpose GUI support.
Utility functions.
User notifications manager.
options * g_options
Global instance.
Definition options.cpp:181
Options dialog.
Input priorities management dialog.