| 1 | /* |
| 2 | RailControl - Model Railway Control Software |
| 3 | |
| 4 | Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org |
| 5 | |
| 6 | RailControl is free software; you can redistribute it and/or modify it |
| 7 | under the terms of the GNU General Public License as published by the |
| 8 | Free Software Foundation; either version 3, or (at your option) any |
| 9 | later version. |
| 10 | |
| 11 | RailControl is distributed in the hope that it will be useful, but |
| 12 | WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 14 | See the GNU General Public License for more details. |
| 15 | |
| 16 | You should have received a copy of the GNU General Public License |
| 17 | along with RailControl; see the file LICENCE. If not see |
| 18 | <http://www.gnu.org/licenses/>. |
| 19 | */ |
| 20 | |
| 21 | #include "DataModel/Feedback.h" |
| 22 | #include "Hardware/FeedbackCache.h" |
| 23 | #include "Manager.h" |
| 24 | |
| 25 | namespace Hardware |
| 26 | { |
| 27 | void FeedbackCache::Save(FeedbackCacheEntry& entry, const std::string& oldMatchKey) |
| 28 | { |
| 29 | const std::string& matchKey = entry.GetMatchKey(); |
| 30 | DataModel::Feedback* feedback = nullptr; |
| 31 | |
| 32 | const bool matchKeyChanged = matchKey.compare(oldMatchKey) != 0; |
| 33 | if (matchKeyChanged) |
| 34 | { |
| 35 | const FeedbackID feedbackId = Delete(oldMatchKey); |
| 36 | feedback = manager->GetFeedback(feedbackId); |
| 37 | } |
| 38 | |
| 39 | if (feedback == nullptr) |
| 40 | { |
| 41 | feedback = manager->GetFeedbackByMatchKey(GetControlId(), oldMatchKey); |
| 42 | } |
| 43 | |
| 44 | if (feedback == nullptr && matchKeyChanged) |
| 45 | { |
| 46 | feedback = manager->GetFeedbackByMatchKey(GetControlId(), matchKey); |
| 47 | } |
| 48 | |
| 49 | if (feedback != nullptr) |
| 50 | { |
| 51 | entry.SetFeedbackID(feedback->GetID()); |
| 52 | *feedback = entry; |
| 53 | } |
| 54 | entries.emplace(matchKey, entry); |
| 55 | } |
| 56 | |
| 57 | FeedbackID FeedbackCache::Delete(const std::string& matchKey) |
| 58 | { |
| 59 | FeedbackID feedbackId = Get(matchKey).GetFeedbackID(); |
| 60 | manager->FeedbackRemoveMatchKey(feedbackId); |
| 61 | entries.erase(matchKey); |
| 62 | return feedbackId; |
| 63 | } |
| 64 | |
| 65 | void FeedbackCache::SetFeedbackId(const FeedbackID feedbackId, const std::string& matchKey) |
| 66 | { |
| 67 | if (feedbackId != FeedbackNone) |
| 68 | { |
| 69 | for (auto& feedbackCacheEntry : entries) |
| 70 | { |
| 71 | FeedbackCacheEntry& entry = feedbackCacheEntry.second; |
| 72 | if (entry.GetFeedbackID() == feedbackId) |
| 73 | { |
| 74 | entry.SetFeedbackID(FeedbackNone); |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | auto entry = entries.find(matchKey); |
| 80 | if (entry == entries.end()) |
| 81 | { |
| 82 | return; |
| 83 | } |
| 84 | entry->second.SetFeedbackID(feedbackId); |
| 85 | } |
| 86 | } // namespace Hardware |
| 87 |