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 "libgui/expand_panel.h"
45
46#include "model/linux_devices.h"
47#include "model/logger.h"
49#include "model/ocpn_utils.h"
50
51#include "gui_lib.h"
52#include "udev_rule_mgr.h"
53
54#if !defined(__linux__) || defined(__ANDROID__)
55
56// non-linux platforms: Empty place holders.
57bool CheckDongleAccess(wxWindow* parent) { return true; }
58bool CheckSerialAccess(wxWindow* parent, const std::string device) {
59 return true;
60}
62
63#else
64
65static bool hide_dongle_dialog;
66static bool hide_device_dialog;
67
68static const char* const DONGLE_INTRO = _(R"(
69An OpenCPN dongle is detected but cannot be used due to missing permissions.
70
71This problem can be fixed by installing a udev rules file. Once installed,
72it will ensure that the dongle permissions are OK.
73)");
74
75static const char* const FLATPAK_INTRO_TRAILER = _(R"(
76
77On flatpak, this must be done using the manual command instructions below
78)");
79
80static const char* const DEVICE_INTRO = _(R"(
81The device @DEVICE@ exists but cannot be used due to missing permissions.
82
83This problem can be fixed by installing a udev rules file. Once installed,
84the rules file will fix the permissions problem.
85)");
86
87static const char* const DEVICE_LINK_INTRO = _(R"(
88
89It will also create a new device called @SYMLINK@. It is recommended to use
90@SYMLINK@ instead of @DEVICE@ to avoid problems with changing device names,
91in particular on laptops.
92)");
93
94static const char* const HIDE_DIALOG_LABEL =
95 _("Do not show this dialog next time");
96
97static const char* const RULE_SUCCESS_TTYS_MSG = _(R"(
98Rule successfully installed. To activate the new rule restart the system.
99)");
100
101static const char* const RULE_SUCCESS_MSG = _(R"(
102Rule successfully installed. To activate the new rule restart system or:
103- Exit opencpn.
104- Unplug and re-insert the USB device.
105- Restart opencpn
106)");
107
108static const char* const FLATPAK_INSTALL_MSG = _(R"(
109To do after installing the rule according to instructions:
110- Exit opencpn.
111- Unplug and re-insert the USB device.
112- Restart opencpn
113)");
114
115static const char* const DEVICE_NOT_FOUND =
116 _("The device @device@ can not be found (disconnected?)");
117
118static const char* const INSTRUCTIONS = "@pkexec@ cp @PATH@ /etc/udev/rules.d";
119
121class DeviceNotFoundDlg : public wxFrame {
122public:
124 static void Create(wxWindow* parent, const std::string& device) {
125 wxWindow* dlg = new DeviceNotFoundDlg(parent, device);
126 dlg->Show();
127 }
128
130 static void DestroyOpenWindows() {
131 for (const auto& name : open_windows) {
132 auto window = wxWindow::FindWindowByName(name);
133 if (window) window->Destroy();
134 }
135 open_windows.clear();
136 }
137
138private:
139 static std::vector<std::string> open_windows;
140
141 class ButtonsSizer : public wxStdDialogButtonSizer {
142 public:
143 ButtonsSizer(DeviceNotFoundDlg* parent) : wxStdDialogButtonSizer() {
144 auto button = new wxButton(parent, wxID_OK);
145 AddButton(button);
146 Realize();
147 }
148 };
149
150 DeviceNotFoundDlg(wxWindow* parent, const std::string& device)
151 : wxFrame(parent, wxID_ANY, _("Opencpn: device not found"),
152 wxDefaultPosition, wxDefaultSize,
153 wxDEFAULT_FRAME_STYLE | wxFRAME_FLOAT_ON_PARENT) {
154 std::stringstream ss;
155 ss << "dlg-id-" << rand();
156 SetName(ss.str());
157 open_windows.push_back(ss.str());
158
159 Bind(wxEVT_CLOSE_WINDOW, [&](wxCloseEvent& e) {
160 OnClose();
161 e.Skip();
162 });
163 Bind(wxEVT_COMMAND_BUTTON_CLICKED, [&](wxCommandEvent&) { OnClose(); });
164
165 auto vbox = new wxBoxSizer(wxVERTICAL);
166 SetSizer(vbox);
167 auto flags = wxSizerFlags().Expand().Border();
168 std::string txt(DEVICE_NOT_FOUND);
169 ocpn::replace(txt, "@device@", device);
170 vbox->Add(0, 0, 1); // vertical space
171 vbox->Add(new wxStaticText(this, wxID_ANY, txt), flags);
172 vbox->Add(0, 0, 1);
173 vbox->Add(new wxStaticLine(this), wxSizerFlags().Expand());
174 vbox->Add(new ButtonsSizer(this), flags);
175 Layout();
176 CenterOnScreen();
177 SetFocus();
178 }
179
180 void OnClose() {
181 const std::string name(GetName().ToStdString());
182 auto found =
183 std::find_if(open_windows.begin(), open_windows.end(),
184 [name](const std::string& s) { return s == name; });
185 assert(found != std::end(open_windows) &&
186 "Cannot find dialog in window list");
187 open_windows.erase(found);
188 Destroy();
189 }
190};
191
192std::vector<std::string> DeviceNotFoundDlg::open_windows;
193
194void DestroyDeviceNotFoundDialogs() { DeviceNotFoundDlg::DestroyOpenWindows(); }
195
197class HideCheckbox : public wxCheckBox {
198public:
199 HideCheckbox(wxWindow* parent, const char* label, bool* state)
200 : wxCheckBox(parent, wxID_ANY, label, wxDefaultPosition, wxDefaultSize,
201 wxALIGN_LEFT),
202 m_state(state) {
203 SetValue(*state);
204 Bind(wxEVT_CHECKBOX,
205 [&](wxCommandEvent& ev) { *m_state = ev.IsChecked(); });
206 }
207
208private:
209 bool* m_state;
210};
211
213class HidePanel : public wxPanel {
214public:
215 HidePanel(wxWindow* parent, const char* label, bool* state)
216 : wxPanel(parent) {
217 auto hbox = new wxBoxSizer(wxHORIZONTAL);
218 hbox->Add(new HideCheckbox(this, label, state), wxSizerFlags().Expand());
219 SetSizer(hbox);
220 Fit();
221 Show();
222 }
223};
224
226class ManualInstructions : public ExpandablePanel {
227public:
228 ManualInstructions(wxWindow* parent, const char* cmd)
229 : ExpandablePanel(parent, nullptr) {
230 Create(GetCmd(parent, cmd));
231 auto flags = wxSizerFlags().Expand();
232 auto hbox = new wxBoxSizer(wxHORIZONTAL);
233
234 const char* label = _("Manual command line instructions");
235 hbox->Add(new wxStaticText(this, wxID_ANY, label), flags);
236 hbox->Add(GetIcon());
237
238 auto vbox = new wxBoxSizer(wxVERTICAL);
239 vbox->Add(hbox);
240 flags = flags.Border(wxLEFT);
241 vbox->Add(GetChild(), flags.ReserveSpaceEvenIfHidden());
242
243 SetSizer(vbox);
244 SetAutoLayout(true);
245 Show();
246 }
247
248private:
249 wxTextCtrl* GetCmd(wxWindow* parent, const char* tmpl) {
250 std::string cmd(tmpl);
251 ocpn::replace(cmd, "@PATH@", GetDongleRule());
252 auto ctrl = new CopyableText(this, cmd.c_str());
253 ctrl->SetMinSize(parent->GetTextExtent(cmd + "aaa"));
254 return ctrl;
255 }
256 wxWindow* m_parent;
257};
258
260class ReviewRule : public ExpandablePanel {
261public:
262 ReviewRule(wxWindow* parent, const std::string& rule)
263 : ExpandablePanel(parent) {
264 int from = rule[0] == '\n' ? 1 : 0;
265 Create(new wxStaticText(this, wxID_ANY, rule.substr(from)));
266
267 auto flags = wxSizerFlags().Expand();
268 auto hbox = new wxBoxSizer(wxHORIZONTAL);
269 hbox->Add(new wxStaticText(this, wxID_ANY, _("Review rule")), flags);
270 hbox->Add(GetIcon(), flags);
271 auto vbox = new wxBoxSizer(wxVERTICAL);
272 vbox->Add(hbox);
273 auto indent = parent->GetTextExtent("ABCDE").GetWidth();
274 flags = flags.Border(wxLEFT, indent);
275
276 vbox->Add(GetChild(), flags.ReserveSpaceEvenIfHidden());
277 SetSizer(vbox);
278 SetAutoLayout(true);
279 Show();
280 }
281};
282
284static std::string GetRule(const std::string& path) {
285 std::ifstream input(path.c_str());
286 std::ostringstream buf;
287 buf << input.rdbuf();
288 input.close();
289 if (input.bad()) {
290 WARNING_LOG << "Cannot open rule file: " << path;
291 }
292 return buf.str();
293}
294
296class DongleInfoPanel : public wxPanel {
297public:
298 DongleInfoPanel(wxWindow* parent) : wxPanel(parent) {
299 std::string cmd(INSTRUCTIONS);
300 std::string rule_path(GetDongleRule());
301 ocpn::replace(cmd, "@PATH@", rule_path.c_str());
302 ocpn::replace(cmd, "@pkexec@", "sudo");
303 auto vbox = new wxBoxSizer(wxVERTICAL);
304 vbox->Add(new ManualInstructions(this, cmd.c_str()));
305 std::string rule_text = GetRule(rule_path);
306 vbox->Add(new ReviewRule(this, rule_text.c_str()));
307 SetAutoLayout(true);
308 SetSizer(vbox);
309 }
310};
311
313class DeviceInfoPanel : public wxPanel {
314public:
315 DeviceInfoPanel(wxWindow* parent, const std::string rule_path)
316 : wxPanel(parent) {
317 std::string cmd(INSTRUCTIONS);
318 ocpn::replace(cmd, "@PATH@", rule_path.c_str());
319 ocpn::replace(cmd, "@pkexec@", "sudo");
320 auto vbox = new wxBoxSizer(wxVERTICAL);
321 vbox->Add(new ManualInstructions(this, cmd.c_str()));
322 vbox->Add(new ReviewRule(this, GetRule(rule_path)));
323 SetAutoLayout(true);
324 SetSizer(vbox);
325 }
326};
327
329class Buttons : public wxPanel {
330public:
331 Buttons(wxWindow* parent, const char* rule_path)
332 : wxPanel(parent), m_rule_path(rule_path) {
333 auto sizer = new wxBoxSizer(wxHORIZONTAL);
334 auto flags = wxSizerFlags().Bottom().Border(wxLEFT);
335 sizer->Add(1, 1, 100, wxEXPAND); // Expanding spacer
336 auto install = new wxButton(this, wxID_ANY, _("Install rule"));
337 install->Bind(wxEVT_COMMAND_BUTTON_CLICKED,
338 [&](wxCommandEvent& ev) { DoInstall(); });
339 install->Enable(getenv("FLATPAK_ID") == NULL);
340 sizer->Add(install, flags);
341 auto quit = new wxButton(this, wxID_EXIT, _("Quit"));
342 quit->Bind(wxEVT_COMMAND_BUTTON_CLICKED, [&](wxCommandEvent& ev) {
343 if (getenv("FLATPAK_ID")) {
344 auto flags = wxOK | wxICON_INFORMATION;
345 auto msg = FLATPAK_INSTALL_MSG;
346 OCPNMessageBox(this, msg, _("OpenCPN"), flags);
347 }
348 dynamic_cast<wxDialog*>(GetParent())->EndModal(0);
349 });
350 sizer->Add(quit, flags);
351 SetSizer(sizer);
352 Fit();
353 Show();
354 }
355
356 void DoInstall() {
357 using namespace std;
358 string cmd(INSTRUCTIONS);
359 ocpn::replace(cmd, "@PATH@", m_rule_path);
360 ocpn::replace(cmd, "@pkexec@", "sudo");
361 ifstream f(m_rule_path);
362 auto rule =
363 string(istreambuf_iterator<char>(f), istreambuf_iterator<char>());
364 int sts = system(cmd.c_str());
365 int flags = wxOK | wxICON_WARNING;
366 const char* msg = _("Errors encountered installing rule.");
367 if (WIFEXITED(sts) && WEXITSTATUS(sts) == 0) {
368 if (rule.find("ttyS") != std::string::npos) {
369 msg = RULE_SUCCESS_TTYS_MSG;
370 } else {
371 msg = RULE_SUCCESS_MSG;
372 }
373 flags = wxOK | wxICON_INFORMATION;
374 }
375 OCPNMessageBox(this, msg, _("OpenCPN Info"), flags);
376 }
377
378private:
379 std::string m_rule_path;
380};
381
383class DongleRuleDialog : public wxDialog {
384public:
385 DongleRuleDialog(wxWindow* parent)
386 : wxDialog(parent, wxID_ANY, _("Manage dongle udev rule")) {
387 auto sizer = new wxBoxSizer(wxVERTICAL);
388 auto flags = wxSizerFlags().Expand().Border();
389 std::string intro(DONGLE_INTRO);
390 if (getenv("FLATPAK_ID")) {
391 intro += FLATPAK_INTRO_TRAILER;
392 }
393 sizer->Add(new wxStaticText(this, wxID_ANY, intro), flags);
394 sizer->Add(new wxStaticLine(this), flags);
395 sizer->Add(new DongleInfoPanel(this), flags);
396 sizer->Add(new HidePanel(this, HIDE_DIALOG_LABEL, &hide_dongle_dialog),
397 flags.Left());
398 sizer->Add(new wxStaticLine(this), flags);
399 sizer->Add(new Buttons(this, GetDongleRule().c_str()), flags);
400 SetSizer(sizer);
401 SetAutoLayout(true);
402 Fit();
403 }
404};
405
407static std::string GetDeviceIntro(const char* device, std::string symlink) {
408 std::string intro(DEVICE_INTRO);
409
410 std::string dev_name(device);
411 ocpn::replace(dev_name, "/dev/", "");
412 if (!ocpn::startswith(dev_name, "ttyS")) {
413 intro += DEVICE_LINK_INTRO;
414 }
415 if (getenv("FLATPAK_ID")) {
416 intro += FLATPAK_INTRO_TRAILER;
417 }
418 ocpn::replace(symlink, "/dev/", "");
419 while (intro.find("@SYMLINK@") != std::string::npos) {
420 ocpn::replace(intro, "@SYMLINK@", symlink);
421 }
422 while (intro.find("@DEVICE@") != std::string::npos) {
423 ocpn::replace(intro, "@DEVICE@", dev_name.c_str());
424 }
425 return intro;
426}
427
429class DeviceRuleDialog : public wxDialog {
430public:
431 DeviceRuleDialog(wxWindow* parent, const char* device_path)
432 : wxDialog(parent, wxID_ANY, _("Manage device udev rule")) {
433 auto sizer = new wxBoxSizer(wxVERTICAL);
434 auto flags = wxSizerFlags().Expand().Border();
435
436 std::string symlink(MakeUdevLink());
437 auto intro = GetDeviceIntro(device_path, symlink.c_str());
438 auto rule_path = GetDeviceRule(device_path, symlink.c_str());
439 sizer->Add(new wxStaticText(this, wxID_ANY, intro), flags);
440 sizer->Add(new wxStaticLine(this), flags);
441 sizer->Add(new DeviceInfoPanel(this, rule_path), flags);
442 sizer->Add(new HidePanel(this, HIDE_DIALOG_LABEL, &hide_device_dialog),
443 flags);
444 sizer->Add(new wxStaticLine(this), flags);
445 sizer->Add(new Buttons(this, rule_path.c_str()), flags);
446
447 SetSizer(sizer);
448 SetAutoLayout(true);
449 Fit();
450 }
451};
452
453bool CheckSerialAccess(wxWindow* parent, const std::string device) {
454 if (hide_device_dialog) {
455 return true;
456 }
457 if (!ocpn::exists(device)) {
458 auto& noteman = NotificationManager::GetInstance();
459 std::string msg = "Device not found: ";
460 msg += device;
461 noteman.AddNotification(NotificationSeverity::kInformational, msg, 60);
462 return false;
463 }
464 int result = 0;
465 if (!IsDevicePermissionsOk(device.c_str())) {
466 auto dialog = new DeviceRuleDialog(parent, device.c_str());
467 result = dialog->ShowModal();
468 delete dialog;
469 }
470 return result == 0;
471}
472
473bool CheckDongleAccess(wxWindow* parent) {
474 int result = 0;
475 if (IsDonglePermissionsWrong() && !hide_dongle_dialog) {
476 auto dialog = new DongleRuleDialog(parent);
477 result = dialog->ShowModal();
478 delete dialog;
479 }
480 return result == 0;
481}
482
483#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.