chiark / gitweb /
lib/home.c: Introduce functions for building pathmames in home directories.
[disorder] / lib / home.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2020 Mark Wooding
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/home.c
19  * @brief Find things in the user's home directory
20  */
21
22 #include "common.h"
23
24 #include <errno.h>
25
26 #if HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #if HAVE_PWD_H
30 # include <pwd.h>
31 #endif
32 #if HAVE_SHLOBJ_H
33 # include <Shlobj.h>
34 #endif
35
36 #include "mem.h"
37 #include "home.h"
38 #include "log.h"
39 #include "printf.h"
40
41 #if _WIN32
42 #  define DIRSEP "\\"
43 #else
44 #  define DIRSEP "/"
45 #endif
46
47 static char *profiledir;
48
49
50 /** @brief Return the user's profile directory
51  * @return profile directory
52  * On Unix, this defaults to `$HOME/.disorder/'; on Windows, it's
53  * `%APPDATA%\DisOrder\'.  The trailing delimiter is included.
54  */
55 const char *profile_directory(void) {
56   char *t;
57
58   if(profiledir) return profiledir;
59 #if _WIN32
60   wchar_t *wpath = 0;
61   char *appdata;
62   if(SHGetKnownFolderPath(&FOLDERID_RoamingAppData, 0, NULL, &wpath) != S_OK) {
63     disorder_error(0, "error calling SHGetKnownFolderPath");
64     return 0;
65   }
66   t = win_wtomb(wpath);
67   CoTaskMemFree(wpath);
68   byte_xasprintf(&profiledir, "%s\\DisOrder", appdata);
69 #else
70   struct passwd *pw;
71   if(!(t = getenv("HOME"))) {
72     if(!(pw = getpwuid(getuid())))
73       disorder_error(0, "user not found in password database");
74     t = pw->pw_dir;
75   }
76   byte_xasprintf(&profiledir, "%s/.disorder", t);
77 #endif
78   return profiledir;
79 }
80
81 /** @brief Return the name of a file within the user's profile directory
82  * @param file Basename of the file desired
83  * @return Full path name of selected file.
84  * This currently doesn't do anything very useful with directory separators
85  * within @a file.
86  */
87 char *profile_filename(const char *file) {
88   const char *d;
89   char *t;
90   if(!(d = profile_directory())) return 0;
91   byte_xasprintf(&t, "%s" DIRSEP "%s", d, file);
92   return t;
93 }
94
95 /*
96 Local Variables:
97 c-basic-offset:2
98 comment-column:40
99 fill-column:79
100 indent-tabs-mode:nil
101 End:
102 */