| 1 | // LAF FreeType Wrapper |
| 2 | // Copyright (c) 2020 Igara Studio S.A. |
| 3 | // Copyright (c) 2016-2018 David Capello |
| 4 | // |
| 5 | // This file is released under the terms of the MIT license. |
| 6 | // Read LICENSE.txt for more information. |
| 7 | |
| 8 | #include "ft/stream.h" |
| 9 | |
| 10 | #include "base/file_handle.h" |
| 11 | #include "base/debug.h" |
| 12 | |
| 13 | #include <ft2build.h> |
| 14 | |
| 15 | #define STREAM_FILE(stream) ((FILE*)stream->descriptor.pointer) |
| 16 | |
| 17 | namespace ft { |
| 18 | |
| 19 | static void ft_stream_close(FT_Stream stream) |
| 20 | { |
| 21 | fclose(STREAM_FILE(stream)); |
| 22 | free(stream); |
| 23 | } |
| 24 | |
| 25 | static unsigned long ft_stream_io(FT_Stream stream, |
| 26 | unsigned long offset, |
| 27 | unsigned char* buffer, |
| 28 | unsigned long count) |
| 29 | { |
| 30 | if (!count && offset > stream->size) |
| 31 | return 1; |
| 32 | |
| 33 | FILE* file = STREAM_FILE(stream); |
| 34 | if (stream->pos != offset) |
| 35 | fseek(file, (long)offset, SEEK_SET); |
| 36 | |
| 37 | return (unsigned long)fread(buffer, 1, count, file); |
| 38 | } |
| 39 | |
| 40 | FT_Stream open_stream(const std::string& utf8Filename) |
| 41 | { |
| 42 | FT_Stream stream = nullptr; |
| 43 | stream = (FT_Stream)malloc(sizeof(*stream)); |
| 44 | if(!stream) |
| 45 | return nullptr; |
| 46 | memset(stream, 0, sizeof(*stream)); |
| 47 | |
| 48 | TRACE("FT: Loading font %s... " , utf8Filename.c_str()); |
| 49 | |
| 50 | FILE* file = base::open_file_raw(utf8Filename, "rb" ); |
| 51 | if (!file) { |
| 52 | free(stream); |
| 53 | TRACE("FAIL\n" ); |
| 54 | return nullptr; |
| 55 | } |
| 56 | |
| 57 | fseek(file, 0, SEEK_END); |
| 58 | stream->size = (unsigned long)ftell(file); |
| 59 | if (!stream->size) { |
| 60 | fclose(file); |
| 61 | free(stream); |
| 62 | TRACE("FAIL\n" ); |
| 63 | return nullptr; |
| 64 | } |
| 65 | fseek(file, 0, SEEK_SET); |
| 66 | |
| 67 | stream->descriptor.pointer = file; |
| 68 | stream->base = nullptr; |
| 69 | stream->pos = 0; |
| 70 | stream->read = ft_stream_io; |
| 71 | stream->close = ft_stream_close; |
| 72 | |
| 73 | TRACE("OK\n" ); |
| 74 | return stream; |
| 75 | } |
| 76 | |
| 77 | } // namespace ft |
| 78 | |