Testing functions to open files from bundle

This commit is contained in:
Francesco Abbate 2021-04-18 17:08:35 +02:00
parent 032018ec48
commit f913a8513f
4 changed files with 67 additions and 0 deletions

9
src/bundle_open.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef BUNDLE_OPEN_H
#define BUNDLE_OPEN_H
#include <stdio.h>
const char *resource_path_from_bundle();
FILE* open_fp_from_bundle_or_fallback(const char *file, const char *mode);
#endif

47
src/bundle_open.m Normal file
View File

@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#import <Foundation/Foundation.h>
#include "bundle_open.h"
const char *resource_path_from_bundle()
{ @autoreleasepool
{
NSFileManager* file_manager = [NSFileManager defaultManager];
NSString* resource_path = [[NSBundle mainBundle] resourcePath];
const char *resource_path_c = [resource_path UTF8String];
size_t len = strlen(resource_path_c);
char *resource_path_s = malloc(len + 1);
if (resource_path_s) {
memcpy(resource_path_s, resource_path_c, len + 1);
}
return resource_path_s;
}}
FILE* open_fp_from_bundle_or_fallback(const char *file, const char *mode)
{ @autoreleasepool
{
FILE* fp = NULL;
/* If the file mode is writable, skip all the bundle stuff because generally the bundle is read-only. */
if(strcmp("r", mode) && strcmp("rb", mode)) {
return fopen(file, mode);
}
NSFileManager* file_manager = [NSFileManager defaultManager];
NSString* resource_path = [[NSBundle mainBundle] resourcePath];
NSString* ns_string_file_component = [file_manager stringWithFileSystemRepresentation:file length:strlen(file)];
NSString* full_path_with_file_to_try = [resource_path stringByAppendingPathComponent:ns_string_file_component];
if([file_manager fileExistsAtPath:full_path_with_file_to_try]) {
fp = fopen([full_path_with_file_to_try fileSystemRepresentation], mode);
} else {
fp = fopen(file, mode);
}
return fp;
}}

View File

@ -13,6 +13,7 @@
#include <X11/Xresource.h>
#elif __APPLE__
#include <mach-o/dyld.h>
#include "bundle_open.h"
#endif
@ -102,6 +103,12 @@ int main(int argc, char **argv) {
SetProcessDPIAware();
#endif
#ifdef __APPLE__
const char *resource_path = resource_path_from_bundle();
fprintf(stderr, "resource path: %s\n", resource_path);
free(resource_path);
#endif
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
SDL_EnableScreenSaver();
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);

View File

@ -9,6 +9,10 @@ lite_sources = [
'main.c',
]
if host_machine.system() == 'darwin'
lite_sources += 'bundle_open.m'
endif
executable('lite',
lite_sources + lite_rc,
include_directories: [lite_include, font_renderer_include],