blob: e6a97fae9306aa91c05ed8e7c84f1e88c3b18193 [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#include "glass/networktables/NTStringChooser.h"
6
7#include <fmt/format.h>
8
9using namespace glass;
10
11NTStringChooserModel::NTStringChooserModel(std::string_view path)
12 : NTStringChooserModel{nt::GetDefaultInstance(), path} {}
13
14NTStringChooserModel::NTStringChooserModel(NT_Inst inst, std::string_view path)
15 : m_nt{inst},
16 m_default{m_nt.GetEntry(fmt::format("{}/default", path))},
17 m_selected{m_nt.GetEntry(fmt::format("{}/selected", path))},
18 m_active{m_nt.GetEntry(fmt::format("{}/active", path))},
19 m_options{m_nt.GetEntry(fmt::format("{}/options", path))} {
20 m_nt.AddListener(m_default);
21 m_nt.AddListener(m_selected);
22 m_nt.AddListener(m_active);
23 m_nt.AddListener(m_options);
24}
25
26void NTStringChooserModel::SetDefault(std::string_view val) {
27 nt::SetEntryValue(m_default, nt::Value::MakeString(val));
28}
29
30void NTStringChooserModel::SetSelected(std::string_view val) {
31 nt::SetEntryValue(m_selected, nt::Value::MakeString(val));
32}
33
34void NTStringChooserModel::SetActive(std::string_view val) {
35 nt::SetEntryValue(m_active, nt::Value::MakeString(val));
36}
37
38void NTStringChooserModel::SetOptions(wpi::span<const std::string> val) {
39 nt::SetEntryValue(m_options, nt::Value::MakeStringArray(val));
40}
41
42void NTStringChooserModel::Update() {
43 for (auto&& event : m_nt.PollListener()) {
44 if (event.entry == m_default) {
45 if ((event.flags & NT_NOTIFY_DELETE) != 0) {
46 m_defaultValue.clear();
47 } else if (event.value && event.value->IsString()) {
48 m_defaultValue = event.value->GetString();
49 }
50 } else if (event.entry == m_selected) {
51 if ((event.flags & NT_NOTIFY_DELETE) != 0) {
52 m_selectedValue.clear();
53 } else if (event.value && event.value->IsString()) {
54 m_selectedValue = event.value->GetString();
55 }
56 } else if (event.entry == m_active) {
57 if ((event.flags & NT_NOTIFY_DELETE) != 0) {
58 m_activeValue.clear();
59 } else if (event.value && event.value->IsString()) {
60 m_activeValue = event.value->GetString();
61 }
62 } else if (event.entry == m_options) {
63 if ((event.flags & NT_NOTIFY_DELETE) != 0) {
64 m_optionsValue.clear();
65 } else if (event.value && event.value->IsStringArray()) {
66 auto arr = event.value->GetStringArray();
67 m_optionsValue.assign(arr.begin(), arr.end());
68 }
69 }
70 }
71}
72
73bool NTStringChooserModel::Exists() {
74 return m_nt.IsConnected() && nt::GetEntryType(m_options) != NT_UNASSIGNED;
75}