OpenCPN Partial API docs
Loading...
Searching...
No Matches
udev_rule_mgr.cpp
Go to the documentation of this file.
1
2/**************************************************************************
3 * Copyright (C) 2021 Alec Leamas *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
17 ***************************************************************************/
18
24#include "config.h"
25
26#include <algorithm>
27#include <cassert>
28#include <sstream>
29#include <vector>
30
31#include <stdlib.h>
32
33#include <wx/button.h>
34#include <wx/checkbox.h>
35#include <wx/dcclient.h>
36#include <wx/dialog.h>
37#include <wx/frame.h>
38#include <wx/panel.h>
39#include <wx/sizer.h>
40#include <wx/statline.h>
41#include <wx/stattext.h>
42#include <wx/textctrl.h>
43
44#include "model/linux_devices.h"
45#include "model/logger.h"
47#include "model/ocpn_utils.h"
48
49#include "expand_panel.h"
50#include "gui_lib.h"
51#include "udev_rule_mgr.h"
52
53#if !defined(__linux__) || defined(__ANDROID__)
54
55// non-linux platforms: Empty place holders.
56bool CheckDongleAccess(wxWindow* parent) { return true; }
57bool CheckSerialAccess(wxWindow* parent, const std::string device) {
58 return true;
59}
61
62#else
63
64static bool hide_dongle_dialog;
65static bool hide_device_dialog;
66
67static const char* const DONGLE_INTRO = _(R"(
68An OpenCPN dongle is detected but cannot be used due to missing permissions.
69
70This problem can be fixed by installing a udev rules file. Once installed,
71it will ensure that the dongle permissions are OK.
72)");
73
74static const char* const FLATPAK_INTRO_TRAILER = _(R"(
75
76On flatpak, this must be done using the manual command instructions below
77)");
78
79static const char* const DEVICE_INTRO = _(R"(
80The device @DEVICE@ exists but cannot be used due to missing permissions.
81
82This problem can be fixed by installing a udev rules file. Once installed,
83the rules file will fix the permissions problem.
84)");
85
86static const char* const DEVICE_LINK_INTRO = _(R"(
87
88It will also create a new device called @SYMLINK@. It is recommended to use
89@SYMLINK@ instead of @DEVICE@ to avoid problems with changing device names,
90in particular on laptops.
91)");
92
93static const char* const HIDE_DIALOG_LABEL =
94 _("Do not show this dialog next time");
95
96static const char* const RULE_SUCCESS_TTYS_MSG = _(R"(
97Rule successfully installed. To activate the new rule restart the system.
98)");
99
100static const char* const RULE_SUCCESS_MSG = _(R"(
101Rule successfully installed. To activate the new rule restart system or:
102- Exit opencpn.
103- Unplug and re-insert the USB device.
104- Restart opencpn
105)");
106
107static const char* const FLATPAK_INSTALL_MSG = _(R"(
108To do after installing the rule according to instructions:
109- Exit opencpn.
110- Unplug and re-insert the USB device.
111- Restart opencpn
112)");
113
114static const char* const DEVICE_NOT_FOUND =
115 _("The device @device@ can not be found (disconnected?)");
116
117static const char* const INSTRUCTIONS = "@pkexec@ cp @PATH@ /etc/udev/rules.d";
118
120class DeviceNotFoundDlg : public wxFrame {
121public:
123 static void Create(wxWindow* parent, const std::string& device) {
124 wxWindow* dlg = new DeviceNotFoundDlg(parent, device);
125 dlg->Show();
126 }
127
129 static void DestroyOpenWindows() {
130 for (const auto& name : open_windows) {
131 auto window = wxWindow::FindWindowByName(name);
132 if (window) window->Destroy();
133 }
134 open_windows.clear();
135 }
136
137private:
138 static std::vector<std::string> open_windows;
139
140 class ButtonsSizer : public wxStdDialogButtonSizer {
141 public:
142 ButtonsSizer(DeviceNotFoundDlg* parent) : wxStdDialogButtonSizer() {
143 auto button = new wxButton(parent, wxID_OK);
144 AddButton(button);
145 Realize();
146 }
147 };
148
149 DeviceNotFoundDlg(wxWindow* parent, const std::string& device)
150 : wxFrame(parent, wxID_ANY, _("Opencpn: device not found"),
151 wxDefaultPosition, wxDefaultSize,
152 wxDEFAULT_FRAME_STYLE | wxFRAME_FLOAT_ON_PARENT) {
153 std::stringstream ss;
154 ss << "dlg-id-" << rand();
155 SetName(ss.str());
156 open_windows.push_back(ss.str());
157
158 Bind(wxEVT_CLOSE_WINDOW, [&](wxCloseEvent& e) {
159 OnClose();
160 e.Skip();
161 });
162 Bind(wxEVT_COMMAND_BUTTON_CLICKED, [&](wxCommandEvent&) { OnClose(); });
163
164 auto vbox = new wxBoxSizer(wxVERTICAL);
165 SetSizer(vbox);
166 auto flags = wxSizerFlags().Expand().Border();
167 std::string txt(DEVICE_NOT_FOUND);
168 ocpn::replace(txt, "@device@", device);
169 vbox->Add(0, 0, 1); // vertical space
170 vbox->Add(new wxStaticText(this, wxID_ANY, txt), flags);
171 vbox->Add(0, 0, 1);
172 vbox->Add(new wxStaticLine(this), wxSizerFlags().Expand());
173 vbox->Add(new ButtonsSizer(this), flags);
174 Layout();
175 CenterOnScreen();
176 SetFocus();
177 }
178
179 void OnClose() {
180 const std::string name(GetName().ToStdString());
181 auto found =
182 std::find_if(open_windows.begin(), open_windows.end(),
183 [name](const std::string& s) { return s == name; });
184 assert(found != std::end(open_windows) &&
185 "Cannot find dialog in window list");
186 open_windows.erase(found);
187 Destroy();
188 }
189};
190
191std::vector<std::string> DeviceNotFoundDlg::open_windows;
192
193void DestroyDeviceNotFoundDialogs() { DeviceNotFoundDlg::DestroyOpenWindows(); }
194
196class HideCheckbox : public wxCheckBox {
197public:
198 HideCheckbox(wxWindow* parent, const char* label, bool* state)
199 : wxCheckBox(parent, wxID_ANY, label, wxDefaultPosition, wxDefaultSize,
200 wxALIGN_LEFT),
201 m_state(state) {
202 SetValue(*state);
203 Bind(wxEVT_CHECKBOX,
204 [&](wxCommandEvent& ev) { *m_state = ev.IsChecked(); });
205 }
206
207private:
208 bool* m_state;
209};
210
212class HidePanel : public wxPanel {
213public:
214 HidePanel(wxWindow* parent, const char* label, bool* state)
215 : wxPanel(parent) {
216 auto hbox = new wxBoxSizer(wxHORIZONTAL);
217 hbox->Add(new HideCheckbox(this, label, state), wxSizerFlags().Expand());
218 SetSizer(hbox);
219 Fit();
220 Show();
221 }
222};
223
225class ManualInstructions : public ExpandablePanel {
226public:
227 ManualInstructions(wxWindow* parent, const char* cmd)
228 : ExpandablePanel(parent, nullptr) {
229 Create(GetCmd(parent, cmd));
230 auto flags = wxSizerFlags().Expand();
231 auto hbox = new wxBoxSizer(wxHORIZONTAL);
232
233 const char* label = _("Manual command line instructions");
234 hbox->Add(new wxStaticText(this, wxID_ANY, label), flags);
235 hbox->Add(GetIcon());
236
237 auto vbox = new wxBoxSizer(wxVERTICAL);
238 vbox->Add(hbox);
239 flags = flags.Border(wxLEFT);
240 vbox->Add(GetChild(), flags.ReserveSpaceEvenIfHidden());
241
242 SetSizer(vbox);
243 SetAutoLayout(true);
244 Show();
245 }
246
247private:
248 wxTextCtrl* GetCmd(wxWindow* parent, const char* tmpl) {
249 std::string cmd(tmpl);
250 ocpn::replace(cmd, "@PATH@", GetDongleRule());
251 auto ctrl = new CopyableText(this, cmd.c_str());
252 ctrl->SetMinSize(parent->GetTextExtent(cmd + "aaa"));
253 return ctrl;
254 }
255 wxWindow* m_parent;
256};
257
259class ReviewRule : public ExpandablePanel {
260public:
261 ReviewRule(wxWindow* parent, const std::string& rule)
262 : ExpandablePanel(parent) {
263 int from = rule[0] == '\n' ? 1 : 0;
264 Create(new wxStaticText(this, wxID_ANY, rule.substr(from)));
265
266 auto flags = wxSizerFlags().Expand();
267 auto hbox = new wxBoxSizer(wxHORIZONTAL);
268 hbox->Add(new wxStaticText(this, wxID_ANY, _("Review rule")), flags);
269 hbox->Add(GetIcon(), flags);
270 auto vbox = new wxBoxSizer(wxVERTICAL);
271 vbox->Add(hbox);
272 auto indent = parent->GetTextExtent("ABCDE").GetWidth();
273 flags = flags.Border(wxLEFT, indent);
274
275 vbox->Add(GetChild(), flags.ReserveSpaceEvenIfHidden());
276 SetSizer(vbox);
277 SetAutoLayout(true);
278 Show();
279 }
280};
281
283static std::string GetRule(const std::string& path) {
284 std::ifstream input(path.c_str());
285 std::ostringstream buf;
286 buf << input.rdbuf();
287 input.close();
288 if (input.bad()) {
289 WARNING_LOG << "Cannot open rule file: " << path;
290 }
291 return buf.str();
292}
293
295class DongleInfoPanel : public wxPanel {
296public:
297 DongleInfoPanel(wxWindow* parent) : wxPanel(parent) {
298 std::string cmd(INSTRUCTIONS);
299 std::string rule_path(GetDongleRule());
300 ocpn::replace(cmd, "@PATH@", rule_path.c_str());
301 ocpn::replace(cmd, "@pkexec@", "sudo");
302 auto vbox = new wxBoxSizer(wxVERTICAL);
303 vbox->Add(new ManualInstructions(this, cmd.c_str()));
304 std::string rule_text = GetRule(rule_path);
305 vbox->Add(new ReviewRule(this, rule_text.c_str()));
306 SetAutoLayout(true);
307 SetSizer(vbox);
308 }
309};
310
312class DeviceInfoPanel : public wxPanel {
313public:
314 DeviceInfoPanel(wxWindow* parent, const std::string rule_path)
315 : wxPanel(parent) {
316 std::string cmd(INSTRUCTIONS);
317 ocpn::replace(cmd, "@PATH@", rule_path.c_str());
318 ocpn::replace(cmd, "@pkexec@", "sudo");
319 auto vbox = new wxBoxSizer(wxVERTICAL);
320 vbox->Add(new ManualInstructions(this, cmd.c_str()));
321 vbox->Add(new ReviewRule(this, GetRule(rule_path)));
322 SetAutoLayout(true);
323 SetSizer(vbox);
324 }
325};
326
328class Buttons : public wxPanel {
329public:
330 Buttons(wxWindow* parent, const char* rule_path)
331 : wxPanel(parent), m_rule_path(rule_path) {
332 auto sizer = new wxBoxSizer(wxHORIZONTAL);
333 auto flags = wxSizerFlags().Bottom().Border(wxLEFT);
334 sizer->Add(1, 1, 100, wxEXPAND); // Expanding spacer
335 auto install = new wxButton(this, wxID_ANY, _("Install rule"));
336 install->Bind(wxEVT_COMMAND_BUTTON_CLICKED,
337 [&](wxCommandEvent& ev) { DoInstall(); });
338 install->Enable(getenv("FLATPAK_ID") == NULL);
339 sizer->Add(install, flags);
340 auto quit = new wxButton(this, wxID_EXIT, _("Quit"));
341 quit->Bind(wxEVT_COMMAND_BUTTON_CLICKED, [&](wxCommandEvent& ev) {
342 if (getenv("FLATPAK_ID")) {
343 auto flags = wxOK | wxICON_INFORMATION;
344 auto msg = FLATPAK_INSTALL_MSG;
345 OCPNMessageBox(this, msg, _("OpenCPN"), flags);
346 }
347 dynamic_cast<wxDialog*>(GetParent())->EndModal(0);
348 });
349 sizer->Add(quit, flags);
350 SetSizer(sizer);
351 Fit();
352 Show();
353 }
354
355 void DoInstall() {
356 using namespace std;
357 string cmd(INSTRUCTIONS);
358 ocpn::replace(cmd, "@PATH@", m_rule_path);
359 ocpn::replace(cmd, "@pkexec@", "sudo");
360 ifstream f(m_rule_path);
361 auto rule =
362 string(istreambuf_iterator<char>(f), istreambuf_iterator<char>());
363 int sts = system(cmd.c_str());
364 int flags = wxOK | wxICON_WARNING;
365 const char* msg = _("Errors encountered installing rule.");
366 if (WIFEXITED(sts) && WEXITSTATUS(sts) == 0) {
367 if (rule.find("ttyS") != std::string::npos) {
368 msg = RULE_SUCCESS_TTYS_MSG;
369 } else {
370 msg = RULE_SUCCESS_MSG;
371 }
372 flags = wxOK | wxICON_INFORMATION;
373 }
374 OCPNMessageBox(this, msg, _("OpenCPN Info"), flags);
375 }
376
377private:
378 std::string m_rule_path;
379};
380
382class DongleRuleDialog : public wxDialog {
383public:
384 DongleRuleDialog(wxWindow* parent)
385 : wxDialog(parent, wxID_ANY, _("Manage dongle udev rule")) {
386 auto sizer = new wxBoxSizer(wxVERTICAL);
387 auto flags = wxSizerFlags().Expand().Border();
388 std::string intro(DONGLE_INTRO);
389 if (getenv("FLATPAK_ID")) {
390 intro += FLATPAK_INTRO_TRAILER;
391 }
392 sizer->Add(new wxStaticText(this, wxID_ANY, intro), flags);
393 sizer->Add(new wxStaticLine(this), flags);
394 sizer->Add(new DongleInfoPanel(this), flags);
395 sizer->Add(new HidePanel(this, HIDE_DIALOG_LABEL, &hide_dongle_dialog),
396 flags.Left());
397 sizer->Add(new wxStaticLine(this), flags);
398 sizer->Add(new Buttons(this, GetDongleRule().c_str()), flags);
399 SetSizer(sizer);
400 SetAutoLayout(true);
401 Fit();
402 }
403};
404
406static std::string GetDeviceIntro(const char* device, std::string symlink) {
407 std::string intro(DEVICE_INTRO);
408
409 std::string dev_name(device);
410 ocpn::replace(dev_name, "/dev/", "");
411 if (!ocpn::startswith(dev_name, "ttyS")) {
412 intro += DEVICE_LINK_INTRO;
413 }
414 if (getenv("FLATPAK_ID")) {
415 intro += FLATPAK_INTRO_TRAILER;
416 }
417 ocpn::replace(symlink, "/dev/", "");
418 while (intro.find("@SYMLINK@") != std::string::npos) {
419 ocpn::replace(intro, "@SYMLINK@", symlink);
420 }
421 while (intro.find("@DEVICE@") != std::string::npos) {
422 ocpn::replace(intro, "@DEVICE@", dev_name.c_str());
423 }
424 return intro;
425}
426
428class DeviceRuleDialog : public wxDialog {
429public:
430 DeviceRuleDialog(wxWindow* parent, const char* device_path)
431 : wxDialog(parent, wxID_ANY, _("Manage device udev rule")) {
432 auto sizer = new wxBoxSizer(wxVERTICAL);
433 auto flags = wxSizerFlags().Expand().Border();
434
435 std::string symlink(MakeUdevLink());
436 auto intro = GetDeviceIntro(device_path, symlink.c_str());
437 auto rule_path = GetDeviceRule(device_path, symlink.c_str());
438 sizer->Add(new wxStaticText(this, wxID_ANY, intro), flags);
439 sizer->Add(new wxStaticLine(this), flags);
440 sizer->Add(new DeviceInfoPanel(this, rule_path), flags);
441 sizer->Add(new HidePanel(this, HIDE_DIALOG_LABEL, &hide_device_dialog),
442 flags);
443 sizer->Add(new wxStaticLine(this), flags);
444 sizer->Add(new Buttons(this, rule_path.c_str()), flags);
445
446 SetSizer(sizer);
447 SetAutoLayout(true);
448 Fit();
449 }
450};
451
452bool CheckSerialAccess(wxWindow* parent, const std::string device) {
453 if (hide_device_dialog) {
454 return true;
455 }
456 if (!ocpn::exists(device)) {
457 auto& noteman = NotificationManager::GetInstance();
458 std::string msg = "Device not found: ";
459 msg += device;
460 noteman.AddNotification(NotificationSeverity::kInformational, msg, 60);
461 return false;
462 }
463 int result = 0;
464 if (!IsDevicePermissionsOk(device.c_str())) {
465 auto dialog = new DeviceRuleDialog(parent, device.c_str());
466 result = dialog->ShowModal();
467 delete dialog;
468 }
469 return result == 0;
470}
471
472bool CheckDongleAccess(wxWindow* parent) {
473 int result = 0;
474 if (IsDonglePermissionsWrong() && !hide_dongle_dialog) {
475 auto dialog = new DongleRuleDialog(parent);
476 result = dialog->ShowModal();
477 delete dialog;
478 }
479 return result == 0;
480}
481
482#endif // !defined(__linux__) || defined(__ANDROID__)
The Done button.
Non-editable TextCtrl, used like wxStaticText but is copyable.
Definition gui_lib.h:38
An ExpandIcon together with a child window.
void Create(wxWindow *child, std::function< void()> on_resize=[] {})
Second part of two step creation.
wxWindow * GetIcon() const
Return the ExpandableIcon reflecting expanded/collapsed state.
wxWindow * GetChild() const
Return the managed window which is shown or hidden.
General purpose GUI support.
std::string MakeUdevLink()
Get next available udev rule base name.
bool IsDevicePermissionsOk(const char *path)
Check device path permissions.
std::string GetDongleRule()
std::string GetDeviceRule(const char *device, const char *symlink)
Get device udev rule.
bool IsDonglePermissionsWrong()
Return true if an existing dongle cannot be accessed.
Implement linux_devices.h – low level udev usb device management (Linux only).
Enhanced logging interface on top of wx/log.h.
bool replace(std::string &str, const std::string &from, const std::string &to)
Perform in place substitution in str, replacing "from" with "to".
bool startswith(const std::string &str, const std::string &prefix)
Return true if s starts with given prefix.
bool exists(const std::string &name)
User notifications manager.
Miscellaneous utilities, many of which string related.
void DestroyDeviceNotFoundDialogs()
Destroy all open "Device not found" dialog windows.
bool CheckDongleAccess(wxWindow *parent)
Runs checks and if required dialogs to make dongle accessible.
bool CheckSerialAccess(wxWindow *parent, const std::string device)
Run checks and possible dialogs to ensure device is accessible.
Access checks for comm devices and dongle.