Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
GUINewsFeed.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2026-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
18// Fetches the SUMO release news RSS feed in the background (sumo-gui, netedit)
19/****************************************************************************/
20#include <config.h>
21
22#include <iomanip>
23#include <regex>
24#include <sstream>
25#ifdef HAVE_CURL
26#include <curl/curl.h>
27#endif
28
35
36#include "GUINewsFeed.h"
37
38
39// ===========================================================================
40// constants
41// ===========================================================================
42const std::string GUINewsFeed::DEFAULT_URL = "https://eclipse.dev/sumo/feed/news.xml";
43const time_t GUINewsFeed::MIN_INTERVAL = 30 * 24 * 60 * 60;
44
45#define NEWS_REG_SECTION "NEWS"
46#define NEWS_MAX_SHOWN 5
47#define NEWS_DISABLED 4102444800LL // year 2100
48#define NEWS_WRAP_COLUMNS 80
49#define NEWS_MAX_BYTES (1024 * 1024)
50
51
52// ===========================================================================
53// FOX callback mapping
54// ===========================================================================
59
60FXIMPLEMENT(GUINewsFeed, FXObject, GUINewsFeedMap, ARRAYNUMBER(GUINewsFeedMap))
61
62
63// ===========================================================================
64// helpers
65// ===========================================================================
66#ifdef HAVE_CURL
67static size_t
68collect(char* data, size_t size, size_t nmemb, void* userdata) {
69 std::string* result = static_cast<std::string*>(userdata);
70 const size_t bytes = size * nmemb;
71 if (result->size() + bytes > NEWS_MAX_BYTES) {
72 return 0; // abort the transfer
73 }
74 result->append(data, bytes);
75 return bytes;
76}
77
78static int
79checkAbort(void* userdata, curl_off_t, curl_off_t, curl_off_t, curl_off_t) {
80 return static_cast<std::atomic<bool>*>(userdata)->load() ? 1 : 0;
81}
82#endif
83
85static std::string
86wrapLine(const std::string& line, const size_t width) {
87 std::string result;
88 size_t lineStart = 0;
89 size_t lastSpace = std::string::npos;
90 for (size_t i = 0; i < line.size(); i++) {
91 if (line[i] == ' ') {
92 lastSpace = i;
93 }
94 if (i - lineStart >= width && lastSpace != std::string::npos && lastSpace > lineStart) {
95 result += line.substr(lineStart, lastSpace - lineStart) + "\n";
96 lineStart = lastSpace + 1;
97 lastSpace = std::string::npos;
98 }
99 }
100 return result + line.substr(lineStart);
101}
102
104static bool
105getElement(const std::string& xml, const std::string& tag, size_t& pos, std::string& result) {
106 const std::string open = "<" + tag;
107 size_t start = pos;
108 while ((start = xml.find(open, start)) != std::string::npos) {
109 const size_t after = start + open.size();
110 if (after < xml.size() && (xml[after] == '>' || xml[after] == ' ')) {
111 break;
112 }
113 start = after;
114 }
115 if (start == std::string::npos) {
116 return false;
117 }
118 const size_t contentStart = xml.find('>', start);
119 const size_t end = xml.find("</" + tag + ">", contentStart);
120 if (contentStart == std::string::npos || end == std::string::npos) {
121 return false;
122 }
123 result = StringUtils::trim(xml.substr(contentStart + 1, end - contentStart - 1));
124 result = StringUtils::replace(result, "&lt;", "<");
125 result = StringUtils::replace(result, "&gt;", ">");
126 result = StringUtils::replace(result, "&amp;", "&");
127 pos = end;
128 return true;
129}
130
132static time_t
133parseDate(const std::string& text) {
134 std::tm tm = {};
135 std::istringstream in(text);
136 in >> std::get_time(&tm, "%a, %d %b %Y %H:%M:%S");
137 if (in.fail()) {
138 return 0;
139 }
140#ifdef _MSC_VER
141 return _mkgmtime(&tm);
142#else
143 return timegm(&tm);
144#endif
145}
146
147
148// ===========================================================================
149// member method definitions
150// ===========================================================================
151GUINewsFeed::GUINewsFeed(FXApp* app, FXWindow* owner, FXStatusBar* statusBar, const std::string& url) :
152 myApp(app),
153 myOwner(owner),
154 myStatusBar(statusBar),
155 myURL(url),
156 myAbort(false),
157 myThreadEvent(this, ID_FETCHED) {
158}
159
160
162 myAbort = true;
163 if (myThread.joinable()) {
164 myThread.join();
165 }
166}
167
168
169time_t
171 const std::string stored = myApp->reg().readStringEntry(NEWS_REG_SECTION, "lastaccess", "0");
172 try {
173 return (time_t)StringUtils::toLong(stored);
174 } catch (...) {
175 return 0;
176 }
177}
178
179
180void
182 if (!myItems.empty()) {
183 onCmdShow(nullptr, 0, nullptr);
184 } else if (myThread.joinable()) {
185 myShowAfterFetch = true;
186 } else if (!startCheck(true)) {
187 FXMessageBox::information(myOwner, MBOX_OK, TL("SUMO news"), "%s", TL("The news feed is not available."));
188 }
189}
190
191
192bool
193GUINewsFeed::startCheck(const bool force) {
194#ifdef HAVE_CURL
195 if (myThread.joinable()) {
196 return false;
197 }
199 const time_t now = time(nullptr);
200 // a last access in the future (or less than MIN_INTERVAL ago) suppresses the automatic check
201 if (!force && myPreviousAccess > 0 && now - myPreviousAccess < MIN_INTERVAL) {
202 return false;
203 }
204 myShowAfterFetch = force;
205 myThread = std::thread(&GUINewsFeed::fetch, this);
206 return true;
207#else
208 return false;
209#endif
210}
211
212
213void
215#ifdef HAVE_CURL
216 std::string document;
217 bool ok = false;
218 CURL* curl = curl_easy_init();
219 if (curl != nullptr) {
220 curl_easy_setopt(curl, CURLOPT_URL, myURL.c_str());
221#if LIBCURL_VERSION_NUM >= 0x075500
222 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "http,https");
223#else
224 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
225#endif
226 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
227 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 3L);
228 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
229 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15L);
230 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
231 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
232#if defined(WIN32) && LIBCURL_VERSION_NUM >= 0x074700
233 // OpenSSL builds have no CA bundle on Windows, use the system store; do not fail if revocation servers are unreachable (Schannel)
234 curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, (long)(CURLSSLOPT_NATIVE_CA | CURLSSLOPT_REVOKE_BEST_EFFORT));
235#endif
236 curl_easy_setopt(curl, CURLOPT_USERAGENT, "sumo-gui-news");
237 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, collect);
238 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &document);
239 curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
240 curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, checkAbort);
241 curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &myAbort);
242 ok = curl_easy_perform(curl) == CURLE_OK;
243 curl_easy_cleanup(curl);
244 }
245 if (myAbort) {
246 return;
247 }
248 {
249 std::lock_guard<std::mutex> lock(myMutex);
250 myDocument = document;
251 myOK = ok;
252 }
254#endif
255}
256
257
258long
259GUINewsFeed::onFetched(FXObject*, FXSelector, void*) {
260 std::string document;
261 bool ok;
262 {
263 std::lock_guard<std::mutex> lock(myMutex);
264 document = myDocument;
265 ok = myOK;
266 }
267 if (myThread.joinable()) {
268 myThread.join();
269 }
270 const bool requested = myShowAfterFetch;
271 myShowAfterFetch = false;
272 if (!ok) {
273 // offline or feed unavailable, try again next time
274 if (requested) {
275 FXMessageBox::information(myOwner, MBOX_OK, TL("SUMO news"), "%s", TL("The news feed is currently not available."));
276 }
277 return 1;
278 }
279 if (!requested) {
280 // an explicit request must not reset a (possibly manually set) last access time
281 myApp->reg().writeStringEntry(NEWS_REG_SECTION, "lastaccess", toString((long long)time(nullptr)).c_str());
282 }
283 myItems.clear();
284 bool hasNew = false;
285 for (const Item& item : parseRSS(document)) {
286 if ((int)myItems.size() < NEWS_MAX_SHOWN) {
287 myItems.push_back(item);
288 hasNew |= item.published > myPreviousAccess;
289 }
290 }
291 if (requested) {
292 if (myItems.empty()) {
293 FXMessageBox::information(myOwner, MBOX_OK, TL("SUMO news"), "%s", TL("There is currently no news."));
294 } else {
295 onCmdShow(nullptr, 0, nullptr);
296 }
297 } else if (hasNew) {
298 if (myStatusBar == nullptr) {
299 onCmdShow(nullptr, 0, nullptr);
300 } else if (myButton == nullptr) {
301 myButton = GUIDesigns::buildFXButton(myStatusBar, "", TL("Show the latest SUMO news"), TL("Show the latest SUMO news"),
302 GUIIconSubSys::getIcon(GUIIcon::NEWS), this, ID_SHOW, BUTTON_TOOLBAR | FRAME_RAISED | LAYOUT_RIGHT);
303 if (myStatusBar->id() != 0) {
304 myButton->create();
305 }
306 myStatusBar->recalc();
307 }
308 }
309 return 1;
310}
311
312
314static void
315addRichLine(FXComposite* parent, const std::string& line) {
316 static const std::regex urlRegex("^(https?://\\S+|([A-Za-z0-9-]+\\.)+[A-Za-z]{2,}(/\\S*)?)$");
317 const char* const leadChars = "(\"'";
318 const char* const trailChars = ".,;:!?)\"'";
319 FXHorizontalFrame* row = new FXHorizontalFrame(parent, LAYOUT_FILL_X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
320 std::string text;
321 bool first = true;
322 const auto flush = [&]() {
323 if (!text.empty()) {
324 new FXLabel(row, text.c_str(), nullptr, LABEL_NORMAL | JUSTIFY_LEFT, 0, 0, 0, 0, 0, 0, 0, 0);
325 text.clear();
326 }
327 };
328 std::istringstream words(line);
329 std::string word;
330 while (words >> word) {
331 const size_t coreStart = word.find_first_not_of(leadChars);
332 const size_t coreEnd = word.find_last_not_of(trailChars);
333 if (coreStart != std::string::npos && coreEnd != std::string::npos && coreStart <= coreEnd
334 && std::regex_match(word.substr(coreStart, coreEnd - coreStart + 1), urlRegex)) {
335 const std::string core = word.substr(coreStart, coreEnd - coreStart + 1);
336 text += (first ? "" : " ") + word.substr(0, coreStart);
337 flush();
338 MFXLinkLabel* link = new MFXLinkLabel(row, core.c_str(), nullptr, LABEL_NORMAL | JUSTIFY_LEFT, 0, 0, 0, 0, 0, 0, 0, 0);
339 link->setTipText((core.compare(0, 4, "http") == 0 ? core : "https://" + core).c_str());
340 text = word.substr(coreEnd + 1);
341 } else {
342 text += (first ? "" : " ") + word;
343 }
344 first = false;
345 }
346 flush();
347}
348
349
350long
351GUINewsFeed::onCmdShow(FXObject*, FXSelector, void*) {
352 FXDialogBox* dialog = new FXDialogBox(myOwner, TL("SUMO news"), GUIDesignDialogBox);
354 FXScrollWindow* scroll = new FXScrollWindow(dialog, GUIDesignScrollWindowFixed(640, 420));
355 FXVerticalFrame* content = new FXVerticalFrame(scroll, LAYOUT_FILL_X | LAYOUT_FILL_Y);
356 bool first = true;
357 for (const Item& item : myItems) {
358 if (!first) {
359 new FXHorizontalSeparator(content, GUIDesignHorizontalSeparator);
360 }
361 first = false;
362 // the date links to the post, if there is no date the link itself is shown
363 std::string dateText = item.link;
364 if (item.published > 0) {
365 char date[32];
366 const std::tm* tm = std::gmtime(&item.published);
367 if (tm != nullptr && std::strftime(date, sizeof(date), "%Y-%m-%d", tm) > 0) {
368 dateText = date;
369 }
370 }
371 if (!item.link.empty()) {
372 MFXLinkLabel* link = new MFXLinkLabel(content, dateText.c_str(), nullptr, LABEL_NORMAL | JUSTIFY_LEFT, 0, 0, 0, 0, 0, 0, 0, 0);
373 link->setTipText(item.link.c_str());
374 }
375 // the title (if any) is followed by the description
376 std::vector<std::string> lines;
377 for (const std::string& part : {
378 item.title, item.description
379 }) {
380 std::istringstream in(part);
381 std::string line;
382 while (std::getline(in, line)) {
383 lines.push_back(StringUtils::trim(line));
384 }
385 }
386 for (const std::string& line : lines) {
387 if (!line.empty()) {
388 std::istringstream wrapped(wrapLine(line, NEWS_WRAP_COLUMNS));
389 std::string part;
390 while (std::getline(wrapped, part)) {
391 addRichLine(content, part);
392 }
393 }
394 }
395 }
396 // automatic checking is disabled by a last access far in the future
397 const bool wasEnabled = getLastAccess() < NEWS_DISABLED;
398 FXCheckButton* autoCheck = new FXCheckButton(dialog, TL("Check for news automatically"), nullptr, 0, CHECKBUTTON_NORMAL | LAYOUT_LEFT);
399 autoCheck->setCheck(wasEnabled);
400 FXHorizontalFrame* buttonFrame = new FXHorizontalFrame(dialog, GUIDesignHorizontalFrame);
401 new FXHorizontalFrame(buttonFrame, GUIDesignAuxiliarHorizontalFrame);
402 GUIDesigns::buildFXButton(buttonFrame, TL("OK"), "", "", GUIIconSubSys::getIcon(GUIIcon::ACCEPT), dialog, FXDialogBox::ID_ACCEPT, GUIDesignButtonDialog);
403 new FXHorizontalFrame(buttonFrame, GUIDesignAuxiliarHorizontalFrame);
404 dialog->create();
405 dialog->execute(PLACEMENT_OWNER);
406 if (autoCheck->getCheck() != wasEnabled) {
407 myApp->reg().writeStringEntry(NEWS_REG_SECTION, "lastaccess", autoCheck->getCheck() ? "0" : toString((long long)NEWS_DISABLED).c_str());
408 }
409 delete dialog;
410 if (myButton != nullptr) {
411 delete myButton;
412 myButton = nullptr;
413 myStatusBar->recalc();
414 }
415 return 1;
416}
417
418
419std::vector<GUINewsFeed::Item>
420GUINewsFeed::parseRSS(const std::string& xml) {
421 std::vector<Item> result;
422 size_t pos = 0;
423 std::string block;
424 while (getElement(xml, "item", pos, block)) {
425 Item item;
426 size_t p = 0;
427 getElement(block, "title", p, item.title);
428 p = 0;
429 getElement(block, "link", p, item.link);
430 p = 0;
431 getElement(block, "description", p, item.description);
432 p = 0;
433 std::string date;
434 if (getElement(block, "pubDate", p, date)) {
435 item.published = parseDate(date);
436 }
437 result.push_back(item);
438 }
439 return result;
440}
441
442
443/****************************************************************************/
#define GUIDesignAuxiliarHorizontalFrame
design for auxiliar (Without borders) horizontal frame used to pack another frames
Definition GUIDesigns.h:430
#define GUIDesignDialogBox
Definition GUIDesigns.h:630
#define GUIDesignScrollWindowFixed(width, height)
design for the content scroll of UndoList
Definition GUIDesigns.h:400
#define GUIDesignHorizontalSeparator
Definition GUIDesigns.h:494
#define GUIDesignButtonDialog
Definition GUIDesigns.h:174
#define GUIDesignHorizontalFrame
Horizontal frame extended over frame parent with padding and spacing.
Definition GUIDesigns.h:347
static std::string wrapLine(const std::string &line, const size_t width)
inserts line breaks at spaces so that lines have at most the given number of bytes (if possible)
FXDEFMAP(GUINewsFeed) GUINewsFeedMap[]
#define NEWS_REG_SECTION
static void addRichLine(FXComposite *parent, const std::string &line)
adds a row of labels to parent, words that look like URLs (with or without scheme) become clickable l...
static time_t parseDate(const std::string &text)
parses an RFC 822 date like "Thu, 19 Nov 2026 10:00:00 +0000" (always UTC)
#define NEWS_MAX_BYTES
#define NEWS_MAX_SHOWN
#define NEWS_WRAP_COLUMNS
#define NEWS_DISABLED
static bool getElement(const std::string &xml, const std::string &tag, size_t &pos, std::string &result)
returns the text of the first <tag> element in xml (starting at pos), the feed is created by tools/ne...
#define TL(string)
Definition MsgHandler.h:316
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
static FXButton * buildFXButton(FXComposite *p, const std::string &text, const std::string &tip, const std::string &help, FXIcon *ic, FXObject *tgt, FXSelector sel, FXuint opts=BUTTON_NORMAL, FXint x=0, FXint y=0, FXint w=0, FXint h=0, FXint pl=DEFAULT_PAD, FXint pr=DEFAULT_PAD, FXint pt=DEFAULT_PAD, FXint pb=DEFAULT_PAD)
build button
static FXIcon * getIcon(const GUIIcon which)
returns a icon previously defined in the enum GUIIcon
Periodically fetches an RSS feed with news about upcoming releases.
Definition GUINewsFeed.h:47
FXButton * myButton
the button in the status bar (null while there is nothing new)
GUINewsFeed(FXApp *app, FXWindow *owner, FXStatusBar *statusBar, const std::string &url=DEFAULT_URL)
constructor
FXStatusBar * myStatusBar
the status bar holding the news button
time_t getLastAccess() const
time of the last successful access (0 if never)
static const std::string DEFAULT_URL
default feed location
Definition GUINewsFeed.h:68
std::atomic< bool > myAbort
tells the worker thread to give up
std::mutex myMutex
protects myDocument and myOK
time_t myPreviousAccess
the last access time before this download started
void fetch()
the download, executed in myThread
bool myShowAfterFetch
whether the dialog should open as soon as the running download finishes
void showLatest()
shows the latest items, downloading them first if necessary
static std::vector< Item > parseRSS(const std::string &xml)
extracts the items of an RSS document
std::string myURL
the feed address
long onCmdShow(FXObject *, FXSelector, void *)
called when the news button was clicked, shows the latest items
std::string myDocument
the downloaded document
FXEX::MFXThreadEvent myThreadEvent
wakes the GUI thread
FXApp * myApp
the application (registry access)
FXWindow * myOwner
parent of the news dialog
~GUINewsFeed()
destructor, aborts a running download
static const time_t MIN_INTERVAL
minimum time between two accesses (seconds)
Definition GUINewsFeed.h:71
std::vector< Item > myItems
the latest items (empty until a download succeeded)
bool myOK
whether the download succeeded
bool startCheck(const bool force=false)
starts a download if enabled, curl is available and the last access is long enough ago
std::thread myThread
the worker thread
long onFetched(FXObject *, FXSelector, void *)
called in the GUI thread when the download has finished
static long long int toLong(const std::string &sData)
converts a string into the long value described by it by calling the char-type converter,...
static std::string trim(const std::string s, const std::string &t=" \t\n")
remove leading and trailing whitespace
static std::string replace(std::string str, const std::string &what, const std::string &by)
Replaces all occurrences of the second string by the third string within the first string.
@ SEL_THREAD
Definition fxexdefs.h:153
a single entry of the feed
Definition GUINewsFeed.h:52
std::string description
Definition GUINewsFeed.h:55
std::string title
Definition GUINewsFeed.h:53
std::string link
Definition GUINewsFeed.h:54
time_t published
publication time (seconds since epoch), 0 if unknown
Definition GUINewsFeed.h:57