Add: allow making heightmap screenshot via console
[openttd-github.git] / src / textfile_gui.cpp
blob075898fd71b4f7f8a3edff90898940bce00d32ef
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file textfile_gui.cpp Implementation of textfile window. */
10 #include "stdafx.h"
11 #include "fileio_func.h"
12 #include "fontcache.h"
13 #include "gfx_type.h"
14 #include "gfx_func.h"
15 #include "string_func.h"
16 #include "textfile_gui.h"
18 #include "widgets/misc_widget.h"
20 #include "table/strings.h"
22 #if defined(WITH_ZLIB)
23 #include <zlib.h>
24 #endif
26 #if defined(WITH_LIBLZMA)
27 #include <lzma.h>
28 #endif
30 #include "safeguards.h"
32 /** Widgets for the textfile window. */
33 static const NWidgetPart _nested_textfile_widgets[] = {
34 NWidget(NWID_HORIZONTAL),
35 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
36 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_TF_CAPTION), SetDataTip(STR_NULL, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
37 NWidget(WWT_TEXTBTN, COLOUR_MAUVE, WID_TF_WRAPTEXT), SetDataTip(STR_TEXTFILE_WRAP_TEXT, STR_TEXTFILE_WRAP_TEXT_TOOLTIP),
38 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
39 EndContainer(),
40 NWidget(NWID_HORIZONTAL),
41 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_TF_BACKGROUND), SetMinimalSize(200, 125), SetResize(1, 12), SetScrollbar(WID_TF_VSCROLLBAR),
42 EndContainer(),
43 NWidget(NWID_VERTICAL),
44 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_TF_VSCROLLBAR),
45 EndContainer(),
46 EndContainer(),
47 NWidget(NWID_HORIZONTAL),
48 NWidget(NWID_HSCROLLBAR, COLOUR_MAUVE, WID_TF_HSCROLLBAR),
49 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
50 EndContainer(),
53 /** Window definition for the textfile window */
54 static WindowDesc _textfile_desc(
55 WDP_CENTER, "textfile", 630, 460,
56 WC_TEXTFILE, WC_NONE,
58 _nested_textfile_widgets, lengthof(_nested_textfile_widgets)
61 TextfileWindow::TextfileWindow(TextfileType file_type) : Window(&_textfile_desc), file_type(file_type)
63 this->CreateNestedTree();
64 this->vscroll = this->GetScrollbar(WID_TF_VSCROLLBAR);
65 this->hscroll = this->GetScrollbar(WID_TF_HSCROLLBAR);
66 this->FinishInitNested(file_type);
67 this->GetWidget<NWidgetCore>(WID_TF_CAPTION)->SetDataTip(STR_TEXTFILE_README_CAPTION + file_type, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
69 this->hscroll->SetStepSize(10); // Speed up horizontal scrollbar
70 this->vscroll->SetStepSize(FONT_HEIGHT_MONO);
73 /* virtual */ TextfileWindow::~TextfileWindow()
75 free(this->text);
78 /**
79 * Get the total height of the content displayed in this window, if wrapping is disabled.
80 * @return the height in pixels
82 uint TextfileWindow::GetContentHeight()
84 int max_width = this->GetWidget<NWidgetCore>(WID_TF_BACKGROUND)->current_x - WD_FRAMETEXT_LEFT - WD_FRAMERECT_RIGHT;
86 uint height = 0;
87 for (uint i = 0; i < this->lines.size(); i++) {
88 height += GetStringHeight(this->lines[i], max_width, FS_MONO);
91 return height;
94 /* virtual */ void TextfileWindow::UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
96 switch (widget) {
97 case WID_TF_BACKGROUND:
98 resize->height = 1;
100 size->height = 4 * resize->height + TOP_SPACING + BOTTOM_SPACING; // At least 4 lines are visible.
101 size->width = std::max(200u, size->width); // At least 200 pixels wide.
102 break;
106 /** Set scrollbars to the right lengths. */
107 void TextfileWindow::SetupScrollbars()
109 if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
110 this->vscroll->SetCount(this->GetContentHeight());
111 this->hscroll->SetCount(0);
112 } else {
113 uint max_length = 0;
114 for (uint i = 0; i < this->lines.size(); i++) {
115 max_length = std::max(max_length, GetStringBoundingBox(this->lines[i], FS_MONO).width);
117 this->vscroll->SetCount((uint)this->lines.size() * FONT_HEIGHT_MONO);
118 this->hscroll->SetCount(max_length + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
121 this->SetWidgetDisabledState(WID_TF_HSCROLLBAR, IsWidgetLowered(WID_TF_WRAPTEXT));
124 /* virtual */ void TextfileWindow::OnClick(Point pt, int widget, int click_count)
126 switch (widget) {
127 case WID_TF_WRAPTEXT:
128 this->ToggleWidgetLoweredState(WID_TF_WRAPTEXT);
129 this->SetupScrollbars();
130 this->InvalidateData();
131 break;
135 /* virtual */ void TextfileWindow::DrawWidget(const Rect &r, int widget) const
137 if (widget != WID_TF_BACKGROUND) return;
139 const int x = r.left + WD_FRAMETEXT_LEFT;
140 const int y = r.top + WD_FRAMETEXT_TOP;
141 const int right = r.right - WD_FRAMETEXT_RIGHT;
142 const int bottom = r.bottom - WD_FRAMETEXT_BOTTOM;
144 DrawPixelInfo new_dpi;
145 if (!FillDrawPixelInfo(&new_dpi, x, y, right - x + 1, bottom - y + 1)) return;
146 DrawPixelInfo *old_dpi = _cur_dpi;
147 _cur_dpi = &new_dpi;
149 /* Draw content (now coordinates given to DrawString* are local to the new clipping region). */
150 int line_height = FONT_HEIGHT_MONO;
151 int y_offset = -this->vscroll->GetPosition();
153 for (uint i = 0; i < this->lines.size(); i++) {
154 if (IsWidgetLowered(WID_TF_WRAPTEXT)) {
155 y_offset = DrawStringMultiLine(0, right - x, y_offset, bottom - y, this->lines[i], TC_WHITE, SA_TOP | SA_LEFT, false, FS_MONO);
156 } else {
157 DrawString(-this->hscroll->GetPosition(), right - x, y_offset, this->lines[i], TC_WHITE, SA_TOP | SA_LEFT, false, FS_MONO);
158 y_offset += line_height; // margin to previous element
162 _cur_dpi = old_dpi;
165 /* virtual */ void TextfileWindow::OnResize()
167 this->vscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND, TOP_SPACING + BOTTOM_SPACING);
168 this->hscroll->SetCapacityFromWidget(this, WID_TF_BACKGROUND);
170 this->SetupScrollbars();
173 /* virtual */ void TextfileWindow::Reset()
175 this->search_iterator = 0;
178 /* virtual */ FontSize TextfileWindow::DefaultSize()
180 return FS_MONO;
183 /* virtual */ const char *TextfileWindow::NextString()
185 if (this->search_iterator >= this->lines.size()) return nullptr;
187 return this->lines[this->search_iterator++];
190 /* virtual */ bool TextfileWindow::Monospace()
192 return true;
195 /* virtual */ void TextfileWindow::SetFontNames(FreeTypeSettings *settings, const char *font_name, const void *os_data)
197 #if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
198 strecpy(settings->mono.font, font_name, lastof(settings->mono.font));
199 settings->mono.os_handle = os_data;
200 #endif
203 #if defined(WITH_ZLIB)
206 * Do an in-memory gunzip operation. This works on a raw deflate stream,
207 * or a file with gzip or zlib header.
208 * @param bufp A pointer to a buffer containing the input data. This
209 * buffer will be freed and replaced by a buffer containing
210 * the uncompressed data.
211 * @param sizep A pointer to the buffer size. Before the call, the value
212 * pointed to should contain the size of the input buffer.
213 * After the call, it contains the size of the uncompressed
214 * data.
216 * When decompressing fails, *bufp is set to nullptr and *sizep to 0. The
217 * compressed buffer passed in is still freed in this case.
219 static void Gunzip(byte **bufp, size_t *sizep)
221 static const int BLOCKSIZE = 8192;
222 byte *buf = nullptr;
223 size_t alloc_size = 0;
224 z_stream z;
225 int res;
227 memset(&z, 0, sizeof(z));
228 z.next_in = *bufp;
229 z.avail_in = (uInt)*sizep;
231 /* window size = 15, add 32 to enable gzip or zlib header processing */
232 res = inflateInit2(&z, 15 + 32);
233 /* Z_BUF_ERROR just means we need more space */
234 while (res == Z_OK || (res == Z_BUF_ERROR && z.avail_out == 0)) {
235 /* When we get here, we're either just starting, or
236 * inflate is out of output space - allocate more */
237 alloc_size += BLOCKSIZE;
238 z.avail_out += BLOCKSIZE;
239 buf = ReallocT(buf, alloc_size);
240 z.next_out = buf + alloc_size - z.avail_out;
241 res = inflate(&z, Z_FINISH);
244 free(*bufp);
245 inflateEnd(&z);
247 if (res == Z_STREAM_END) {
248 *bufp = buf;
249 *sizep = alloc_size - z.avail_out;
250 } else {
251 /* Something went wrong */
252 *bufp = nullptr;
253 *sizep = 0;
254 free(buf);
257 #endif
259 #if defined(WITH_LIBLZMA)
262 * Do an in-memory xunzip operation. This works on a .xz or (legacy)
263 * .lzma file.
264 * @param bufp A pointer to a buffer containing the input data. This
265 * buffer will be freed and replaced by a buffer containing
266 * the uncompressed data.
267 * @param sizep A pointer to the buffer size. Before the call, the value
268 * pointed to should contain the size of the input buffer.
269 * After the call, it contains the size of the uncompressed
270 * data.
272 * When decompressing fails, *bufp is set to nullptr and *sizep to 0. The
273 * compressed buffer passed in is still freed in this case.
275 static void Xunzip(byte **bufp, size_t *sizep)
277 static const int BLOCKSIZE = 8192;
278 byte *buf = nullptr;
279 size_t alloc_size = 0;
280 lzma_stream z = LZMA_STREAM_INIT;
281 int res;
283 z.next_in = *bufp;
284 z.avail_in = *sizep;
286 res = lzma_auto_decoder(&z, UINT64_MAX, LZMA_CONCATENATED);
287 /* Z_BUF_ERROR just means we need more space */
288 while (res == LZMA_OK || (res == LZMA_BUF_ERROR && z.avail_out == 0)) {
289 /* When we get here, we're either just starting, or
290 * inflate is out of output space - allocate more */
291 alloc_size += BLOCKSIZE;
292 z.avail_out += BLOCKSIZE;
293 buf = ReallocT(buf, alloc_size);
294 z.next_out = buf + alloc_size - z.avail_out;
295 res = lzma_code(&z, LZMA_FINISH);
298 free(*bufp);
299 lzma_end(&z);
301 if (res == LZMA_STREAM_END) {
302 *bufp = buf;
303 *sizep = alloc_size - z.avail_out;
304 } else {
305 /* Something went wrong */
306 *bufp = nullptr;
307 *sizep = 0;
308 free(buf);
311 #endif
315 * Loads the textfile text from file and setup #lines.
317 /* virtual */ void TextfileWindow::LoadTextfile(const char *textfile, Subdirectory dir)
319 if (textfile == nullptr) return;
321 this->lines.clear();
323 /* Get text from file */
324 size_t filesize;
325 FILE *handle = FioFOpenFile(textfile, "rb", dir, &filesize);
326 if (handle == nullptr) return;
328 this->text = ReallocT(this->text, filesize);
329 size_t read = fread(this->text, 1, filesize, handle);
330 fclose(handle);
332 if (read != filesize) return;
334 #if defined(WITH_ZLIB) || defined(WITH_LIBLZMA)
335 const char *suffix = strrchr(textfile, '.');
336 if (suffix == nullptr) return;
337 #endif
339 #if defined(WITH_ZLIB)
340 /* In-place gunzip */
341 if (strcmp(suffix, ".gz") == 0) Gunzip((byte**)&this->text, &filesize);
342 #endif
344 #if defined(WITH_LIBLZMA)
345 /* In-place xunzip */
346 if (strcmp(suffix, ".xz") == 0) Xunzip((byte**)&this->text, &filesize);
347 #endif
349 if (!this->text) return;
351 /* Add space for trailing \0 */
352 this->text = ReallocT(this->text, filesize + 1);
353 this->text[filesize] = '\0';
355 /* Replace tabs and line feeds with a space since str_validate removes those. */
356 for (char *p = this->text; *p != '\0'; p++) {
357 if (*p == '\t' || *p == '\r') *p = ' ';
360 /* Check for the byte-order-mark, and skip it if needed. */
361 char *p = this->text + (strncmp(u8"\ufeff", this->text, 3) == 0 ? 3 : 0);
363 /* Make sure the string is a valid UTF-8 sequence. */
364 str_validate(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);
366 /* Split the string on newlines. */
367 this->lines.push_back(p);
368 for (; *p != '\0'; p++) {
369 if (*p == '\n') {
370 *p = '\0';
371 this->lines.push_back(p + 1);
375 CheckForMissingGlyphs(true, this);
379 * Search a textfile file next to the given content.
380 * @param type The type of the textfile to search for.
381 * @param dir The subdirectory to search in.
382 * @param filename The filename of the content to look for.
383 * @return The path to the textfile, \c nullptr otherwise.
385 const char *GetTextfile(TextfileType type, Subdirectory dir, const char *filename)
387 static const char * const prefixes[] = {
388 "readme",
389 "changelog",
390 "license",
392 static_assert(lengthof(prefixes) == TFT_END);
394 const char *prefix = prefixes[type];
396 if (filename == nullptr) return nullptr;
398 static char file_path[MAX_PATH];
399 strecpy(file_path, filename, lastof(file_path));
401 char *slash = strrchr(file_path, PATHSEPCHAR);
402 if (slash == nullptr) return nullptr;
404 static const char * const exts[] = {
405 "txt",
406 #if defined(WITH_ZLIB)
407 "txt.gz",
408 #endif
409 #if defined(WITH_LIBLZMA)
410 "txt.xz",
411 #endif
414 for (size_t i = 0; i < lengthof(exts); i++) {
415 seprintf(slash + 1, lastof(file_path), "%s_%s.%s", prefix, GetCurrentLanguageIsoCode(), exts[i]);
416 if (FioCheckFileExists(file_path, dir)) return file_path;
418 seprintf(slash + 1, lastof(file_path), "%s_%.2s.%s", prefix, GetCurrentLanguageIsoCode(), exts[i]);
419 if (FioCheckFileExists(file_path, dir)) return file_path;
421 seprintf(slash + 1, lastof(file_path), "%s.%s", prefix, exts[i]);
422 if (FioCheckFileExists(file_path, dir)) return file_path;
424 return nullptr;