wxUsleep() introduced (and documented) to try to work around usleep() bug in
[wxWidgets.git] / src / gtk1 / utilsgtk.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: utils.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Julian Smart and Markus Holzem
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 #include "wx/utils.h"
11 #include "wx/string.h"
12
13 #include "wx/intl.h"
14 #include "wx/log.h"
15
16 #include "wx/process.h"
17
18 #include <stdarg.h>
19 #include <dirent.h>
20 #include <string.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <sys/wait.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <netdb.h>
28 #include <signal.h>
29 #include <fcntl.h> // for O_WRONLY and friends
30 #include <time.h> // nanosleep() and/or usleep()
31
32 #include <glib.h>
33 #include <gdk/gdk.h>
34 #include <gtk/gtk.h>
35 #include <gtk/gtkfeatures.h>
36 #include <gdk/gdkx.h>
37
38 #ifdef __SVR4__
39 #include <sys/systeminfo.h>
40 #endif
41
42 // many versions of Unices have this function, but it is not defined in system
43 // headers - please add your system here if it is the case for your OS.
44 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
45 #if (defined(__SUN__) && !defined(__SunOs_5_6) && \
46 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
47 defined(__osf__)
48 extern "C"
49 {
50 void usleep(unsigned long usec);
51 };
52 #endif // Unices without usleep()
53
54 // many versions of Unices have this function, but it is not defined in system
55 // headers - please add your system here if it is the case for your OS.
56 // SunOS (and Solaris) and DG-UX are like this.
57 #if defined(__SOLARIS__) || defined(__osf__)
58 extern "C"
59 {
60 pid_t wait4(pid_t pid, int *statusp, int options,
61 struct rusage *rusage);
62 }
63
64 #define wxWait4(pid, stat, flags, rusage) wait4(pid, stat, flags, rusage)
65 #elif defined(__sgi) || defined(__HPUX__)
66 // no wait4() at all on these systems
67 // TODO verify whether wait3() really works in this situation
68 #define wxWait4(pid, stat, flags, rusage) wait3(stat, flags, rusage)
69 #else
70 // other Unices: assume have wait4(), although it's not standard (but
71 // Linux and FreeBSD do have it)
72 #define wxWait4(pid, stat, flags, rusage) wait4(pid, stat, flags, rusage)
73 #endif // wait4()
74
75 //------------------------------------------------------------------------
76 // misc.
77 //------------------------------------------------------------------------
78
79 void wxBell(void)
80 {
81 gdk_beep();
82 }
83
84 void wxSleep(int nSecs)
85 {
86 sleep(nSecs);
87 }
88
89 void wxUsleep(unsigned long milliseconds)
90 {
91 #if defined(HAVE_NANOSLEEP)
92 timespec tmReq;
93 tmReq.tv_sec = milliseconds / 1000;
94 tmReq.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
95
96 // we're not interested in remaining time nor in return value
97 (void)nanosleep(&tmReq, (timespec *)NULL);
98 #elif defined(HAVE_USLEEP)
99 // uncomment this if you feel brave or if you are sure that your version
100 // of Solaris has a safe usleep() function but please notice that usleep()
101 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
102 // documented as MT-Safe
103 #if defined(__SUN__) && defined(wxUSE_THREADS)
104 #error "usleep() cannot be used in MT programs under Solaris."
105 #endif // Sun
106
107 usleep(milliseconds * 1000); // usleep(3) wants microseconds
108 #else // !sleep function
109 #error "usleep() or nanosleep() function required for wxUsleep"
110 #endif // sleep function
111 }
112
113 int wxKill(long pid, int sig)
114 {
115 return kill(pid, sig);
116 }
117
118 void wxDisplaySize( int *width, int *height )
119 {
120 if (width) *width = gdk_screen_width();
121 if (height) *height = gdk_screen_height();
122 }
123
124 void wxGetMousePosition( int* x, int* y )
125 {
126 gdk_window_get_pointer( (GdkWindow*) NULL, x, y, (GdkModifierType*) NULL );
127 }
128
129 bool wxColourDisplay(void)
130 {
131 return TRUE;
132 }
133
134 int wxDisplayDepth(void)
135 {
136 return gdk_window_get_visual( (GdkWindow*) &gdk_root_parent )->depth;
137 }
138
139 int wxGetOsVersion(int *majorVsn, int *minorVsn)
140 {
141 if (majorVsn) *majorVsn = GTK_MAJOR_VERSION;
142 if (minorVsn) *minorVsn = GTK_MINOR_VERSION;
143
144 return wxGTK;
145 }
146
147 //------------------------------------------------------------------------
148 // user and home routines
149 //------------------------------------------------------------------------
150
151 const char* wxGetHomeDir( wxString *home )
152 {
153 *home = wxGetUserHome( wxString() );
154 if (home->IsNull()) *home = "/";
155 return *home;
156 }
157
158 char *wxGetUserHome( const wxString &user )
159 {
160 struct passwd *who = (struct passwd *) NULL;
161
162 if (user.IsNull() || (user== ""))
163 {
164 register char *ptr;
165
166 if ((ptr = getenv("HOME")) != NULL)
167 {
168 return ptr;
169 }
170 if ((ptr = getenv("USER")) != NULL || (ptr = getenv("LOGNAME")) != NULL)
171 {
172 who = getpwnam(ptr);
173 }
174
175 /* We now make sure the the user exists! */
176 if (who == NULL)
177 {
178 who = getpwuid(getuid());
179 }
180 }
181 else
182 {
183 who = getpwnam (user);
184 }
185
186 return who ? who->pw_dir : (char*)NULL;
187 }
188
189 //------------------------------------------------------------------------
190 // id routines
191 //------------------------------------------------------------------------
192
193 bool wxGetHostName(char *buf, int sz)
194 {
195 *buf = '\0';
196 #if defined(__SVR4__) && !defined(__sgi)
197 //KB: does this return the fully qualified host.domain name?
198 return (sysinfo(SI_HOSTNAME, buf, sz) != -1);
199 #else /* BSD Sockets */
200 char name[255], domain[255];
201 //struct hostent *h;
202 // Get hostname
203 if (gethostname(name, sizeof(name)/sizeof(char)-1) == -1)
204 return FALSE;
205 if (getdomainname(domain, sizeof(domain)/sizeof(char)-1) == -1)
206 return FALSE;
207 // Get official full name of host
208 // doesn't return the full qualified name, replaced by following
209 // code (KB)
210 // strncpy(buf, (h=gethostbyname(name))!=NULL ? h->h_name : name, sz-1);
211 if((unsigned)sz > strlen(name)+strlen(domain)+1)
212 {
213 strcpy(buf, name);
214 if(strcmp(domain,"(none)") == 0) // standalone machine
215 {
216 strcat(buf,".");
217 strcat(buf,domain);
218 }
219 }
220 else
221 return FALSE;
222 return TRUE;
223 #endif
224 }
225
226 bool wxGetUserId(char *buf, int sz)
227 {
228 struct passwd *who;
229
230 *buf = '\0';
231 if ((who = getpwuid(getuid ())) != NULL) {
232 strncpy (buf, who->pw_name, sz-1);
233 return TRUE;
234 }
235 return FALSE;
236 }
237
238 bool wxGetUserName(char *buf, int sz)
239 {
240 struct passwd *who;
241 char *comma;
242
243 *buf = '\0';
244 if ((who = getpwuid (getuid ())) != NULL) {
245 comma = strchr(who->pw_gecos,'c');
246 if(comma) *comma = '\0'; // cut off non-name comment fields
247 strncpy (buf, who->pw_gecos, sz - 1);
248 return TRUE;
249 }
250 return FALSE;
251 }
252
253 //------------------------------------------------------------------------
254 // error and debug output routines
255 //------------------------------------------------------------------------
256
257 void wxDebugMsg( const char *format, ... )
258 {
259 va_list ap;
260 va_start( ap, format );
261 vfprintf( stderr, format, ap );
262 fflush( stderr );
263 va_end(ap);
264 }
265
266 void wxError( const wxString &msg, const wxString &title )
267 {
268 fprintf( stderr, "Error " );
269 if (!title.IsNull()) fprintf( stderr, "%s ", WXSTRINGCAST(title) );
270 if (!msg.IsNull()) fprintf( stderr, ": %s", WXSTRINGCAST(msg) );
271 fprintf( stderr, ".\n" );
272 }
273
274 void wxFatalError( const wxString &msg, const wxString &title )
275 {
276 fprintf( stderr, "Error " );
277 if (!title.IsNull()) fprintf( stderr, "%s ", WXSTRINGCAST(title) );
278 if (!msg.IsNull()) fprintf( stderr, ": %s", WXSTRINGCAST(msg) );
279 fprintf( stderr, ".\n" );
280 exit(3); // the same exit code as for abort()
281 }
282
283 //------------------------------------------------------------------------
284 // directory routines
285 //------------------------------------------------------------------------
286
287 bool wxDirExists( const wxString& dir )
288 {
289 char buf[500];
290 strcpy( buf, WXSTRINGCAST(dir) );
291 struct stat sbuf;
292 return ((stat(buf, &sbuf) != -1) && S_ISDIR(sbuf.st_mode) ? TRUE : FALSE);
293 }
294
295 //------------------------------------------------------------------------
296 // subprocess routines
297 //------------------------------------------------------------------------
298
299 // if pid > 0, the execution is async and the data is freed in
300 // GTK_EndProcessDetector, if pid < 0, the execution is synchronous and the
301 // caller (wxExecute) frees the data
302 struct wxEndProcessData
303 {
304 gint pid, tag;
305 wxProcess *process;
306 int exitcode;
307 };
308
309 static void GTK_EndProcessDetector(gpointer data, gint source,
310 GdkInputCondition WXUNUSED(condition) )
311 {
312 wxEndProcessData *proc_data = (wxEndProcessData *)data;
313 int pid;
314
315 pid = (proc_data->pid > 0) ? proc_data->pid : -(proc_data->pid);
316
317 int status = 0;
318 wxWait4(pid, &status, 0, (rusage *) NULL);
319
320 close(source);
321 gdk_input_remove(proc_data->tag);
322
323 if (proc_data->process)
324 proc_data->process->OnTerminate(proc_data->pid, status);
325
326 if (proc_data->pid > 0)
327 {
328 delete proc_data;
329 }
330 else
331 {
332 // wxExecute() will know about it
333 proc_data->exitcode = status;
334
335 proc_data->pid = 0;
336 }
337 }
338
339 long wxExecute( char **argv, bool sync, wxProcess *process )
340 {
341 wxEndProcessData *data = new wxEndProcessData;
342 int end_proc_detect[2];
343
344 wxCHECK_MSG( *argv, 0, "can't exec empty command" );
345
346 /* Create pipes */
347 if (pipe(end_proc_detect) == -1)
348 {
349 wxLogSysError( _("Pipe creation failed") );
350 return 0;
351 }
352
353 /* fork the process */
354 #if defined(sun) || defined(__ultrix) || defined(__bsdi__)
355 pid_t pid = vfork();
356 #else
357 pid_t pid = fork();
358 #endif
359 if (pid == -1)
360 {
361 wxLogSysError( _("Fork failed") );
362 return 0;
363 }
364 else if (pid == 0)
365 {
366 // we're in child
367 close(end_proc_detect[0]); // close reading side
368
369 // These three lines close the open file descriptors to to avoid any
370 // input/output which might block the process or irritate the user. If
371 // one wants proper IO for the subprocess, the "right thing to do is
372 // to start an xterm executing it.
373 close(STDIN_FILENO);
374 close(STDOUT_FILENO);
375
376 // leave stderr opened, it won't do any hurm
377 #if 0
378 close(STDERR_FILENO);
379
380 // some programs complain about stderr not being open, so redirect
381 // them:
382 open("/dev/null", O_RDONLY); // stdin
383 open("/dev/null", O_WRONLY); // stdout
384 open("/dev/null", O_WRONLY); // stderr
385 #endif
386
387 #ifdef _AIX
388 execvp ((const char *)*argv, (const char **)argv);
389 #else
390 execvp (*argv, argv);
391 #endif
392
393 // there is no return after successful exec()
394 fprintf(stderr, _("Can't execute '%s'\n"), *argv);
395
396 _exit(-1);
397 }
398 else
399 {
400 // we're in parent
401 close(end_proc_detect[1]); // close writing side
402 data->tag = gdk_input_add(end_proc_detect[0], GDK_INPUT_READ,
403 GTK_EndProcessDetector, (gpointer)data);
404 if ( sync )
405 {
406 wxASSERT_MSG( !process, "wxProcess param ignored for sync exec" );
407 data->process = NULL;
408
409 // sync execution: indicate it by negating the pid
410 data->pid = -pid;
411
412 // it will be set to 0 from GTK_EndProcessDetector
413 while (data->pid != 0)
414 wxYield();
415
416 int exitcode = data->exitcode;
417
418 delete data;
419
420 return exitcode;
421 }
422 else
423 {
424 // async execution, nothing special to do - caller will be
425 // notified about the process terminationif process != NULL, data
426 // will be deleted in GTK_EndProcessDetector
427 data->process = process;
428 data->pid = pid;
429
430 return pid;
431 }
432 }
433 }
434
435 long wxExecute( const wxString& command, bool sync, wxProcess *process )
436 {
437 static const char *IFS = " \t\n";
438
439 wxCHECK_MSG( !command.IsEmpty(), 0, "can't exec empty command" );
440
441 int argc = 0;
442 char *argv[127];
443 char *tmp = new char[command.Len() + 1];
444 strcpy(tmp, command);
445
446 argv[argc++] = strtok(tmp, IFS);
447 while ((argv[argc++] = strtok((char *) NULL, IFS)) != NULL)
448 /* loop */ ;
449
450 long lRc = wxExecute(argv, sync, process);
451
452 delete [] tmp;
453
454 return lRc;
455 }