OpenTTD
textfile_gui.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "fileio_func.h"
14 #include "fontcache.h"
15 #include "gfx_type.h"
16 #include "gfx_func.h"
17 #include "string_func.h"
18 #include "textfile_gui.h"
19 
20 #include "widgets/misc_widget.h"
21 
22 #include "table/strings.h"
23 
24 #if defined(WITH_ZLIB)
25 #include <zlib.h>
26 #endif
27 
28 #if defined(WITH_LIBLZMA)
29 #include <lzma.h>
30 #endif
31 
32 #include "safeguards.h"
33 
37  NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
38  NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_TF_CAPTION), SetDataTip(STR_NULL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
39  NWidget(WWT_TEXTBTN, COLOUR_MAUVE, WID_TF_WRAPTEXT), SetDataTip(STR_TEXTFILE_WRAP_TEXT, STR_TEXTFILE_WRAP_TEXT_TOOLTIP),
40  NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
41  EndContainer(),
44  EndContainer(),
47  EndContainer(),
48  EndContainer(),
51  NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
52  EndContainer(),
53 };
54 
57  WDP_CENTER, "textfile", 630, 460,
59  0,
60  _nested_textfile_widgets, lengthof(_nested_textfile_widgets)
61 );
62 
63 TextfileWindow::TextfileWindow(TextfileType file_type) : Window(&_textfile_desc), file_type(file_type)
64 {
65  this->CreateNestedTree();
66  this->vscroll = this->GetScrollbar(WID_TF_VSCROLLBAR);
67  this->hscroll = this->GetScrollbar(WID_TF_HSCROLLBAR);
68  this->FinishInitNested(file_type);
69  this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetDataTip(STR_TEXTFILE_README_CAPTION + file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
70 
71  this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
72  this->vscroll->SetStepSize(FONT_HEIGHT_MONO);
73 }
74 
75 /* virtual */ TextfileWindow::~TextfileWindow()
76 {
77  free(this->text);
78 }
79 
85 {
86  int max_width = this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WD_FRAMETEXT_LEFT - WD_FRAMERECT_RIGHT;
87 
88  uint height = 0;
89  for (uint i = 0; i < this->lines.size(); i++) {
90  height += GetStringHeight(this->lines[i], max_width, FS_MONO);
91  }
92 
93  return height;
94 }
95 
96 /* virtual */ void TextfileWindow::UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
97 {
98  switch (widget) {
99  case WID_TF_BACKGROUND:
100  resize->height = 1;
101 
102  size->height = 4 * resize->height + TOP_SPACING + BOTTOM_SPACING; // At least 4 lines are visible.
103  size->width = max(200u, size->width); // At least 200 pixels wide.
104  break;
105  }
106 }
107 
110 {
112  this->vscroll->SetCount(this->GetContentHeight());
113  this->hscroll->SetCount(0);
114  } else {
115  uint max_length = 0;
116  for (uint i = 0; i < this->lines.size(); i++) {
117  max_length = max(max_length, GetStringBoundingBox(this->lines[i], FS_MONO).width);
118  }
119  this->vscroll->SetCount((uint)this->lines.size() * FONT_HEIGHT_MONO);
120  this->hscroll->SetCount(max_length + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
121  }
122 
124 }
125 
126 /* virtual */ void TextfileWindow::OnClick(Point pt, int widget, int click_count)
127 {
128  switch (widget) {
129  case WID_TF_WRAPTEXT:
131  this->SetupScrollbars();
132  this->InvalidateData();
133  break;
134  }
135 }
136 
137 /* virtual */ void TextfileWindow::DrawWidget(const Rect &r, int widget) const
138 {
139  if (widget != WID_TF_BACKGROUND) return;
140 
141  const int x = r.left + WD_FRAMETEXT_LEFT;
142  const int y = r.top + WD_FRAMETEXT_TOP;
143  const int right = r.right - WD_FRAMETEXT_RIGHT;
144  const int bottom = r.bottom - WD_FRAMETEXT_BOTTOM;
145 
146  DrawPixelInfo new_dpi;
147  if (!FillDrawPixelInfo(&new_dpi, x, y, right - x + 1, bottom - y + 1)) return;
148  DrawPixelInfo *old_dpi = _cur_dpi;
149  _cur_dpi = &new_dpi;
150 
151  /* Draw content (now coordinates given to DrawString* are local to the new clipping region). */
152  int line_height = FONT_HEIGHT_MONO;
153  int y_offset = -this->vscroll->GetPosition();
154 
155  for (uint i = 0; i < this->lines.size(); i++) {
157  y_offset = DrawStringMultiLine(0, right - x, y_offset, bottom - y, this->lines[i], TC_WHITE, SA_TOP | SA_LEFT, false, FS_MONO);
158  } else {
159  DrawString(-this->hscroll->GetPosition(), right - x, y_offset, this->lines[i], TC_WHITE, SA_TOP | SA_LEFT, false, FS_MONO);
160  y_offset += line_height; // margin to previous element
161  }
162  }
163 
164  _cur_dpi = old_dpi;
165 }
166 
167 /* virtual */ void TextfileWindow::OnResize()
168 {
171 
172  this->SetupScrollbars();
173 }
174 
175 /* virtual */ void TextfileWindow::Reset()
176 {
177  this->search_iterator = 0;
178 }
179 
181 {
182  return FS_MONO;
183 }
184 
185 /* virtual */ const char *TextfileWindow::NextString()
186 {
187  if (this->search_iterator >= this->lines.size()) return nullptr;
188 
189  return this->lines[this->search_iterator++];
190 }
191 
192 /* virtual */ bool TextfileWindow::Monospace()
193 {
194  return true;
195 }
196 
197 /* virtual */ void TextfileWindow::SetFontNames(FreeTypeSettings *settings, const char *font_name, const void *os_data)
198 {
199 #if defined(WITH_FREETYPE) || defined(_WIN32)
200  strecpy(settings->mono.font, font_name, lastof(settings->mono.font));
201  free(settings->mono.os_handle);
202  settings->mono.os_handle = os_data;
203 #endif
204 }
205 
206 #if defined(WITH_ZLIB)
207 
222 static void Gunzip(byte **bufp, size_t *sizep)
223 {
224  static const int BLOCKSIZE = 8192;
225  byte *buf = nullptr;
226  size_t alloc_size = 0;
227  z_stream z;
228  int res;
229 
230  memset(&z, 0, sizeof(z));
231  z.next_in = *bufp;
232  z.avail_in = (uInt)*sizep;
233 
234  /* window size = 15, add 32 to enable gzip or zlib header processing */
235  res = inflateInit2(&z, 15 + 32);
236  /* Z_BUF_ERROR just means we need more space */
237  while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
238  /* When we get here, we're either just starting, or
239  * inflate is out of output space - allocate more */
240  alloc_size += BLOCKSIZE;
241  z.avail_out += BLOCKSIZE;
242  buf = ReallocT(buf, alloc_size);
243  z.next_out = buf + alloc_size - z.avail_out;
244  res = inflate(&z, Z_FINISH);
245  }
246 
247  free(*bufp);
248  inflateEnd(&z);
249 
250  if (res == Z_STREAM_END) {
251  *bufp = buf;
252  *sizep = alloc_size - z.avail_out;
253  } else {
254  /* Something went wrong */
255  *bufp = nullptr;
256  *sizep = 0;
257  free(buf);
258  }
259 }
260 #endif
261 
262 #if defined(WITH_LIBLZMA)
263 
278 static void Xunzip(byte **bufp, size_t *sizep)
279 {
280  static const int BLOCKSIZE = 8192;
281  byte *buf = nullptr;
282  size_t alloc_size = 0;
283  lzma_stream z = LZMA_STREAM_INIT;
284  int res;
285 
286  z.next_in = *bufp;
287  z.avail_in = *sizep;
288 
289  res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
290  /* Z_BUF_ERROR just means we need more space */
291  while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
292  /* When we get here, we're either just starting, or
293  * inflate is out of output space - allocate more */
294  alloc_size += BLOCKSIZE;
295  z.avail_out += BLOCKSIZE;
296  buf = ReallocT(buf, alloc_size);
297  z.next_out = buf + alloc_size - z.avail_out;
298  res = lzma_code(&z, LZMA_FINISH);
299  }
300 
301  free(*bufp);
302  lzma_end(&z);
303 
304  if (res == LZMA_STREAM_END) {
305  *bufp = buf;
306  *sizep = alloc_size - z.avail_out;
307  } else {
308  /* Something went wrong */
309  *bufp = nullptr;
310  *sizep = 0;
311  free(buf);
312  }
313 }
314 #endif
315 
316 
320 /* virtual */ void TextfileWindow::LoadTextfile(const char *textfile, Subdirectory dir)
321 {
322  if (textfile == nullptr) return;
323 
324  this->lines.clear();
325 
326  /* Get text from file */
327  size_t filesize;
328  FILE *handle = FioFOpenFile(textfile, "rb", dir, &filesize);
329  if (handle == nullptr) return;
330 
331  this->text = ReallocT(this->text, filesize);
332  size_t read = fread(this->text, 1, filesize, handle);
333  fclose(handle);
334 
335  if (read != filesize) return;
336 
337 #if defined(WITH_ZLIB) || defined(WITH_LIBLZMA)
338  const char *suffix = strrchr(textfile, '.');
339  if (suffix == nullptr) return;
340 #endif
341 
342 #if defined(WITH_ZLIB)
343  /* In-place gunzip */
344  if (strcmp(suffix, ".gz") == 0) Gunzip((byte**)&this->text, &filesize);
345 #endif
346 
347 #if defined(WITH_LIBLZMA)
348  /* In-place xunzip */
349  if (strcmp(suffix, ".xz") == 0) Xunzip((byte**)&this->text, &filesize);
350 #endif
351 
352  if (!this->text) return;
353 
354  /* Add space for trailing \0 */
355  this->text = ReallocT(this->text, filesize + 1);
356  this->text[filesize] = '\0';
357 
358  /* Replace tabs and line feeds with a space since str_validate removes those. */
359  for (char *p = this->text; *p != '\0'; p++) {
360  if (*p == '\t' || *p == '\r') *p = ' ';
361  }
362 
363  /* Check for the byte-order-mark, and skip it if needed. */
364  char *p = this->text + (strncmp("\xEF\xBB\xBF", this->text, 3) == 0 ? 3 : 0);
365 
366  /* Make sure the string is a valid UTF-8 sequence. */
368 
369  /* Split the string on newlines. */
370  this->lines.push_back(p);
371  for (; *p != '\0'; p++) {
372  if (*p == '\n') {
373  *p = '\0';
374  this->lines.push_back(p + 1);
375  }
376  }
377 
378  CheckForMissingGlyphs(true, this);
379 }
380 
388 const char *GetTextfile(TextfileType type, Subdirectory dir, const char *filename)
389 {
390  static const char * const prefixes[] = {
391  "readme",
392  "changelog",
393  "license",
394  };
395  assert_compile(lengthof(prefixes) == TFT_END);
396 
397  const char *prefix = prefixes[type];
398 
399  if (filename == nullptr) return nullptr;
400 
401  static char file_path[MAX_PATH];
402  strecpy(file_path, filename, lastof(file_path));
403 
404  char *slash = strrchr(file_path, PATHSEPCHAR);
405  if (slash == nullptr) return nullptr;
406 
407  static const char * const exts[] = {
408  "txt",
409 #if defined(WITH_ZLIB)
410  "txt.gz",
411 #endif
412 #if defined(WITH_LIBLZMA)
413  "txt.xz",
414 #endif
415  };
416 
417  for (size_t i = 0; i < lengthof(exts); i++) {
418  seprintf(slash + 1, lastof(file_path), "%s_%s.%s", prefix, GetCurrentLanguageIsoCode(), exts[i]);
419  if (FioCheckFileExists(file_path, dir)) return file_path;
420 
421  seprintf(slash + 1, lastof(file_path), "%s_%.2s.%s", prefix, GetCurrentLanguageIsoCode(), exts[i]);
422  if (FioCheckFileExists(file_path, dir)) return file_path;
423 
424  seprintf(slash + 1, lastof(file_path), "%s.%s", prefix, exts[i]);
425  if (FioCheckFileExists(file_path, dir)) return file_path;
426  }
427  return nullptr;
428 }
bool Monospace() override
Whether to search for a monospace font or not.
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition: strings.cpp:2099
Data about how and where to blit pixels.
Definition: gfx_type.h:156
ResizeInfo resize
Resize information.
Definition: window_gui.h:324
static NWidgetPart SetResize(int16 dx, int16 dy)
Widget part function for setting the resize step.
Definition: widget_type.h:930
void SetWidgetDisabledState(byte widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition: window_gui.h:394
static void Xunzip(byte **bufp, size_t *sizep)
Do an in-memory xunzip operation.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
High level window description.
Definition: window_gui.h:168
char * text
Lines of text from the NewGRF&#39;s textfile.
Definition: textfile_gui.h:27
static WindowDesc _textfile_desc(WDP_CENTER, "textfile", 630, 460, WC_TEXTFILE, WC_NONE, 0, _nested_textfile_widgets, lengthof(_nested_textfile_widgets))
Window definition for the textfile window.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
textfile; Window numbers:
Definition: window_type.h:182
Horizontal container.
Definition: widget_type.h:75
#define FONT_HEIGHT_MONO
Height of characters in the large (FS_MONO) font.
Definition: gfx_func.h:184
Index of the monospaced font in the font tables.
Definition: gfx_type.h:207
static void Gunzip(byte **bufp, size_t *sizep)
Do an in-memory gunzip operation.
void OnClick(Point pt, int widget, int click_count) override
A click with the left mouse button has been made on the window.
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:22
Resize box (normally at bottom-right of a window)
Definition: widget_type.h:68
Horizontal scrollbar to scroll through the textfile left-to-right.
Definition: misc_widget.h:55
void ToggleWidgetLoweredState(byte widget_index)
Invert the lowered/raised status of a widget.
Definition: window_gui.h:465
void DrawWidget(const Rect &r, int widget) const override
Draw the contents of a nested widget.
int GetStringHeight(const char *str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition: gfx.cpp:547
Close box (at top-left of a window)
Definition: widget_type.h:69
Functions for Standard In/Out file operations.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition: gfx.cpp:1478
Settings for the freetype fonts.
Definition: fontcache.h:226
void SetCount(int num)
Sets the number of elements in the list.
Definition: widget_type.h:670
Partial widget specification to allow NWidgets to be written nested.
Definition: widget_type.h:910
Data structure for an opened window.
Definition: window_gui.h:278
Functions to read fonts from files and cache them.
Bottom offset of the text of the frame.
Definition: window_gui.h:75
uint GetContentHeight()
Get the total height of the content displayed in this window, if wrapping is disabled.
Functions related to low-level strings.
FontSize DefaultSize() override
Get the default (font) size of the string.
uint search_iterator
Iterator for the font check search.
Definition: textfile_gui.h:29
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX) ...
Definition: widget_type.h:65
bool IsWidgetLowered(byte widget_index) const
Gets the lowered state of a widget.
Definition: window_gui.h:495
void str_validate(char *str, const char *last, StringValidationSettings settings)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:196
FreeTypeSubSetting mono
The mono space font used for license/readme viewers.
Definition: fontcache.h:230
const char * NextString() override
Get the next string to search through.
Whether or not to wrap the text.
Definition: misc_widget.h:52
void SetFontNames(FreeTypeSettings *settings, const char *font_name, const void *os_data) override
Set the right font names.
Types related to the misc widgets.
static NWidgetPart SetDataTip(uint32 data, StringID tip)
Widget part function for setting the data and tooltip.
Definition: widget_type.h:1014
Functions related to the gfx engine.
static NWidgetPart SetMinimalSize(int16 x, int16 y)
Widget part function for setting the minimal size.
Definition: widget_type.h:947
FILE * FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:465
Definition of base types and functions in a cross-platform compatible way.
static const int BOTTOM_SPACING
Additional spacing at the bottom of the WID_TF_BACKGROUND widget.
Definition: textfile_gui.h:32
Allow newlines.
Definition: string_type.h:53
Top align the text.
Definition: gfx_func.h:101
A number of safeguards to prevent using unsafe methods.
Simple depressed panel.
Definition: widget_type.h:50
Horizontal scrollbar.
Definition: widget_type.h:83
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type...
Definition: alloc_func.hpp:113
Center the window.
Definition: window_gui.h:157
virtual void LoadTextfile(const char *textfile, Subdirectory dir)
Loads the textfile text from file and setup lines.
static NWidgetPart NWidget(WidgetType tp, Colours col, int16 idx=-1)
Widget part function for starting a new &#39;real&#39; widget.
Definition: widget_type.h:1114
int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition: gfx.cpp:499
Right offset of the text of the frame.
Definition: window_gui.h:73
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
TextfileType
Additional text files accompanying Tar archives.
Definition: textfile_type.h:16
Top offset of the text of the frame.
Definition: window_gui.h:74
Left offset of the text of the frame.
Definition: window_gui.h:72
bool FioCheckFileExists(const char *filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:312
static const int TOP_SPACING
Additional spacing at the top of the WID_TF_BACKGROUND widget.
Definition: textfile_gui.h:31
Scrollbar * hscroll
Horizontal scrollbar.
Definition: textfile_gui.h:26
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
Update size and resize step of a widget in the window.
void SetupScrollbars()
Set scrollbars to the right lengths.
Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition: gfx.cpp:698
No window, redirects to WC_MAIN_WINDOW.
Definition: window_type.h:40
char font[MAX_PATH]
The name of the font, or path to the font.
Definition: fontcache.h:218
const char * GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
Definition: strings.cpp:1999
static const NWidgetPart _nested_textfile_widgets[]
Widgets for the textfile window.
const void * os_handle
Optional native OS font info.
Definition: fontcache.h:222
Window caption (window title between closebox and stickybox)
Definition: widget_type.h:61
Replace the unknown/bad bits with question marks.
Definition: string_type.h:52
void Reset() override
Reset the search, i.e.
Panel to draw the textfile on.
Definition: misc_widget.h:53
Vertical container.
Definition: widget_type.h:77
static NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME, WWT_INSET, or WWT_PANEL).
Definition: widget_type.h:999
FontSize
Available font sizes.
Definition: gfx_type.h:203
Scrollbar * vscroll
Vertical scrollbar.
Definition: textfile_gui.h:25
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
Coordinates of a point in 2D.
std::vector< const char * > lines
text, split into lines in a table with lines.
Definition: textfile_gui.h:28
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
Offset at right to draw the frame rectangular area.
Definition: window_gui.h:63
int width
width of the window (number of pixels to the right in x direction)
Definition: window_gui.h:321
The caption of the window.
Definition: misc_widget.h:51
void SetCapacityFromWidget(Window *w, int widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget. ...
Definition: widget.cpp:1973
Specification of a rectangle with absolute coordinates of all edges.
Vertical scrollbar.
Definition: widget_type.h:84
Left align the text.
Definition: gfx_func.h:96
const char * GetTextfile(TextfileType type, Subdirectory dir, const char *filename)
Search a textfile file next to the given content.
Vertical scrollbar to scroll through the textfile up-and-down.
Definition: misc_widget.h:54
static NWidgetPart SetScrollbar(int index)
Attach a scrollbar to a widget.
Definition: widget_type.h:1095
Dimensions (a width and height) of a rectangle in 2D.
Types related to the graphics and/or input devices.
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window&#39;s data as invalid (in need of re-computing)
Definition: window.cpp:3240
int height
Height of the window (number of pixels down in y direction)
Definition: window_gui.h:322
GUI functions related to textfiles.
int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition: gfx.cpp:620
(Toggle) Button with text
Definition: widget_type.h:55
void OnResize() override
Called after the window got resized.
uint16 GetPosition() const
Gets the position of the first visible element in the list.
Definition: widget_type.h:631