1 /* 2 * Copyright (C) 2019 Emeric Poupon 3 * 4 * This file is part of LMS. 5 * 6 * LMS is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * 11 * LMS is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with LMS. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 #pragma once 21 22 #include <optional> 23 24 #include <Wt/WStringListModel.h> 25 26 namespace UserInterface { 27 28 // Helper class 29 template <typename T> 30 class ValueStringModel : public Wt::WStringListModel 31 { 32 public: 33 getValue(std::size_t row) const34 T getValue(std::size_t row) const 35 { 36 return Wt::cpp17::any_cast<T>(data(index(static_cast<int>(row), 0), Wt::ItemDataRole::User)); 37 } 38 getString(std::size_t row) const39 Wt::WString getString(std::size_t row) const 40 { 41 return Wt::cpp17::any_cast<Wt::WString>(data(index(static_cast<int>(row), 0), Wt::ItemDataRole::Display)); 42 } 43 44 std::optional<std::size_t> getRowFromString(const Wt::WString & value)45 getRowFromString(const Wt::WString& value) 46 { 47 for (std::size_t i{}; i < static_cast<std::size_t>(rowCount()); ++i) 48 { 49 if (getString(i) == value) 50 return i; 51 } 52 53 return std::nullopt; 54 } 55 56 std::optional<std::size_t> getRowFromValue(const T & value)57 getRowFromValue(const T& value) 58 { 59 for (std::size_t i{}; i < static_cast<std::size_t>(rowCount()); ++i) 60 { 61 if (getValue(i) == value) 62 return i; 63 } 64 65 return std::nullopt; 66 } 67 68 void add(const Wt::WString & str,const T & value)69 add(const Wt::WString& str, const T& value) 70 { 71 insertRows(rowCount(), 1); 72 setData(rowCount() - 1, 0, value, Wt::ItemDataRole::User); 73 setData(rowCount() - 1, 0, str, Wt::ItemDataRole::Display); 74 } 75 76 void clear()77 clear() 78 { 79 removeRows(0, rowCount()); 80 } 81 82 }; 83 84 } // namespace UserInterface 85