Debian Codegraph @

src/io/file.cpp

raw symbols SCIP
1
2 /**
3 *
4 * @file file.cpp
5 *
6 * Part of the OpenJazz project
7 *
8 * @par History:
9 * - 23rd August 2005: Created main.c
10 * - 22nd July 2008: Created util.c from parts of main.c
11 * - 3rd February 2009: Renamed util.c to util.cpp
12 * - 3rd February 2009: Created file.cpp from parts of util.cpp
13 *
14 * @par Licence:
15 * Copyright (c) 2005-2017 AJ Thomson
16 * Copyright (c) 2015-2026 Carsten Teibes
17 *
18 * OpenJazz is distributed under the terms of
19 * the GNU General Public License, version 2.0
20 *
21 * @par Description:
22 * Deals with files.
23 *
24 */
25
26
27 #include "file.h"
28
29 #include "io/gfx/video.h"
30 #include "util.h"
31 #include "io/log.h"
32
33 #include <string.h>
34 #include <unistd.h>
35 #include <miniz.h>
36
37 #ifdef OJ_SDL3
38 #include <SDL3/SDL.h>
39 #else
40 #include <SDL.h>
41 #endif
42
43 #if !(defined(_WIN32) || defined(WII) || defined(PSP))
44 #define UPPERCASE_FILENAMES
45 #define LOWERCASE_FILENAMES
46 #endif
47
48
49 /**
50 * Try opening a file from the available paths.
51 *
52 * @param name File name
53 * @param pathType Kind of directory
54 * @param write Whether or not the file can be written to
55 */
56 File::File (const char* name, int pathType, bool write) :
57 file(nullptr), filePath(nullptr), forWriting(write) {
58
59 Path* path = gamePaths.paths;
60
61 while (path) {
62
63 // skip other paths
64 if (pathType != PATH_TYPE_ANY && (path->pathType & pathType) != pathType) {
65 path = path->next;
66 continue;
67 }
68
69 // only allow certain write paths
70 if (!write || (pathType & (PATH_TYPE_CONFIG|PATH_TYPE_TEMP)) > 0) {
71 if (open(path->path, name, write)) return;
72 } else LOG_FATAL("Not allowed to write to %s", name);
73
74 path = path->next;
75
76 }
77
78 LOG_WARN("Could not open file: %s", name);
79
80 throw E_FILE;
81
82 }
83
84
85 /**
86 * Delete the file object.
87 */
88 File::~File () {
89
90 fclose(file);
91
92 LOG_TRACE("Closed file: %s", filePath);
93
94 delete[] filePath;
95
96 }
97
98
99 /**
100 * Try opening a file from the given path
101 *
102 * @param path Directory path
103 * @param name File name
104 * @param write Whether or not the file can be written to
105 */
106 bool File::open (const char* path, const char* name, bool write) {
107 const char *fileMode = write ? "wb": "rb";
108
109 // Create the file path for the given directory
110 filePath = createString(path, name);
111
112 // Open the file from the path
113 file = fopen(filePath, fileMode);
114
115 #ifdef UPPERCASE_FILENAMES
116 if (!file) {
117 uppercaseString(filePath + strlen(path));
118 file = fopen(filePath, fileMode);
119 }
120 #endif
121
122 #ifdef LOWERCASE_FILENAMES
123 if (!file) {
124 lowercaseString(filePath + strlen(path));
125 file = fopen(filePath, fileMode);
126 }
127 #endif
128
129 if (file) {
130 LOG_DEBUG("Opened file: %s", filePath);
131
132 return true;
133 }
134
135 delete[] filePath;
136
137 return false;
138 }
139
140
141 /**
142 * Get the size of the file.
143 *
144 * @return The size of the file
145 */
146 int File::getSize () {
147
148 int pos, size;
149
150 pos = ftell(file);
151
152 fseek(file, 0, SEEK_END);
153
154 size = ftell(file);
155
156 fseek(file, pos, SEEK_SET);
157
158 return size;
159
160 }
161
162
163 /**
164 * Get the current read/write location within the file.
165 *
166 * @return The current location
167 */
168 int File::tell () {
169
170 return ftell(file);
171
172 }
173
174
175 /**
176 * Set the read/write location within the file.
177 *
178 * @param offset The new offset
179 * @param reset Whether to offset from the current location or the start of the file
180 */
181 void File::seek (int offset, bool reset) {
182
183 fseek(file, offset, reset ? SEEK_SET: SEEK_CUR);
184
185 }
186
187
188 /**
189 * Load an unsigned char from the file.
190 *
191 * @return The value read
192 */
193 unsigned char File::loadChar () {
194
195 return fgetc(file);
196
197 }
198
199
200 void File::storeChar (unsigned char val) {
201
202 fputc(val, file);
203
204 }
205
206
207 /**
208 * Load an unsigned short int from the file.
209 *
210 * @return The value read
211 */
212 unsigned short int File::loadShort () {
213
214 unsigned short int val;
215
216 val = fgetc(file);
217 val += fgetc(file) << 8;
218
219 return val;
220
221 }
222
223
224 /**
225 * Load an unsigned short int with an upper limit from the file.
226 *
227 * @return The value read
228 */
229 unsigned short int File::loadShort (unsigned short int max) {
230
231 unsigned short int val;
232
233 val = loadShort();
234
235 if (val > max) {
236
237 LOG_ERROR("Oversized value %d>%d in file %s", val, max, filePath);
238
239 return max;
240
241 }
242
243 return val;
244
245 }
246
247
248 void File::storeShort (unsigned short int val) {
249
250 fputc(val & 255, file);
251 fputc(val >> 8, file);
252
253 }
254
255
256 /**
257 * Load a signed int from the file.
258 *
259 * @return The value read
260 */
261 signed int File::loadInt () {
262
263 unsigned int val;
264
265 val = fgetc(file);
266 val += fgetc(file) << 8;
267 val += fgetc(file) << 16;
268 val += fgetc(file) << 24;
269
270 return *((signed int *)&val);
271
272 }
273
274
275 void File::storeInt (signed int val) {
276
277 unsigned int uval;
278
279 uval = *((unsigned int *)&val);
280
281 fputc(uval & 255, file);
282 fputc((uval >> 8) & 255, file);
283 fputc((uval >> 16) & 255, file);
284 fputc(uval >> 24, file);
285
286 }
287
288
289 void File::storeData (void* data, int length) {
290
291 if(!forWriting) {
292 LOG_ERROR("File %s not opened for writing!", filePath);
293 return;
294 }
295
296 fwrite (data, length, 1, file);
297
298 }
299
300
301 /**
302 * Load a block of uncompressed data from the file.
303 *
304 * @param length The length of the block
305 *
306 * @return Buffer containing the block of data
307 */
308 unsigned char * File::loadBlock (int length) {
309
310 unsigned char *buffer;
311
312 buffer = new unsigned char[length];
313
314 int res = fread(buffer, 1, length, file);
315
316 if (res != length)
317 LOG_ERROR("Could not read whole block (%d of %d bytes read)", res, length);
318
319 return buffer;
320
321 }
322
323
324 /**
325 * Load a block of RLE compressed data from the file.
326 *
327 * @param length The length of the uncompressed block
328 * @param checkSize Whether or not the RLE block is terminated
329 *
330 * @return Buffer containing the uncompressed data
331 */
332 unsigned char* File::loadRLE (int length, bool checkSize) {
333 int size = 0;
334
335 if (checkSize) {
336 // Determine the offset that follows the block
337 size = loadShort();
338 }
339 int start = tell();
340
341 unsigned char* buffer = new unsigned char[length];
342
343 int pos = 0;
344 while (pos < length) {
345 unsigned char code = loadChar();
346 unsigned char amount = code & 127;
347
348 if (code & 128) { // repeat
349 unsigned char value = loadChar();
350
351 if (pos + amount >= length) break;
352
353 memset(buffer + pos, value, amount);
354 pos += amount;
355 } else if (amount) { // copy
356 if (pos + amount >= length) break;
357
358 fread(buffer + pos, 1, amount, file);
359 pos += amount;
360 } else { // end marker
361 buffer[pos++] = loadChar();
362 break;
363 }
364 }
365
366 if (checkSize) {
367 if (tell() != start + size)
368 LOG_DEBUG("RLE block has incorrect size: %d vs. %d", tell() - start, size);
369
370 seek(start + size, true);
371 } else {
372 LOG_MAX("RLE block was %d bytes long", tell() - start);
373 }
374
375 return buffer;
376
377 }
378
379
380 /**
381 * Skip past a block of RLE compressed data in the file.
382 */
383 void File::skipRLE () {
384
385 int next;
386
387 next = fgetc(file);
388 next += fgetc(file) << 8;
389
390 fseek(file, next, SEEK_CUR);
391
392 }
393
394
395 /**
396 * Load a block of LZ compressed data from the file.
397 *
398 * @param compressedLength The length of the compressed block
399 * @param length The length of the uncompressed block
400 *
401 * @return Buffer containing the uncompressed data
402 */
403 unsigned char* File::loadLZ (int compressedLength, int length) {
404
405 unsigned char* compressedBuffer;
406 unsigned char* buffer;
407
408 compressedBuffer = loadBlock(compressedLength);
409
410 buffer = new unsigned char[length];
411
412 uncompress(buffer, (unsigned long int *)&length, compressedBuffer, compressedLength);
413
414 delete[] compressedBuffer;
415
416 return buffer;
417
418 }
419
420
421 /**
422 * Load a terminated string from the file.
423 *
424 * @param maxSize maximum length of field in the file
425 *
426 * @return The new string
427 */
428 char * File::loadTerminatedString (int maxSize) {
429 char *string;
430 int length = loadChar();
431
432 if (maxSize > 0 && length > maxSize) {
433 LOG_WARN("Trimming oversized terminated string (%d > %d)", length, maxSize);
434 length = maxSize;
435 }
436
437 if (length) {
438 string = loadString(length);
439 } else {
440 string = new char[1];
441 string[0] = '\0';
442 }
443
444 // Skip until end of field
445 if(maxSize > length) {
446 seek(maxSize - length);
447 }
448
449 return string;
450 }
451
452
453 /**
454 * Load a 8.3 file name from the file.
455 *
456 * @return The new string
457 */
458 char * File::loadFileName () {
459 int length = 0;
460 char *string = new char[13];
461
462 for (int i = 0; i < 9; i++) {
463 string[i] = loadChar();
464
465 if (string[i] == '.') {
466 string[++i] = loadChar();
467 string[++i] = loadChar();
468 string[++i] = loadChar();
469 i++;
470
471 break;
472 }
473
474 length = i;
475 }
476
477 string[length] = 0;
478
479 return string;
480 }
481
482
483
484 /**
485 * Load a string with given length from the file.
486 *
487 * @return The new string
488 */
489 char * File::loadString (int length) {
490 char *string = new char[length + 1];
491 int res = fread(string, 1, length, file);
492
493 if (res != length)
494 LOG_ERROR("Could not read whole string (%d of %d bytes read)", res, length);
495
496 string[length] = '\0';
497
498 return string;
499 }
500
501
502 /**
503 * Load RLE compressed graphical data from the file.
504 *
505 * @param width The width of the image to load
506 * @param height The height of the image to load
507 * @param checkSize Whether or not the RLE block is terminated
508 *
509 * @return SDL surface containing the loaded image
510 */
511 SDL_Surface* File::loadSurface (int width, int height, bool checkSize) {
512
513 SDL_Surface* surface;
514 unsigned char* pixels;
515
516 pixels = loadRLE(width * height, checkSize);
517
518 surface = video.createSurface(pixels, width, height);
519
520 delete[] pixels;
521
522 return surface;
523
524 }
525
526
527 /**
528 * Load a block of scrambled pixel data from the file.
529 *
530 * @param length The length of the block
531 *
532 * @return Buffer containing the de-scrambled data
533 */
534 unsigned char* File::loadPixels (int length) {
535
536 unsigned char* pixels;
537 unsigned char* sorted;
538 int count;
539
540 sorted = new unsigned char[length];
541
542 pixels = loadBlock(length);
543
544 // Rearrange pixels in correct order
545 for (count = 0; count < length; count++) {
546
547 sorted[count] = pixels[(count >> 2) + ((count & 3) * (length >> 2))];
548
549 }
550
551 delete[] pixels;
552
553 return sorted;
554
555 }
556
557
558 /**
559 * Load a block of scrambled and masked pixel data from the file.
560 *
561 * @param length The length of the block
562 * @param key The transparent pixel value
563 *
564 * @return Buffer containing the de-scrambled data
565 */
566 unsigned char* File::loadPixels (int length, int key) {
567
568 unsigned char* pixels;
569 unsigned char* sorted;
570 unsigned char mask = 0;
571 int count;
572
573
574 sorted = new unsigned char[length];
575 pixels = new unsigned char[length];
576
577
578 // Read the mask
579 // Each mask pixel is either 0 or 1
580 // Four pixels are packed into the lower end of each byte
581 for (count = 0; count < length; count++) {
582
583 if (!(count & 3)) mask = fgetc(file);
584 pixels[count] = (mask >> (count & 3)) & 1;
585
586 }
587
588 // Pixels are loaded if the corresponding mask pixel is 1, otherwise
589 // the transparent index is used. Pixels are scrambled, so the mask
590 // has to be scrambled the same way.
591 for (count = 0; count < length; count++) {
592
593 sorted[(count >> 2) + ((count & 3) * (length >> 2))] = pixels[count];
594
595 }
596
597 // Read pixels according to the scrambled mask
598 for (count = 0; count < length; count++) {
599
600 // Use the transparent pixel
601 pixels[count] = key;
602
603 if (sorted[count] == 1) {
604
605 // The unmasked portions are transparent, so no masked
606 // portion should be transparent.
607 while (pixels[count] == key) pixels[count] = fgetc(file);
608
609 }
610
611 }
612
613 // Rearrange pixels in correct order
614 for (count = 0; count < length; count++) {
615
616 sorted[count] = pixels[(count >> 2) + ((count & 3) * (length >> 2))];
617
618 }
619
620 delete[] pixels;
621
622 return sorted;
623
624 }
625
626
627 /**
628 * Load a palette from the file.
629 *
630 * @param palette The palette to be filled with loaded colours
631 * @param rle Whether or not the palette data is RLE-encoded
632 */
633 void File::loadPalette (SDL_Color* palette, bool rle) {
634
635 unsigned char* buffer;
636 int count;
637
638 if (rle) buffer = loadRLE(MAX_PALETTE_COLORS * 3);
639 else buffer = loadBlock(MAX_PALETTE_COLORS * 3);
640
641 for (count = 0; count < MAX_PALETTE_COLORS; count++) {
642
643 // Palette entries are 6-bit
644 // Shift them upwards to 8-bit, and fill in the lower 2 bits
645 palette[count].r = (buffer[count * 3] << 2) + (buffer[count * 3] >> 4);
646 palette[count].g = (buffer[(count * 3) + 1] << 2) + (buffer[(count * 3) + 1] >> 4);
647 palette[count].b = (buffer[(count * 3) + 2] << 2) + (buffer[(count * 3) + 2] >> 4);
648
649 }
650
651 delete[] buffer;
652
653 }
654
655
656 PathMgr::PathMgr():
657 paths(NULL), has_config(false), has_temp(false) {
658
659 };
660
661 PathMgr::~PathMgr() {
662 delete paths;
663 };
664
665 bool PathMgr::add(char* newPath, int newPathType) {
666
667 // Check for CWD
668 if(!strlen(newPath)) {
669 delete[] newPath;
670
671 char cwd[1024];
672 if (getcwd(cwd, sizeof(cwd)) != NULL) {
673 newPath = createString(cwd);
674 } else {
675 LOG_WARN("Could not get current working directory!");
676 return false;
677 }
678 }
679
680 // Append a directory separator if necessary
681 if (newPath[strlen(newPath) - 1] != OJ_DIR_SEP) {
682 char* tmp = createString(newPath, OJ_DIR_SEP_STR);
683 delete[] newPath;
684 newPath = tmp;
685 }
686
687 // all paths need to be readable
688 if (access(newPath, R_OK) != 0) {
689 LOG_TRACE("Path '%s' is not readable, ignoring!", newPath);
690 delete[] newPath;
691 return false;
692 }
693
694 // ignore, if already present
695 if(has_config) newPathType &= ~PATH_TYPE_CONFIG;
696 if(has_temp) newPathType &= ~PATH_TYPE_TEMP;
697
698 // config and temp dir need to be writeable
699 if ((newPathType & (PATH_TYPE_CONFIG|PATH_TYPE_TEMP)) > 0) {
700 if (access(newPath, W_OK) != 0) {
701 LOG_WARN("Path '%s' is not writeable, disabling!", newPath);
702
703 newPathType &= ~PATH_TYPE_CONFIG;
704 newPathType &= ~PATH_TYPE_TEMP;
705 }
706 }
707
708 if(newPathType == PATH_TYPE_INVALID) {
709 delete[] newPath;
710 return false;
711 }
712
713 // we only need one directory for these
714 if (newPathType & PATH_TYPE_CONFIG) has_config = true;
715 if (newPathType & PATH_TYPE_TEMP) has_temp = true;
716
717 // Finally add
718 paths = new Path(paths, newPath, newPathType);
719
720 return true;
721 }
722
723
724 /**
725 * Create a new directory path object.
726 *
727 * @param newNext Next path
728 * @param newPath The new path
729 */
730 Path::Path (Path* newNext, char* newPath, int newPathType) {
731
732 char pathInfo[10] = {};
733 if(newPathType & PATH_TYPE_SYSTEM) strcat(pathInfo, "S");
734 if(newPathType & PATH_TYPE_CONFIG) strcat(pathInfo, "C");
735 if(newPathType & PATH_TYPE_GAME) strcat(pathInfo, "G");
736 if(newPathType & PATH_TYPE_TEMP) strcat(pathInfo, "T");
737 if(newPathType & PATH_TYPE_ANY) strcat(pathInfo, "A");
738
739 LOG_DEBUG("Adding '%s' to the path list [%s]", newPath, pathInfo);
740
741 next = newNext;
742 path = newPath;
743 pathType = newPathType;
744
745 }
746
747
748 /**
749 * Delete the directory path object.
750 */
751 Path::~Path () {
752
753 if (next) delete next;
754 delete[] path;
755
756 }