Debian Codegraph @

gutils/fsys.cpp

raw
1 /* Copyright (C) 2000-2004 by George Williams */
2 /*
3 * Redistribution and use in source and binary forms, with or without
4 * modification, are permitted provided that the following conditions are met:
5
6 * Redistributions of source code must retain the above copyright notice, this
7 * list of conditions and the following disclaimer.
8
9 * Redistributions in binary form must reproduce the above copyright notice,
10 * this list of conditions and the following disclaimer in the documentation
11 * and/or other materials provided with the distribution.
12
13 * The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include <fontforge-config.h>
29
30 #include "basics.h"
31 #include "ffglib_compat.h"
32 #include "ffprocess.h"
33 #include "gfile.h"
34 #include "ustring.h"
35
36 #ifdef HAVE_GLIB
37 #include "ffglib.h"
38 #endif
39
40 #include <errno.h> /* for mkdir_p */
41 #include <fcntl.h>
42 #include <stdio.h>
43 #include <sys/stat.h> /* for mkdir */
44 #include <sys/types.h>
45
46 #ifdef _MSC_VER
47 #include <direct.h>
48 #include <io.h>
49 #include <shlobj.h>
50 #include <windows.h>
51 /* S_ISDIR not defined on MSVC */
52 #ifndef S_ISDIR
53 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
54 #endif
55 #elif defined(__MINGW32__)
56 #include <shlobj.h>
57 #include <windows.h>
58 #include <sys/param.h>
59 #include "ffunistd.h"
60 #else
61 #include <pwd.h>
62 #include <sys/param.h>
63 #include "ffunistd.h"
64 #endif
65
66 static char *program_root = NULL;
67 static bool devel_env = false;
68
69 /**
70 * \brief Removes the extension from a file path, if it exists.
71 * This method assumes that the path is already normalized.
72 * \param path The path to be modified. Is modified in-place.
73 * \return A pointer to the input path.
74 */
75 char *GFileRemoveExtension(char *path) {
76 char *ext = strrchr(path, '.');
77 if (ext) {
78 char *fp = strrchr(path, '/');
79 if (!fp || ext > fp) {
80 *ext = '\0';
81 }
82 }
83 return path;
84 }
85
86 /**
87 * \brief Normalizes the file path as necessary.
88 * On Windows, this means changing backlashes to slashes.
89 *
90 * \param path The file path to be modified. Is modified in-place.
91 * \return A pointer to the input path
92 */
93 char *GFileNormalizePath(char *path) {
94 #if defined(_MSC_VER) || defined(__MINGW32__)
95 char *ptr;
96 for(ptr = path; *ptr; ptr++) {
97 if (*ptr == '\\') {
98 *ptr = '/';
99 }
100 }
101 #endif
102 return path;
103 }
104
105 /**
106 * \brief Normalizes the file path as necessary.
107 * Unicode version of GFileNormalizePath.
108 *
109 * \param path The file path to be modified. Is modified in-place.
110 * \return A pointer to the input path
111 */
112 unichar_t *u_GFileNormalizePath(unichar_t *path) {
113 #if defined(_MSC_VER) || defined(__MINGW32__)
114 unichar_t *ptr;
115 for (ptr = path; *ptr; ptr++) {
116 if (*ptr == '\\') {
117 *ptr = '/';
118 }
119 }
120 #endif
121 return path;
122 }
123
124 /* make directories. make parent directories as needed, with no error if
125 * the path already exists */
126 int mkdir_p(const char *path, mode_t mode) {
127 ff_stat_t st;
128 const char *e;
129 char *p = NULL;
130 char tmp[1024];
131 size_t len;
132 int r;
133
134 /* ensure the path is valid */
135 if(!(e = strrchr(path, '/')))
136 return -EINVAL;
137 /* ensure path is a directory */
138 r = ff_stat(path, &st);
139 if (r == 0 && !S_ISDIR(st.st_mode))
140 return -ENOTDIR;
141
142 /* copy the pathname */
143 snprintf(tmp, sizeof(tmp),"%s", path);
144 len = strlen(tmp);
145 if(tmp[len - 1] == '/')
146 tmp[len - 1] = 0;
147
148 /* iterate mkdir over the path */
149 for(p = tmp + 1; *p; p++)
150 if(*p == '/') {
151 *p = 0;
152 r = GFileMkDir(tmp, mode);
153 if (r < 0 && errno != EEXIST)
154 return -errno;
155 *p = '/';
156 }
157
158 /* try to make the whole path */
159 r = GFileMkDir(tmp, mode);
160 if(r < 0 && errno != EEXIST)
161 return -errno;
162 /* creation successful or the file already exists */
163 return EXIT_SUCCESS;
164 }
165
166 char *GFileGetHomeDir(void) {
167 #if defined(_MSC_VER) || defined(__MINGW32__)
168 char* dir = getenv("HOME");
169 if(!dir)
170 dir = getenv("USERPROFILE");
171 if(dir){
172 char* buffer = copy(dir);
173 GFileNormalizePath(buffer);
174 return buffer;
175 }
176 return NULL;
177 #else
178 static char *dir;
179 uid_t uid;
180 struct passwd *pw;
181
182 dir = getenv("HOME");
183 if ( dir!=NULL )
184 return( copy(dir) );
185
186 uid = getuid();
187 while ( (pw=getpwent())!=NULL ) {
188 if ( pw->pw_uid==uid ) {
189 dir = copy(pw->pw_dir);
190 endpwent();
191 return( dir );
192 }
193 }
194 endpwent();
195 return( NULL );
196 #endif
197 }
198
199 unichar_t *u_GFileGetHomeDir(void) {
200 unichar_t* dir = NULL;
201 char* tmp = GFileGetHomeDir();
202 if( tmp ) {
203 dir = uc_copy(tmp);
204 free(tmp);
205 }
206 return dir;
207 }
208
209 static void savestrcpy(char *dest,const char *src) {
210 for (;;) {
211 *dest = *src;
212 if ( *dest=='\0' )
213 break;
214 ++dest; ++src;
215 }
216 }
217
218 char *GFileGetAbsoluteName(const char *name) {
219 if (!name) {
220 return NULL;
221 } else if (!strncasecmp(name, "file://", 7)) {
222 name += 7;
223 }
224
225 char *abs = ff_canonical_path(name);
226 if (!abs) {
227 return copy(name); // Fallback to just copying
228 }
229 // If the input ends with '/', preserve that trailing slash
230 const char *tail = strrchr(name, '/');
231 if (tail && tail[1] == '\0') {
232 char *ret = smprintf("%s/", abs);
233 free(abs);
234 return GFileNormalizePath(ret);
235 }
236 return GFileNormalizePath(abs);
237 }
238
239 char *GFileBuildName(char *dir,char *fname,char *buffer,size_t size) {
240 int len;
241
242 if ( dir==NULL || *dir=='\0' ) {
243 if ( strlen( fname )<size-1 ) /* valgrind didn't like my strncpies but this complication makes it happy */
244 savestrcpy(buffer,fname);
245 else {
246 strncpy(buffer,fname,size-1);
247 buffer[size-1]='\0';
248 }
249 } else {
250 if ( buffer!=dir ) {
251 if ( strlen( dir )<size-3 )
252 strcpy(buffer,dir);
253 else {
254 strncpy(buffer,dir,size-3);
255 buffer[size-3]='\0';
256 }
257 }
258 len = strlen(buffer);
259 if ( buffer[len-1]!='/' )
260 buffer[len++] = '/';
261 if ( strlen( fname )<size-1 )
262 strcpy(buffer+len,fname);
263 else {
264 strncpy(buffer+len,fname,size-len-1);
265 buffer[size-1]='\0';
266 }
267 }
268 return( buffer );
269 }
270
271 /* Given a filename in a directory, pick the directory out of it, and */
272 /* create a new filename using that directory and the given nametail */
273 char *GFileReplaceName(char *oldname,char *fname,char *buffer,size_t size) {
274 int len;
275 char *dirend;
276
277 dirend = strrchr(oldname,'/');
278 if ( dirend == NULL ) {
279 strncpy(buffer,fname,size-1);
280 buffer[size-1]='\0';
281 } else {
282 *dirend = '\0';
283 if ( buffer!=oldname ) {
284 strncpy(buffer,oldname,size-3);
285 buffer[size-3]='\0';
286 }
287 len = strlen(buffer);
288 *dirend = '/';
289 buffer[len++] = '/';
290 strncpy(buffer+len,fname,size-len-1);
291 buffer[size-1]='\0';
292 }
293 return( buffer );
294 }
295
296 char *GFileNameTail(const char *oldname) {
297 const char *pt = strrchr(oldname,'/');
298
299 // a final slash was found, so we know that p+1 is a valid
300 // address in the string.
301 if ( pt )
302 return( (char *)(pt+1));
303
304 return( (char *)oldname );
305 }
306
307 char *GFileAppendFile(char *dir,char *name,int isdir) {
308 char *ret, *pt;
309
310 ret = (char *) malloc((strlen(dir)+strlen(name)+3));
311 strcpy(ret,dir);
312 pt = ret+strlen(ret);
313 if ( pt>ret && pt[-1]!='/' )
314 *pt++ = '/';
315 strcpy(pt,name);
316 if ( isdir ) {
317 pt += strlen(pt);
318 if ( pt>ret && pt[-1]!='/' ) {
319 *pt++ = '/';
320 *pt = '\0';
321 }
322 }
323 return(ret);
324 }
325
326 int GFileIsAbsolute(const char *file) {
327 #if defined(_MSC_VER) || defined(__MINGW32__)
328 if( (file[1]==':') && (('a'<=file[0] && file[0]<='z') || ('A'<=file[0] && file[0]<='Z')) )
329 return ( true );
330 #else
331 if ( *file=='/' )
332 return( true );
333 #endif
334 if ( strstr(file,"://")!=NULL )
335 return( true );
336
337 return( false );
338 }
339
340 int GFileIsDir(const char *file) {
341 ff_stat_t info;
342 if ( ff_stat(file, &info)==-1 )
343 return 0;
344 else
345 return( S_ISDIR(info.st_mode) );
346 }
347
348 int GFileExists(const char *file) {
349 return( access(file,0)==0 );
350 }
351
352 int GFileModifyable(const char *file) {
353 return( access(file,02)==0 );
354 }
355
356 int GFileModifyableDir(const char *file) {
357 char buffer[1025], *pt;
358
359 buffer[1024]=0;
360 strncpy(buffer,file,1024);
361 pt = strrchr(buffer,'/');
362 if ( pt==NULL )
363 strcpy(buffer,".");
364 else
365 *pt='\0';
366 return( GFileModifyable(buffer) );
367 }
368
369 int GFileReadable(const char *file) {
370 return( access(file,04)==0 );
371 }
372
373 /**
374 * Creates a temporary file, similar to tmpfile.
375 * Used because the default tmpfile implementation on Windows is broken
376 */
377 FILE *GFileTmpfile() {
378 #ifndef _WIN32
379 return tmpfile();
380 #else
381 wchar_t temp_path[MAX_PATH + 1];
382 DWORD ret = GetTempPathW(MAX_PATH + 1, temp_path);
383 if (!ret) {
384 return NULL;
385 }
386
387 while(true) {
388 wchar_t *temp_name = _wtempnam(temp_path, L"FF_");
389 if (!temp_name) {
390 return NULL;
391 }
392
393 HANDLE handle = CreateFileW(
394 temp_name,
395 GENERIC_READ | GENERIC_WRITE,
396 0,
397 NULL,
398 CREATE_NEW,
399 FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
400 NULL
401 );
402 free(temp_name);
403
404 if (handle == INVALID_HANDLE_VALUE) {
405 if (GetLastError() != ERROR_FILE_EXISTS) {
406 return NULL;
407 }
408 } else {
409 int fd = _open_osfhandle((intptr_t)handle, _O_RDWR|_O_CREAT|_O_TEMPORARY|_O_BINARY);
410 if (fd == -1) {
411 CloseHandle(handle);
412 return NULL;
413 }
414
415 FILE *fp = _fdopen(fd, "w+");
416 if (!fp) {
417 _close(fd);
418 return NULL;
419 }
420
421 return fp;
422 }
423 }
424 return NULL;
425 #endif
426 }
427
428 /**
429 * Removes a file or folder.
430 *
431 * @param [in] path The path to be removed.
432 * @param [in] recursive Specify true to remove a folder and all of its
433 * sub-contents.
434 * @return true if the deletion was successful or the path does not exist. It
435 * will fail if trying to remove a directory that is not empty and
436 * where `recursive` is false.
437 */
438 int GFileRemove(const char *path, int recursive) {
439 if (recursive) {
440 return ff_remove_all(path) >= 0;
441 } else {
442 return ff_unlink(path) == 0 || ff_rmdir(path) == 0 || !GFileExists(path);
443 }
444 }
445
446 int GFileMkDir(const char *name, int mode) {
447 #ifndef _WIN32
448 return mkdir(name, mode);
449 #else
450 return mkdir(name);
451 #endif
452 }
453
454 int GFileRmDir(const char *name) {
455 return(rmdir(name));
456 }
457
458 int GFileUnlink(const char *name) {
459 return(unlink(name));
460 }
461
462 unichar_t *u_GFileBuildName(unichar_t *dir,unichar_t *fname,unichar_t *buffer,int size) {
463 int len;
464
465 if ( dir==NULL || *dir=='\0' ) {
466 u_strncpy(buffer,fname,size-1);
467 buffer[size-1]='\0';
468 } else {
469 if ( buffer!=dir ) {
470 u_strncpy(buffer,dir,size-3);
471 buffer[size-3]='\0';
472 }
473 len = u_strlen(buffer);
474 if ( buffer[len-1]!='/' )
475 buffer[len++] = '/';
476 u_strncpy(buffer+len,fname,size-len-1);
477 buffer[size-1]='\0';
478 }
479 return( buffer );
480 }
481
482 /* Given a filename in a directory, pick the directory out of it, and */
483 /* create a new filename using that directory and the given nametail */
484 unichar_t *u_GFileReplaceName(unichar_t *oldname,unichar_t *fname,unichar_t *buffer,int size) {
485 int len;
486 unichar_t *dirend;
487
488 dirend = u_strrchr(oldname,'/');
489 if ( dirend == NULL ) {
490 u_strncpy(buffer,fname,size-1);
491 buffer[size-1]='\0';
492 } else {
493 *dirend = '\0';
494 if ( buffer!=oldname ) {
495 u_strncpy(buffer,oldname,size-3);
496 buffer[size-3]='\0';
497 }
498 len = u_strlen(buffer);
499 *dirend = '/';
500 buffer[len++] = '/';
501 u_strncpy(buffer+len,fname,size-len-1);
502 buffer[size-1]='\0';
503 }
504 return( buffer );
505 }
506
507 unichar_t *u_GFileNameTail(const unichar_t *oldname) {
508 unichar_t *pt;
509
510 pt = u_strrchr(oldname,'/');
511 if ( pt !=NULL )
512 return( pt+1);
513 else
514 return( (unichar_t *)oldname );
515 }
516
517 /**
518 * Remove the 'root' part of the file path if it is absolute;
519 * On Unix this is '/' and on Windows this is for e.g. 'C:/'
520 */
521 static unichar_t *u_GFileRemoveRoot(unichar_t *path) {
522 //May happen on Windows too e.g. CygWin
523 if (*path == '/') {
524 path++;
525 }
526 #ifdef _WIN32
527 //Check if it is a drive letter path
528 else if (((path[0] >= 'A' && path[0] <= 'Z') ||
529 (path[0] >= 'a' && path[0] <= 'z')) &&
530 path[1] == ':' && path[2] == '/') {
531
532 path += 3;
533 }
534 #endif
535 return path;
536 }
537
538 unichar_t *u_GFileNormalize(unichar_t *name) {
539 unichar_t *pt, *base, *ppt;
540
541 if ( (pt = uc_strstr(name,"://"))!=NULL ) {
542 base = u_strchr(pt+3,'/');
543 if ( base==NULL )
544 return( name );
545 ++base;
546 }
547
548 base = u_GFileRemoveRoot(name);
549 for ( pt=base; *pt!='\0'; ) {
550 if ( *pt=='/' )
551 u_strcpy(pt,pt+1);
552 else if ( uc_strncmp(pt,"./",2)==0 )
553 u_strcpy(pt,pt+2);
554 else if ( uc_strncmp(pt,"../",2)==0 ) {
555 for ( ppt=pt-2; ppt>=base && *ppt!='/'; --ppt );
556 ++ppt;
557 if ( ppt>=base ) {
558 u_strcpy(ppt,pt+3);
559 pt = ppt;
560 } else
561 pt += 3;
562 } else {
563 while ( *pt!='/' && *pt!='\0' ) ++pt;
564 if ( *pt == '/' ) ++pt;
565 }
566 }
567 return( name );
568 }
569
570 unichar_t *u_GFileAppendFile(unichar_t *dir,unichar_t *name,int isdir) {
571 unichar_t *ret, *pt;
572
573 ret = (unichar_t *) malloc((u_strlen(dir)+u_strlen(name)+3)*sizeof(unichar_t));
574 u_strcpy(ret,dir);
575 pt = ret+u_strlen(ret);
576 if ( pt>ret && pt[-1]!='/' )
577 *pt++ = '/';
578 u_strcpy(pt,name);
579 if ( isdir ) {
580 pt += u_strlen(pt);
581 if ( pt>ret && pt[-1]!='/' ) {
582 *pt++ = '/';
583 *pt = '\0';
584 }
585 }
586 return(ret);
587 }
588
589 int u_GFileIsAbsolute(const unichar_t *file) {
590 #if defined(_MSC_VER) || defined(__MINGW32__)
591 if( (file[1]==':') && (('a'<=file[0] && file[0]<='z') || ('A'<=file[0] && file[0]<='Z')) )
592 return ( true );
593 #else
594 if ( *file=='/' )
595 return( true );
596 #endif
597 if ( uc_strstr(file,"://")!=NULL )
598 return( true );
599
600 return( false );
601 }
602
603 int u_GFileIsDir(const unichar_t *file) {
604 char buffer[1024];
605 u2def_strncpy(buffer,file,sizeof(buffer));
606 return GFileIsDir(buffer);
607 }
608
609 int u_GFileExists(const unichar_t *file) {
610 char buffer[1024];
611 u2def_strncpy(buffer,file,sizeof(buffer));
612 return( access(buffer,0)==0 );
613 }
614
615 int u_GFileModifyable(const unichar_t *file) {
616 char buffer[1024];
617 u2def_strncpy(buffer,file,sizeof(buffer));
618 return( access(buffer,02)==0 );
619 }
620
621 int u_GFileModifyableDir(const unichar_t *file) {
622 char buffer[1024], *pt;
623
624 u2def_strncpy(buffer,file,sizeof(buffer));
625 pt = strrchr(buffer,'/');
626 if ( pt==NULL )
627 strcpy(buffer,".");
628 else
629 *pt='\0';
630 return( GFileModifyable(buffer));
631 }
632
633 int u_GFileReadable(unichar_t *file) {
634 char buffer[1024];
635 u2def_strncpy(buffer,file,sizeof(buffer));
636 return( access(buffer,04)==0 );
637 }
638
639 int u_GFileMkDir(unichar_t *name) {
640 char buffer[1024];
641 u2def_strncpy(buffer,name,sizeof(buffer));
642 return GFileMkDir(buffer, 0755);
643 }
644
645 int u_GFileRmDir(unichar_t *name) {
646 char buffer[1024];
647 u2def_strncpy(buffer,name,sizeof(buffer));
648 return(rmdir(buffer));
649 }
650
651 int u_GFileUnlink(unichar_t *name) {
652 char buffer[1024];
653 u2def_strncpy(buffer,name,sizeof(buffer));
654 return(unlink(buffer));
655 }
656
657 void FindProgRoot(const char *prog) {
658 char *tmp = NULL;
659 char *rprog = NULL;
660 if (program_root != NULL) {
661 return;
662 }
663
664 #ifdef _WIN32
665 char path[MAX_PATH+4];
666 unsigned int len = GetModuleFileNameA(NULL, path, MAX_PATH);
667 path[len] = '\0';
668 prog = GFileNormalizePath(path);
669 #endif
670
671 if (prog != NULL) {
672 if (strchr(prog, '/') == NULL) {
673 // Program invoked without path - need to search PATH
674 // For Python module context this won't happen (prog is NULL)
675 #ifdef HAVE_GLIB
676 prog = rprog = g_find_program_in_path(prog);
677 #else
678 prog = NULL; // Skip to fallback
679 #endif
680 }
681 if (prog) {
682 tmp = smprintf("%s/../..", prog);
683 program_root = GFileGetAbsoluteName(tmp);
684 free(tmp);
685 }
686 }
687
688 if (program_root == NULL) {
689 program_root = GFileGetAbsoluteName(FONTFORGE_INSTALL_PREFIX);
690 }
691
692 // Sigh glib doesn't provide symlink resolution
693 #ifdef HAVE_REALPATH
694 tmp = smprintf("%s/share/fontforge", program_root);
695 if (!GFileExists(tmp)) {
696 free(tmp);
697 if (prog != NULL) {
698 tmp = realpath(prog, NULL);
699 if (tmp) {
700 char *real_root = smprintf("%s/../..", tmp);
701 free(tmp);
702 free(program_root);
703
704 program_root = GFileGetAbsoluteName(real_root);
705 free(real_root);
706 }
707 }
708 } else {
709 free(tmp);
710 }
711 #endif
712
713 /* If the fontforge binary path includes "build",
714 we are in the development mode. */
715 if (strstr(program_root, "build")) {
716 devel_env = true;
717 }
718
719 #ifdef HAVE_GLIB
720 g_free(rprog);
721 #else
722 free(rprog);
723 #endif
724 TRACE("Program root: %s\n", program_root);
725 }
726
727 const char *getShareDir(void) {
728 static char *sharedir=NULL;
729 if (!sharedir) {
730 sharedir = smprintf("%s/share/fontforge", program_root);
731 }
732 return sharedir;
733 }
734
735 const char *getLocaleDir(void) {
736 static char *localedir = NULL;
737 if (!localedir) {
738 if (devel_env) {
739 localedir = smprintf("%s/po", program_root);
740 } else {
741 localedir = smprintf("%s/share/locale", program_root);
742 }
743 }
744 return localedir;
745 }
746
747 const char *getPixmapDir(void) {
748 static char *pixmapdir=NULL;
749 if (!pixmapdir) {
750 if (devel_env) {
751 /* GUI_THEME macro is imported from the CMake ${GUI_THEME} variable */
752 char *theme_src = smprintf("%s/../fontforgeexe/pixmaps/%s", program_root, GUI_THEME);
753 pixmapdir = GFileGetAbsoluteName(theme_src);
754 free(theme_src);
755 } else {
756 pixmapdir = smprintf("%s/pixmaps", getShareDir());
757 }
758 }
759 return pixmapdir;
760 }
761
762 const char *getHelpDir(void) {
763 static char *helpdir=NULL;
764 if (!helpdir) {
765 helpdir = smprintf("%s/share/doc/fontforge/", program_root);
766 }
767 return helpdir;
768 }
769
770 /* reimplementation of GFileGetHomeDir, avoiding copy(). Returns NULL if home
771 * directory cannot be found */
772 const char *getUserHomeDir(void) {
773 #if defined(_MSC_VER) || defined(__MINGW32__)
774 char* dir = getenv("APPDATA");
775 if( dir==NULL )
776 dir = getenv("USERPROFILE");
777 if( dir!=NULL ) {
778 GFileNormalizePath(dir);
779 return dir;
780 }
781 return NULL;
782 #else
783 uid_t uid;
784 struct passwd *pw;
785 char *home = getenv("HOME");
786
787 if( home!=NULL )
788 return home;
789
790 uid = getuid();
791 while( (pw=getpwent())!=NULL ) {
792 if ( pw->pw_uid==uid ) {
793 home = pw->pw_dir;
794 endpwent();
795 return home;
796 }
797 }
798 endpwent();
799 return NULL;
800 #endif
801 }
802
803 /* Find the directory in which FontForge places all of its configurations and
804 * save files. On Unix-likes, the argument `dir` (see the below case switch,
805 * enum in inc/gfile.h) determines which directory is returned according to the
806 * XDG Base Directory Specification. On Windows, the argument is ignored--the
807 * home directory as obtained by getUserHomeDir() appended with "/FontForge" is
808 * returned. On error, NULL is returned.
809 *
810 * http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
811 */
812 char *getFontForgeUserDir(int dir) {
813 const char *home;
814 char *buf = NULL;
815
816 /* find home directory first, it is needed if any of the xdg env vars are
817 * not set */
818 if (!(home = getUserHomeDir())) {
819 /* if getUserHomeDir returns NULL, pass NULL to calling function */
820 fprintf(stderr, "%s\n", "cannot find home directory");
821 return NULL;
822 }
823 #ifdef _WIN32
824 /* Allow for preferences to be saved locally in a 'portable' configuration. */
825 if (getenv("FF_PORTABLE") != NULL) {
826 buf = smprintf("%s/preferences/", getShareDir());
827 } else {
828 buf = smprintf("%s/FontForge/", home);
829 }
830 return buf;
831 #else
832 const char *def, *xdg;
833 /* Home directory exists, so check for environment variables. For each of
834 * XDG_{CACHE,CONFIG,DATA}_HOME, assign `def` as the corresponding fallback
835 * for if the environment variable does not exist. */
836 switch(dir) {
837 case Cache:
838 xdg = getenv("XDG_CACHE_HOME");
839 def = ".cache";
840 break;
841 case Config:
842 xdg = getenv("XDG_CONFIG_HOME");
843 def = ".config";
844 break;
845 case Data:
846 xdg = getenv("XDG_DATA_HOME");
847 def = ".local/share";
848 break;
849 default:
850 /* for an invalid argument, return NULL */
851 fprintf(stderr, "%s\n", "invalid input");
852 return NULL;
853 }
854 if(xdg != NULL)
855 /* if, for example, XDG_CACHE_HOME exists, assign the value
856 * "$XDG_CACHE_HOME/fontforge" */
857 buf = smprintf("%s/fontforge", xdg);
858 else
859 /* if, for example, XDG_CACHE_HOME does not exist, instead assign
860 * the value "$HOME/.cache/fontforge" */
861 buf = smprintf("%s/%s/fontforge", home, def);
862 if(buf != NULL) {
863 /* try to create buf. If creating the directory fails, return NULL
864 * because nothing will get saved into an inaccessible directory. */
865 if ( mkdir_p(buf, 0755) != EXIT_SUCCESS ) {
866 free(buf);
867 return NULL;
868 }
869 return buf;
870 }
871 return NULL;
872 #endif
873 }
874
875 off_t GFileGetSize(char *name) {
876 /* Get the binary file size for file 'name'. Return -1 if error. */
877 ff_stat_t buf;
878 if ( ff_stat(name, &buf) )
879 return( -1 );
880 return( buf.st_size );
881 }
882
883 off_t GFileGetSizeF(FILE *file) {
884 /* Get the binary file size for open file. Return -1 if error. */
885 ff_stat_t buf;
886 if ( ff_fstat(fileno(file), &buf) )
887 return( -1 );
888 return( buf.st_size );
889 }
890
891 time_t GFileGetMTime(const char *name) {
892 /* Get the modification time for file 'name'. Return 0 if error. */
893 ff_stat_t buf;
894 if ( ff_stat(name, &buf) )
895 return( 0 );
896 return( buf.st_mtime );
897 }
898
899 time_t GFileGetMTimeF(FILE *file) {
900 /* Get the modification time for open file. Return 0 if error. */
901 ff_stat_t buf;
902 if ( ff_fstat(fileno(file), &buf) )
903 return( 0 );
904 return( buf.st_mtime );
905 }
906
907 char *GFileReadAll(char *name) {
908 /* Read file 'name' all into one large string. Return 0 if error. */
909 char *ret;
910 long sz;
911
912 if ( (sz=GFileGetSize(name))>=0 && \
913 (ret=(char *)calloc(1,sz+1))!=NULL ) {
914 FILE *fp;
915 if ( (fp=fopen(name,"rb"))!=NULL ) {
916 size_t bread=fread(ret,1,sz,fp);
917 fclose(fp);
918
919 if( bread==(size_t)sz )
920 return( ret );
921 }
922 free(ret);
923 }
924 return( 0 );
925 }
926
927 /*
928 * Write char string 'data' into file 'name'. Return -1 if error.
929 **/
930 int GFileWriteAll(char *filepath, char *data) {
931
932 if( !data )
933 return -1;
934
935 size_t bwrite = strlen(data);
936 FILE* fp;
937
938 if ( (fp = fopen( filepath, "wb" )) != NULL ) {
939 if ( (fwrite( data, 1, bwrite, fp ) == bwrite) && \
940 (fflush(fp) == 0) )
941 return( (fclose(fp) == 0 ? 0: -1) );
942 fclose(fp);
943 }
944 return -1;
945 }
946
947 char *GFileGetHomeDocumentsDir(void)
948 {
949 static char* ret = 0;
950 if( ret )
951 return ret;
952
953 #if defined(_MSC_VER) || defined(__MINGW32__)
954
955 CHAR my_documents[MAX_PATH+2];
956 HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, my_documents );
957 if (result != S_OK)
958 {
959 fprintf(stderr,"Error: Can't get My Documents path!'\n");
960 return ret;
961 }
962 int pos = strlen(my_documents);
963 my_documents[ pos++ ] = '\\';
964 my_documents[ pos++ ] = '\0';
965 ret = copy( my_documents );
966 GFileNormalizePath(ret);
967 return ret;
968 #endif
969
970 // On GNU/Linux and OSX it was decided that this should be just the
971 // home directory itself.
972 ret = GFileGetHomeDir();
973 return ret;
974 }
975
976 unichar_t *u_GFileGetHomeDocumentsDir(void) {
977 unichar_t* dir = NULL;
978 char* tmp = GFileGetHomeDocumentsDir();
979 if(tmp) {
980 dir = uc_copy(tmp);
981 }
982 return dir;
983 }
984
985
986 char *GFileDirNameEx(const char *path, int treat_as_file)
987 {
988 char *ret = NULL;
989 if (path != NULL) {
990 //Must allocate enough space to append a trailing slash.
991 size_t len = strlen(path);
992 ret = (char *)malloc(len + 2);
993
994 if (ret != NULL) {
995 char *pt;
996
997 strcpy(ret, path);
998 GFileNormalizePath(ret);
999 if (treat_as_file || !GFileIsDir(ret)) {
1000 pt = strrchr(ret, '/');
1001 if (pt != NULL) {
1002 *pt = '\0';
1003 }
1004 }
1005
1006 //Keep only one trailing slash
1007 len = strlen(ret);
1008 for (pt = ret + len - 1; pt >= ret && *pt == '/'; pt--) {
1009 *pt = '\0';
1010 }
1011 *++pt = '/';
1012 *++pt = '\0';
1013 }
1014 }
1015 return ret;
1016 }
1017
1018 char *GFileDirName(const char *path) {
1019 return GFileDirNameEx(path, 0);
1020 }
1021
1022 char *GFileMimeType(const char *path) {
1023 return ff_guess_mime_type(path);
1024 }