]> Creatis software - crea.git/blob - src/creaSystem.cxx
#3374 crea Bug New Normal - vtk8itk5wx3-mingw64
[crea.git] / src / creaSystem.cxx
1 /*
2 # ---------------------------------------------------------------------
3 #
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image 
5 #                        pour la Santé)
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
9 #
10 #  This software is governed by the CeCILL-B license under French law and 
11 #  abiding by the rules of distribution of free software. You can  use, 
12 #  modify and/ or redistribute the software under the terms of the CeCILL-B 
13 #  license as circulated by CEA, CNRS and INRIA at the following URL 
14 #  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
15 #  or in the file LICENSE.txt.
16 #
17 #  As a counterpart to the access to the source code and  rights to copy,
18 #  modify and redistribute granted by the license, users are provided only
19 #  with a limited warranty  and the software's author,  the holder of the
20 #  economic rights,  and the successive licensors  have only  limited
21 #  liability. 
22 #
23 #  The fact that you are presently reading this means that you have had
24 #  knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------ 
26 */ 
27
28 #include "creaSystem.h"
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <iostream>
32
33
34 #ifdef LINUX
35         #include <sys/types.h>
36         #include <sys/stat.h>
37         #include <errno.h> 
38 #endif 
39
40 #ifdef __APPLE__  /* assume this is OSX */
41 #include <sys/param.h>
42 #include <mach-o/dyld.h> /* _NSGetExecutablePath : must add -framework
43 CoreFoundation to link line */
44 #include <string.h>
45 # ifndef PATH_MAX
46 #  define PATH_MAX MAXPATHLEN
47 # endif
48 #endif /* APPLE */
49
50 #ifndef PATH_MAX
51 #  define PATH_MAX 2048
52 #endif
53
54 #if defined(WIN32)
55   #include <direct.h>
56 #else
57    #include <dirent.h>  
58 #endif
59
60 #include <stdlib.h>
61
62
63 namespace crea
64 {
65
66 #ifdef _WIN32
67   int System::HasTTY() { return false; }
68 #else  
69 #include <unistd.h>
70    int System::HasTTY() 
71    { 
72      return isatty(fileno(stdin));
73    }
74 #endif
75
76
77   
78 #ifdef _WIN32
79   
80 //=====================================================================================
81 /*  http://forums.codeguru.com/showthread.php?336106-WCHAR*-to-CHAR*
82 || ::DESCRIPTION::
83 || This function will convert a WCHAR string to a CHAR string.
84 ||
85 || Param 1 :: Pointer to a buffer that will contain the converted string. Ensure this
86 ||            buffer is large enough; if not, buffer overrun errors will occur.
87 || Param 2 :: Constant pointer to a source WCHAR string to be converted to CHAR
88 */
89 void System::wtoc(const WCHAR* Source,CHAR* Dest)
90 {
91     int i = 0;
92     while(Source[i] != '\0')
93     {
94         Dest[i] = (CHAR)Source[i];
95         ++i;
96     } // while
97 }
98
99
100 #endif
101
102
103
104 int System::GetAppPath(char *pname, size_t pathsize)
105    {
106 #ifdef LINUX    
107     /* Oddly, the readlink(2) man page says no NULL is appended. */
108     /* So you have to do it yourself, based on the return value: */
109     pathsize --; /* Preserve a space to add the trailing NULL */
110     long result = readlink("/proc/self/exe", pname, pathsize);
111     if (result > 0)
112         {
113                 pname[result] = 0; /* add the #@!%ing NULL */
114                 
115                 if ((access(pname, 0) == 0))
116                         return 0; /* file exists, return OK */
117                 /*else name doesn't seem to exist, return FAIL (falls
118                  through) */
119         }
120 #endif /* LINUX */
121     
122 #ifdef WIN32
123
124 //2018-07-06 mingw64
125     wchar_t pname2[512];
126     long result = GetModuleFileName(NULL, pname2, pathsize);
127         crea::System::wtoc(pname2,pname);
128 //    long result = GetModuleFileName(NULL, pname, pathsize);
129
130     if (result > 0)
131         {
132                 /* fix up the dir slashes... */
133                 int len = strlen(pname);
134                 int idx;
135                 for (idx = 0; idx < len; idx++)
136                 {
137                         if (pname[idx] == '\\') pname[idx] = '/';
138                 }
139                 
140                 for (idx = len-1; idx >=0 ; idx--)
141                 {
142                         if (pname[idx] == '/')
143                         { 
144                                 pname[idx+1] = '\0';
145                                 idx = -1;
146                         }
147                 }
148                 
149                 if ((_access(pname, 0) == 0))
150                         return 0; /* file exists, return OK */
151                 /*else name doesn't seem to exist, return FAIL (falls
152                  through) */
153         }
154 #endif /* WIN32 */
155     
156 #ifdef SOLARIS
157     char *p = getexecname();
158     if (p)
159         {
160                 /* According to the Sun manpages, getexecname will
161                  "normally" return an */
162                 /* absolute path - BUT might not... AND that IF it is not,
163                  pre-pending */
164                 /* getcwd() will "usually" be the correct thing... Urgh!
165                  */
166                 
167                 /* check pathname is absolute (begins with a / ???) */
168                 if (p[0] == '/') /* assume this means we have an
169                  absolute path */
170                 {
171                         strncpy(pname, p, pathsize);
172                         if ((access(pname, 0) == 0))
173                                 return 0; /* file exists, return OK */
174                 }
175                 else /* if not, prepend getcwd() then check if file
176                  exists */
177                 {
178                         getcwd(pname, pathsize);
179                         long result = strlen(pname);
180                         strncat(pname, "/", (pathsize - result));
181                         result ++;
182                         strncat(pname, p, (pathsize - result));
183                         
184                         if ((access(pname, 0) == 0))
185                                 return 0; /* file exists, return OK */
186                         /*else name doesn't seem to exist, return FAIL
187                          (falls through) */
188                 }
189         }
190 #endif /* SOLARIS */
191     
192 #ifdef MACOSX /* assume this is OSX */
193     /*
194          from http://www.hmug.org/man/3/NSModule.html
195          
196          extern int _NSGetExecutablePath(char *buf, unsigned long
197          *bufsize);
198          
199          _NSGetExecutablePath  copies  the  path  of the executable
200          into the buffer and returns 0 if the path was successfully
201          copied  in the provided buffer. If the buffer is not large
202          enough, -1 is returned and the  expected  buffer  size  is
203          copied  in  *bufsize.  Note that _NSGetExecutablePath will
204          return "a path" to the executable not a "real path" to the
205          executable.  That  is  the path may be a symbolic link and
206          not the real file. And with  deep  directories  the  total
207          bufsize needed could be more than MAXPATHLEN.
208          */
209         
210     int status = -1;
211     char *given_path = (char*)malloc(MAXPATHLEN * 2);
212     if (!given_path) return status;
213     
214     uint32_t npathsize = MAXPATHLEN * 2;
215     long result = _NSGetExecutablePath(given_path, &npathsize);
216     if (result == 0)
217         { /* OK, we got something - now try and resolve the real path...
218          */
219                 if (realpath(given_path, pname) != NULL)
220                 {
221                         if ((access(pname, 0) == 0))
222                                 status = 0; /* file exists, return OK */
223                 }
224         }
225     free (given_path);
226     return status;
227 #endif /* MACOSX */
228     
229     return -1; /* Path Lookup Failed */
230 }
231
232 std::string System::GetDllAppPath(std::string &nomdll){
233         std::string path = ".";
234 #ifdef WIN32
235         char currentPath[_MAX_PATH];
236         
237 //2018-07-06 mingw64
238     wchar_t nomdll2[512];
239         mbstowcs(nomdll2,nomdll.c_str(),strlen(nomdll.c_str())+1);
240         HMODULE hand = GetModuleHandle(nomdll2);
241 //      HMODULE hand = GetModuleHandle(nomdll.c_str());
242
243 //2018-07-06 mingw64
244     wchar_t currentPath2[512];
245         GetModuleFileName(hand, currentPath2, _MAX_PATH);
246         crea::System::wtoc(currentPath2,currentPath);
247 //      GetModuleFileName(hand, currentPath, _MAX_PATH);
248         path = currentPath;
249
250         path = path.substr(0,path.find_last_of("\\"));
251 #endif
252         return path;
253 }
254
255
256 std::string System::GetDllAppPath(const char *nomdll){
257         std::string path = ".";
258 #ifdef WIN32
259         char currentPath[_MAX_PATH];
260
261 //2018-07-06 mingw64
262     wchar_t nomdll2[512];
263         mbstowcs(nomdll2,nomdll,strlen(nomdll)+1);
264         HMODULE hand = GetModuleHandle(nomdll2);
265 //      HMODULE hand = GetModuleHandle(nomdll);
266         
267 //2018-07-06 mingw64
268     wchar_t currentPath2[512];
269         GetModuleFileName(hand, currentPath2, _MAX_PATH);
270         crea::System::wtoc(currentPath2,currentPath);
271 //      GetModuleFileName(hand, currentPath, _MAX_PATH);
272         path = currentPath;
273         path = path.substr(0,path.find_last_of("\\"));
274 #endif
275         return path;
276 }
277
278 #if defined(_WIN32)
279 #define CREACONTOUR_VALID_FILE_SEPARATOR_CHAR '\\'
280 #else
281 #define CREACONTOUR_VALID_FILE_SEPARATOR_CHAR '/'
282 #endif  
283         
284         //=========================================================================
285 std::string System::GetExecutablePath()
286 {
287                 char name[PATH_MAX];
288                 //EED    int err = get_app_path(name, PATH_MAX);
289                 int err = System::GetAppPath(name,PATH_MAX);
290 printf("EED creaSystem::GetExecutablePath %s \n",name);
291                 if (err) 
292                 {
293                         printf("Could not determine current executable path ?  ");  
294                 }    
295                 // remove the exe name
296                 char *slash;
297                 slash = strrchr(name, CREACONTOUR_VALID_FILE_SEPARATOR_CHAR);
298                 if (slash)
299                 {
300                         *slash = 0;
301                 }
302                 return name;
303         }
304         
305         void System::createDirectory(const char* directorypath){
306                 #ifdef WIN32
307                 
308 //2018-07-06 mingw64
309     wchar_t directorypath2[512];
310         mbstowcs(directorypath2,directorypath,strlen(directorypath)+1);
311                         if (CreateDirectory(directorypath2, NULL) == ERROR_ALREADY_EXISTS) 
312 //                      if (CreateDirectory(directorypath, NULL) == ERROR_ALREADY_EXISTS) 
313                         { 
314                                 std::cout<<"directory already exists "<<directorypath<<std::endl;
315                         }else if(CreateDirectory(directorypath2, NULL) == ERROR_PATH_NOT_FOUND){
316 //                      }else if(CreateDirectory(directorypath, NULL) == ERROR_PATH_NOT_FOUND){
317                                 std::string error = "Directory could not be created ";
318                                 error.append(directorypath);
319                                 throw error.c_str();
320                         }
321                 #endif
322                 #ifdef LINUX
323                         //! include sys/types.h
324                         //! include sys/stat.h
325                         //! int mkdir(const char *path, mode_t mode);
326                         //! read/write/search permissions for owner and group, and with read/search permissions for others S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH
327                         int returnval = mkdir(directorypath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
328                         
329                         if(returnval != 0){
330                                 if(errno == EEXIST){
331                                         std::cout<<"directory already exists "<<directorypath<<std::endl;
332                                 }else{
333                                         std::string error = "Directory could not be created ";
334                                         error.append(directorypath);
335                                         throw error.c_str();
336                                 }
337                         }
338                 #endif
339                 #ifdef MACOSX
340                 //TODO
341                 #endif
342         }
343
344 } // namespace crea