main
paths.c
1#include <string.h>
2#include <stdlib.h>
3#include "blastem.h"
4#include "util.h"
5
6static char **current_path;
7
8static void persist_path(void)
9{
10 char *pathfname = alloc_concat(get_userdata_dir(), PATH_SEP "blastem" PATH_SEP "sticky_path");
11 FILE *f = fopen(pathfname, "wb");
12 if (f) {
13 if (fwrite(*current_path, 1, strlen(*current_path), f) != strlen(*current_path)) {
14 warning("Failed to save menu path");
15 }
16 fclose(f);
17 } else {
18 warning("Failed to save menu path: Could not open %s for writing\n", pathfname);
19
20 }
21 free(pathfname);
22}
23
24void get_initial_browse_path(char **dst)
25{
26 *dst = NULL;
27 char *remember_path = tern_find_path(config, "ui\0remember_path\0", TVAL_PTR).ptrval;
28 if (!remember_path || !strcmp("on", remember_path)) {
29 char *pathfname = alloc_concat(get_userdata_dir(), PATH_SEP "blastem" PATH_SEP "sticky_path");
30 FILE *f = fopen(pathfname, "rb");
31 if (f) {
32 long pathsize = file_size(f);
33 if (pathsize > 0) {
34 *dst = malloc(pathsize + 1);
35 if (fread(*dst, 1, pathsize, f) != pathsize) {
36 warning("Error restoring saved file browser path");
37 free(*dst);
38 *dst = NULL;
39 } else {
40 (*dst)[pathsize] = 0;
41 }
42 }
43 fclose(f);
44 }
45 free(pathfname);
46 if (!current_path) {
47 atexit(persist_path);
48 current_path = dst;
49 }
50 }
51 if (!*dst) {
52 *dst = tern_find_path(config, "ui\0initial_path\0", TVAL_PTR).ptrval;
53 }
54 if (!*dst){
55 *dst = "$HOME";
56 }
57 tern_node *vars = tern_insert_ptr(NULL, "HOME", get_home_dir());
58 vars = tern_insert_ptr(vars, "EXEDIR", get_exe_dir());
59 *dst = replace_vars(*dst, vars, 1);
60 tern_free(vars);
61}
62
63char *path_append(const char *base, const char *suffix)
64{
65 if (!strcmp(suffix, "..")) {
66 size_t len = strlen(base);
67 while (len > 0) {
68 --len;
69 if (is_path_sep(base[len])) {
70 if (!len) {
71 //special handling for /
72 len++;
73 }
74 char *ret = malloc(len+1);
75 memcpy(ret, base, len);
76 ret[len] = 0;
77 return ret;
78 }
79 }
80 return strdup(PATH_SEP);
81 } else {
82 if (is_path_sep(base[strlen(base) - 1])) {
83 return alloc_concat(base, suffix);
84 } else {
85 char const *pieces[] = {base, PATH_SEP, suffix};
86 return alloc_concat_m(3, pieces);
87 }
88 }
89}