]> git.saurik.com Git - wxWidgets.git/blame - src/unix/utilsunx.cpp
Use extraFontFlag to specify if anti-aliased fonts should be used.
[wxWidgets.git] / src / unix / utilsunx.cpp
CommitLineData
518b5d2f 1/////////////////////////////////////////////////////////////////////////////
79066131 2// Name: unix/utilsunx.cpp
518b5d2f
VZ
3// Purpose: generic Unix implementation of many wx functions
4// Author: Vadim Zeitlin
5// Id: $Id$
6// Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7// Licence: wxWindows licence
8/////////////////////////////////////////////////////////////////////////////
9
10// ============================================================================
11// declarations
12// ============================================================================
13
14// ----------------------------------------------------------------------------
15// headers
16// ----------------------------------------------------------------------------
17
14f355c2
VS
18// for compilers that support precompilation, includes "wx.h".
19#include "wx/wxprec.h"
20
518b5d2f
VZ
21#include "wx/defs.h"
22#include "wx/string.h"
23
24#include "wx/intl.h"
25#include "wx/log.h"
a37a5a73 26#include "wx/app.h"
46446cc2 27#include "wx/apptrait.h"
518b5d2f
VZ
28
29#include "wx/utils.h"
30#include "wx/process.h"
bdc72a22 31#include "wx/thread.h"
518b5d2f 32
80d6dc0a 33#include "wx/wfstream.h"
8b33ae2d 34
e2478fde
VZ
35#include "wx/unix/execute.h"
36
2887179b
VZ
37#if wxUSE_STREAMS
38
39// define this to let wxexec.cpp know that we know what we're doing
40#define _WX_USED_BY_WXEXECUTE_
41#include "../common/execcmn.cpp"
42
43#endif // wxUSE_STREAMS
44
ec67cff1 45#if wxUSE_BASE
e2478fde 46
8d4f85ce
SC
47#if defined( __MWERKS__ ) && defined(__MACH__)
48#define WXWIN_OS_DESCRIPTION "MacOS X"
49#define HAVE_NANOSLEEP
50#endif
51
85da04e9
VZ
52// not only the statfs syscall is called differently depending on platform, but
53// one of its incarnations, statvfs(), takes different arguments under
54// different platforms and even different versions of the same system (Solaris
55// 7 and 8): if you want to test for this, don't forget that the problems only
56// appear if the large files support is enabled
eadd7bd2 57#ifdef HAVE_STATFS
85da04e9
VZ
58 #ifdef __BSD__
59 #include <sys/param.h>
60 #include <sys/mount.h>
61 #else // !__BSD__
62 #include <sys/vfs.h>
63 #endif // __BSD__/!__BSD__
64
65 #define wxStatfs statfs
eadd7bd2
VZ
66#endif // HAVE_STATFS
67
9952adac
VZ
68#ifdef HAVE_STATVFS
69 #include <sys/statvfs.h>
70
85da04e9
VZ
71 #define wxStatfs statvfs
72#endif // HAVE_STATVFS
73
74#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
75 // WX_STATFS_T is detected by configure
76 #define wxStatfs_t WX_STATFS_T
77#endif
9952adac 78
f6bcfd97
BP
79// SGI signal.h defines signal handler arguments differently depending on
80// whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
81#if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
82 #define _LANGUAGE_C_PLUS_PLUS 1
83#endif // SGI hack
84
518b5d2f
VZ
85#include <stdarg.h>
86#include <dirent.h>
87#include <string.h>
88#include <sys/stat.h>
89#include <sys/types.h>
518b5d2f 90#include <sys/wait.h>
e2478fde 91#include <unistd.h>
518b5d2f
VZ
92#include <pwd.h>
93#include <errno.h>
94#include <netdb.h>
95#include <signal.h>
96#include <fcntl.h> // for O_WRONLY and friends
97#include <time.h> // nanosleep() and/or usleep()
fad866f4 98#include <ctype.h> // isspace()
b12915c1 99#include <sys/time.h> // needed for FD_SETSIZE
7bcb11d3 100
0fcdf6dc 101#ifdef HAVE_UNAME
518b5d2f
VZ
102 #include <sys/utsname.h> // for uname()
103#endif // HAVE_UNAME
104
105// ----------------------------------------------------------------------------
106// conditional compilation
107// ----------------------------------------------------------------------------
108
109// many versions of Unices have this function, but it is not defined in system
110// headers - please add your system here if it is the case for your OS.
111// SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
1363811b
VZ
112#if !defined(HAVE_USLEEP) && \
113 (defined(__SUN__) && !defined(__SunOs_5_6) && \
518b5d2f 114 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
fd9811b1 115 defined(__osf__) || defined(__EMX__)
518b5d2f
VZ
116 extern "C"
117 {
1363811b
VZ
118 #ifdef __SUN__
119 int usleep(unsigned int usec);
120 #else // !Sun
bdc72a22
VZ
121 #ifdef __EMX__
122 /* I copied this from the XFree86 diffs. AV. */
123 #define INCL_DOSPROCESS
124 #include <os2.h>
125 inline void usleep(unsigned long delay)
126 {
127 DosSleep(delay ? (delay/1000l) : 1l);
128 }
129 #else // !Sun && !EMX
130 void usleep(unsigned long usec);
131 #endif
e6daf794 132 #endif // Sun/EMX/Something else
518b5d2f 133 };
bdc72a22
VZ
134
135 #define HAVE_USLEEP 1
518b5d2f
VZ
136#endif // Unices without usleep()
137
518b5d2f
VZ
138// ============================================================================
139// implementation
140// ============================================================================
141
142// ----------------------------------------------------------------------------
143// sleeping
144// ----------------------------------------------------------------------------
145
146void wxSleep(int nSecs)
147{
148 sleep(nSecs);
149}
150
151void wxUsleep(unsigned long milliseconds)
152{
b12915c1 153#if defined(HAVE_NANOSLEEP)
518b5d2f 154 timespec tmReq;
13111b2a 155 tmReq.tv_sec = (time_t)(milliseconds / 1000);
518b5d2f
VZ
156 tmReq.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
157
158 // we're not interested in remaining time nor in return value
159 (void)nanosleep(&tmReq, (timespec *)NULL);
b12915c1 160#elif defined(HAVE_USLEEP)
518b5d2f
VZ
161 // uncomment this if you feel brave or if you are sure that your version
162 // of Solaris has a safe usleep() function but please notice that usleep()
163 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
164 // documented as MT-Safe
ea18eed9 165 #if defined(__SUN__) && wxUSE_THREADS
518b5d2f
VZ
166 #error "usleep() cannot be used in MT programs under Solaris."
167 #endif // Sun
168
169 usleep(milliseconds * 1000); // usleep(3) wants microseconds
b12915c1
VZ
170#elif defined(HAVE_SLEEP)
171 // under BeOS sleep() takes seconds (what about other platforms, if any?)
172 sleep(milliseconds * 1000);
518b5d2f
VZ
173#else // !sleep function
174 #error "usleep() or nanosleep() function required for wxUsleep"
175#endif // sleep function
176}
177
178// ----------------------------------------------------------------------------
179// process management
180// ----------------------------------------------------------------------------
181
50567b69 182int wxKill(long pid, wxSignal sig, wxKillError *rc)
518b5d2f 183{
50567b69
VZ
184 int err = kill((pid_t)pid, (int)sig);
185 if ( rc )
186 {
15b663b4 187 switch ( errno )
50567b69
VZ
188 {
189 case 0:
190 *rc = wxKILL_OK;
191 break;
192
193 case EINVAL:
194 *rc = wxKILL_BAD_SIGNAL;
195 break;
196
197 case EPERM:
198 *rc = wxKILL_ACCESS_DENIED;
199 break;
200
201 case ESRCH:
202 *rc = wxKILL_NO_PROCESS;
203 break;
204
205 default:
206 // this goes against Unix98 docs so log it
207 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
208
209 // something else...
210 *rc = wxKILL_ERROR;
211 }
212 }
213
214 return err;
518b5d2f
VZ
215}
216
fad866f4
KB
217#define WXEXECUTE_NARGS 127
218
fbf456aa 219long wxExecute( const wxString& command, int flags, wxProcess *process )
518b5d2f 220{
223d09f6 221 wxCHECK_MSG( !command.IsEmpty(), 0, wxT("can't exec empty command") );
518b5d2f 222
647b8e37
VZ
223#if wxUSE_THREADS
224 // fork() doesn't mix well with POSIX threads: on many systems the program
225 // deadlocks or crashes for some reason. Probably our code is buggy and
226 // doesn't do something which must be done to allow this to work, but I
227 // don't know what yet, so for now just warn the user (this is the least we
228 // can do) about it
229 wxASSERT_MSG( wxThread::IsMain(),
230 _T("wxExecute() can be called only from the main thread") );
231#endif // wxUSE_THREADS
232
518b5d2f 233 int argc = 0;
05079acc 234 wxChar *argv[WXEXECUTE_NARGS];
fad866f4 235 wxString argument;
05079acc 236 const wxChar *cptr = command.c_str();
223d09f6 237 wxChar quotechar = wxT('\0'); // is arg quoted?
fad866f4 238 bool escaped = FALSE;
518b5d2f 239
0ed9a934 240 // split the command line in arguments
fad866f4
KB
241 do
242 {
223d09f6
KB
243 argument=wxT("");
244 quotechar = wxT('\0');
0ed9a934 245
fad866f4 246 // eat leading whitespace:
05079acc 247 while ( wxIsspace(*cptr) )
fad866f4 248 cptr++;
0ed9a934 249
223d09f6 250 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
fad866f4 251 quotechar = *cptr++;
0ed9a934 252
fad866f4
KB
253 do
254 {
223d09f6 255 if ( *cptr == wxT('\\') && ! escaped )
fad866f4
KB
256 {
257 escaped = TRUE;
258 cptr++;
259 continue;
260 }
0ed9a934 261
fad866f4 262 // all other characters:
0ed9a934 263 argument += *cptr++;
fad866f4 264 escaped = FALSE;
0ed9a934
VZ
265
266 // have we reached the end of the argument?
267 if ( (*cptr == quotechar && ! escaped)
223d09f6
KB
268 || (quotechar == wxT('\0') && wxIsspace(*cptr))
269 || *cptr == wxT('\0') )
fad866f4 270 {
0ed9a934 271 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
223d09f6 272 wxT("too many arguments in wxExecute") );
0ed9a934 273
05079acc
OK
274 argv[argc] = new wxChar[argument.length() + 1];
275 wxStrcpy(argv[argc], argument.c_str());
fad866f4 276 argc++;
0ed9a934 277
fad866f4 278 // if not at end of buffer, swallow last character:
0ed9a934
VZ
279 if(*cptr)
280 cptr++;
281
fad866f4
KB
282 break; // done with this one, start over
283 }
0ed9a934
VZ
284 } while(*cptr);
285 } while(*cptr);
fad866f4 286 argv[argc] = NULL;
0ed9a934
VZ
287
288 // do execute the command
fbf456aa 289 long lRc = wxExecute(argv, flags, process);
518b5d2f 290
0ed9a934 291 // clean up
fad866f4 292 argc = 0;
0ed9a934 293 while( argv[argc] )
fad866f4 294 delete [] argv[argc++];
518b5d2f
VZ
295
296 return lRc;
297}
298
2c8e4738
VZ
299// ----------------------------------------------------------------------------
300// wxShell
301// ----------------------------------------------------------------------------
302
303static wxString wxMakeShellCommand(const wxString& command)
518b5d2f
VZ
304{
305 wxString cmd;
cd6ce4a9 306 if ( !command )
2c8e4738
VZ
307 {
308 // just an interactive shell
cd6ce4a9 309 cmd = _T("xterm");
2c8e4738 310 }
518b5d2f 311 else
2c8e4738
VZ
312 {
313 // execute command in a shell
314 cmd << _T("/bin/sh -c '") << command << _T('\'');
315 }
316
317 return cmd;
318}
319
320bool wxShell(const wxString& command)
321{
fbf456aa 322 return wxExecute(wxMakeShellCommand(command), wxEXEC_SYNC) == 0;
2c8e4738
VZ
323}
324
325bool wxShell(const wxString& command, wxArrayString& output)
326{
327 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
518b5d2f 328
2c8e4738 329 return wxExecute(wxMakeShellCommand(command), output);
518b5d2f
VZ
330}
331
f6ba47d9
VZ
332// Shutdown or reboot the PC
333bool wxShutdown(wxShutdownFlags wFlags)
334{
335 wxChar level;
336 switch ( wFlags )
337 {
338 case wxSHUTDOWN_POWEROFF:
339 level = _T('0');
340 break;
341
342 case wxSHUTDOWN_REBOOT:
343 level = _T('6');
344 break;
345
346 default:
347 wxFAIL_MSG( _T("unknown wxShutdown() flag") );
348 return FALSE;
349 }
350
351 return system(wxString::Format(_T("init %c"), level).mb_str()) == 0;
352}
353
354
cd6ce4a9
VZ
355// ----------------------------------------------------------------------------
356// wxStream classes to support IO redirection in wxExecute
357// ----------------------------------------------------------------------------
6dc6fda6 358
1e6feb95
VZ
359#if wxUSE_STREAMS
360
2b5f62a0 361bool wxPipeInputStream::CanRead() const
8b33ae2d 362{
cd6ce4a9 363 if ( m_lasterror == wxSTREAM_EOF )
6f3d3c68 364 return FALSE;
cd6ce4a9
VZ
365
366 // check if there is any input available
367 struct timeval tv;
368 tv.tv_sec = 0;
369 tv.tv_usec = 0;
370
80d6dc0a
VZ
371 const int fd = m_file->fd();
372
cd6ce4a9
VZ
373 fd_set readfds;
374 FD_ZERO(&readfds);
80d6dc0a
VZ
375 FD_SET(fd, &readfds);
376 switch ( select(fd + 1, &readfds, NULL, NULL, &tv) )
cd6ce4a9
VZ
377 {
378 case -1:
379 wxLogSysError(_("Impossible to get child process input"));
380 // fall through
8b33ae2d 381
cd6ce4a9 382 case 0:
6f3d3c68 383 return FALSE;
8b33ae2d 384
cd6ce4a9
VZ
385 default:
386 wxFAIL_MSG(_T("unexpected select() return value"));
387 // still fall through
388
389 case 1:
6f3d3c68
VZ
390 // input available -- or maybe not, as select() returns 1 when a
391 // read() will complete without delay, but it could still not read
392 // anything
393 return !Eof();
cd6ce4a9 394 }
8b33ae2d
GL
395}
396
1e6feb95
VZ
397#endif // wxUSE_STREAMS
398
b477f956
VZ
399// ----------------------------------------------------------------------------
400// wxExecute: the real worker function
401// ----------------------------------------------------------------------------
79066131 402
ef0ed19e 403#ifdef __VMS
79066131 404 #pragma message disable codeunreachable
ef0ed19e 405#endif
b477f956 406
6dc6fda6 407long wxExecute(wxChar **argv,
fbf456aa 408 int flags,
cd6ce4a9 409 wxProcess *process)
518b5d2f 410{
f6bcfd97 411 // for the sync execution, we return -1 to indicate failure, but for async
accb3257
VZ
412 // case we return 0 which is never a valid PID
413 //
414 // we define this as a macro, not a variable, to avoid compiler warnings
415 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
fbf456aa 416 #define ERROR_RETURN_CODE ((flags & wxEXEC_SYNC) ? -1 : 0)
f6bcfd97 417
accb3257 418 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
518b5d2f 419
05079acc
OK
420#if wxUSE_UNICODE
421 int mb_argc = 0;
422 char *mb_argv[WXEXECUTE_NARGS];
423
e90c1d2a
VZ
424 while (argv[mb_argc])
425 {
cd6ce4a9
VZ
426 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
427 mb_argv[mb_argc] = strdup(mb_arg);
428 mb_argc++;
05079acc
OK
429 }
430 mb_argv[mb_argc] = (char *) NULL;
e90c1d2a
VZ
431
432 // this macro will free memory we used above
433 #define ARGS_CLEANUP \
345b0247 434 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
e90c1d2a
VZ
435 free(mb_argv[mb_argc])
436#else // ANSI
437 // no need for cleanup
438 #define ARGS_CLEANUP
439
05079acc 440 wxChar **mb_argv = argv;
e90c1d2a 441#endif // Unicode/ANSI
518b5d2f 442
e2478fde
VZ
443 // we want this function to work even if there is no wxApp so ensure that
444 // we have a valid traits pointer
445 wxConsoleAppTraits traitsConsole;
446 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
447 if ( !traits )
448 traits = &traitsConsole;
449
450 // this struct contains all information which we pass to and from
451 // wxAppTraits methods
452 wxExecuteData execData;
453 execData.flags = flags;
454 execData.process = process;
455
518b5d2f 456 // create pipes
e2478fde 457 if ( !traits->CreateEndProcessPipe(execData) )
518b5d2f 458 {
cd6ce4a9 459 wxLogError( _("Failed to execute '%s'\n"), *argv );
e90c1d2a
VZ
460
461 ARGS_CLEANUP;
462
accb3257 463 return ERROR_RETURN_CODE;
518b5d2f
VZ
464 }
465
f6bcfd97 466 // pipes for inter process communication
b477f956
VZ
467 wxPipe pipeIn, // stdin
468 pipeOut, // stdout
469 pipeErr; // stderr
cd6ce4a9
VZ
470
471 if ( process && process->IsRedirected() )
8b33ae2d 472 {
b477f956 473 if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() )
8b33ae2d 474 {
cd6ce4a9 475 wxLogError( _("Failed to execute '%s'\n"), *argv );
8b33ae2d
GL
476
477 ARGS_CLEANUP;
478
accb3257 479 return ERROR_RETURN_CODE;
8b33ae2d
GL
480 }
481 }
8b33ae2d 482
518b5d2f 483 // fork the process
ef5f8ab6
VZ
484 //
485 // NB: do *not* use vfork() here, it completely breaks this code for some
486 // reason under Solaris (and maybe others, although not under Linux)
b2ddee86
JJ
487 // But on OpenVMS we do not have fork so we have to use vfork and
488 // cross our fingers that it works.
489#ifdef __VMS
490 pid_t pid = vfork();
491#else
492 pid_t pid = fork();
493#endif
494 if ( pid == -1 ) // error?
518b5d2f
VZ
495 {
496 wxLogSysError( _("Fork failed") );
e90c1d2a
VZ
497
498 ARGS_CLEANUP;
499
accb3257 500 return ERROR_RETURN_CODE;
518b5d2f 501 }
cd6ce4a9 502 else if ( pid == 0 ) // we're in child
518b5d2f 503 {
cd6ce4a9 504 // These lines close the open file descriptors to to avoid any
518b5d2f 505 // input/output which might block the process or irritate the user. If
cd6ce4a9
VZ
506 // one wants proper IO for the subprocess, the right thing to do is to
507 // start an xterm executing it.
fbf456aa 508 if ( !(flags & wxEXEC_SYNC) )
518b5d2f 509 {
518b5d2f
VZ
510 for ( int fd = 0; fd < FD_SETSIZE; fd++ )
511 {
b477f956
VZ
512 if ( fd == pipeIn[wxPipe::Read]
513 || fd == pipeOut[wxPipe::Write]
514 || fd == pipeErr[wxPipe::Write]
e2478fde 515 || traits->IsWriteFDOfEndProcessPipe(execData, fd) )
cd6ce4a9
VZ
516 {
517 // don't close this one, we still need it
518 continue;
519 }
e90c1d2a 520
b477f956 521 // leave stderr opened too, it won't do any harm
e90c1d2a 522 if ( fd != STDERR_FILENO )
518b5d2f
VZ
523 close(fd);
524 }
0c9c4401 525 }
e1082c9f 526
e8e776aa 527#if !defined(__VMS) && !defined(__EMX__)
0c9c4401
VZ
528 if ( flags & wxEXEC_MAKE_GROUP_LEADER )
529 {
530 // Set process group to child process' pid. Then killing -pid
531 // of the parent will kill the process and all of its children.
532 setsid();
518b5d2f 533 }
0c9c4401
VZ
534#endif // !__VMS
535
0c9c4401
VZ
536 // reading side can be safely closed but we should keep the write one
537 // opened
e2478fde 538 traits->DetachWriteFDOfEndProcessPipe(execData);
518b5d2f 539
80d6dc0a 540 // redirect stdin, stdout and stderr
b477f956 541 if ( pipeIn.IsOk() )
cd6ce4a9 542 {
b477f956
VZ
543 if ( dup2(pipeIn[wxPipe::Read], STDIN_FILENO) == -1 ||
544 dup2(pipeOut[wxPipe::Write], STDOUT_FILENO) == -1 ||
545 dup2(pipeErr[wxPipe::Write], STDERR_FILENO) == -1 )
cd6ce4a9 546 {
f6bcfd97 547 wxLogSysError(_("Failed to redirect child process input/output"));
cd6ce4a9 548 }
518b5d2f 549
b477f956
VZ
550 pipeIn.Close();
551 pipeOut.Close();
552 pipeErr.Close();
cd6ce4a9 553 }
518b5d2f 554
05079acc 555 execvp (*mb_argv, mb_argv);
518b5d2f 556
d264d709 557 fprintf(stderr, "execvp(");
8d4f85ce
SC
558 // CS changed ppc to ppc_ as ppc is not available under mac os CW Mach-O
559 for ( char **ppc_ = mb_argv; *ppc_; ppc_++ )
560 fprintf(stderr, "%s%s", ppc_ == mb_argv ? "" : ", ", *ppc_);
d264d709
VZ
561 fprintf(stderr, ") failed with error %d!\n", errno);
562
518b5d2f 563 // there is no return after successful exec()
518b5d2f 564 _exit(-1);
1d8dd65e
VZ
565
566 // some compilers complain about missing return - of course, they
567 // should know that exit() doesn't return but what else can we do if
568 // they don't?
b477f956
VZ
569 //
570 // and, sure enough, other compilers complain about unreachable code
571 // after exit() call, so we can just always have return here...
1d8dd65e
VZ
572#if defined(__VMS) || defined(__INTEL_COMPILER)
573 return 0;
574#endif
518b5d2f 575 }
cd6ce4a9 576 else // we're in parent
518b5d2f 577 {
cd6ce4a9
VZ
578 ARGS_CLEANUP;
579
7764f973
VZ
580 // save it for WaitForChild() use
581 execData.pid = pid;
582
80d6dc0a
VZ
583 // prepare for IO redirection
584
0e300ddd 585#if wxUSE_STREAMS
80d6dc0a
VZ
586 // the input buffer bufOut is connected to stdout, this is why it is
587 // called bufOut and not bufIn
588 wxStreamTempInputBuffer bufOut,
589 bufErr;
0e300ddd
VZ
590#endif // wxUSE_STREAMS
591
cd6ce4a9
VZ
592 if ( process && process->IsRedirected() )
593 {
1e6feb95 594#if wxUSE_STREAMS
80d6dc0a
VZ
595 wxOutputStream *inStream =
596 new wxFileOutputStream(pipeIn.Detach(wxPipe::Write));
b477f956 597
79066131
VZ
598 wxPipeInputStream *outStream =
599 new wxPipeInputStream(pipeOut.Detach(wxPipe::Read));
b477f956 600
79066131
VZ
601 wxPipeInputStream *errStream =
602 new wxPipeInputStream(pipeErr.Detach(wxPipe::Read));
f6bcfd97 603
80d6dc0a 604 process->SetPipeStreams(outStream, inStream, errStream);
0e300ddd 605
80d6dc0a 606 bufOut.Init(outStream);
b477f956 607 bufErr.Init(errStream);
e2478fde
VZ
608
609 execData.bufOut = &bufOut;
610 execData.bufErr = &bufErr;
1e6feb95 611#endif // wxUSE_STREAMS
b477f956 612 }
1e6feb95 613
b477f956
VZ
614 if ( pipeIn.IsOk() )
615 {
616 pipeIn.Close();
617 pipeOut.Close();
618 pipeErr.Close();
cd6ce4a9
VZ
619 }
620
e2478fde 621 return traits->WaitForChild(execData);
518b5d2f 622 }
79656e30
GD
623
624 return ERROR_RETURN_CODE;
518b5d2f 625}
79066131 626
ef0ed19e 627#ifdef __VMS
79066131 628 #pragma message enable codeunreachable
ef0ed19e 629#endif
518b5d2f 630
accb3257 631#undef ERROR_RETURN_CODE
f6bcfd97
BP
632#undef ARGS_CLEANUP
633
518b5d2f
VZ
634// ----------------------------------------------------------------------------
635// file and directory functions
636// ----------------------------------------------------------------------------
637
05079acc 638const wxChar* wxGetHomeDir( wxString *home )
518b5d2f
VZ
639{
640 *home = wxGetUserHome( wxString() );
79066131 641 wxString tmp;
518b5d2f 642 if ( home->IsEmpty() )
223d09f6 643 *home = wxT("/");
181cbcf4 644#ifdef __VMS
79066131
VZ
645 tmp = *home;
646 if ( tmp.Last() != wxT(']'))
647 if ( tmp.Last() != wxT('/')) *home << wxT('/');
181cbcf4 648#endif
518b5d2f
VZ
649 return home->c_str();
650}
651
05079acc
OK
652#if wxUSE_UNICODE
653const wxMB2WXbuf wxGetUserHome( const wxString &user )
e90c1d2a 654#else // just for binary compatibility -- there is no 'const' here
518b5d2f 655char *wxGetUserHome( const wxString &user )
05079acc 656#endif
518b5d2f
VZ
657{
658 struct passwd *who = (struct passwd *) NULL;
659
0fb67cd1 660 if ( !user )
518b5d2f 661 {
e90c1d2a 662 wxChar *ptr;
518b5d2f 663
223d09f6 664 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
518b5d2f 665 {
2b5f62a0
VZ
666#if wxUSE_UNICODE
667 wxWCharBuffer buffer( ptr );
668 return buffer;
669#else
518b5d2f 670 return ptr;
2b5f62a0 671#endif
518b5d2f 672 }
223d09f6 673 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
518b5d2f 674 {
e90c1d2a 675 who = getpwnam(wxConvertWX2MB(ptr));
518b5d2f
VZ
676 }
677
678 // We now make sure the the user exists!
679 if (who == NULL)
680 {
681 who = getpwuid(getuid());
682 }
683 }
684 else
685 {
05079acc 686 who = getpwnam (user.mb_str());
518b5d2f
VZ
687 }
688
af111fc3 689 return wxConvertMB2WX(who ? who->pw_dir : 0);
518b5d2f
VZ
690}
691
692// ----------------------------------------------------------------------------
0fb67cd1 693// network and user id routines
518b5d2f
VZ
694// ----------------------------------------------------------------------------
695
0fb67cd1
VZ
696// retrieve either the hostname or FQDN depending on platform (caller must
697// check whether it's one or the other, this is why this function is for
698// private use only)
05079acc 699static bool wxGetHostNameInternal(wxChar *buf, int sz)
518b5d2f 700{
223d09f6 701 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
518b5d2f 702
223d09f6 703 *buf = wxT('\0');
518b5d2f
VZ
704
705 // we're using uname() which is POSIX instead of less standard sysinfo()
706#if defined(HAVE_UNAME)
cc743a6f 707 struct utsname uts;
518b5d2f
VZ
708 bool ok = uname(&uts) != -1;
709 if ( ok )
710 {
e90c1d2a 711 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
223d09f6 712 buf[sz] = wxT('\0');
518b5d2f
VZ
713 }
714#elif defined(HAVE_GETHOSTNAME)
715 bool ok = gethostname(buf, sz) != -1;
0fb67cd1 716#else // no uname, no gethostname
223d09f6 717 wxFAIL_MSG(wxT("don't know host name for this machine"));
518b5d2f
VZ
718
719 bool ok = FALSE;
0fb67cd1 720#endif // uname/gethostname
518b5d2f
VZ
721
722 if ( !ok )
723 {
724 wxLogSysError(_("Cannot get the hostname"));
725 }
726
727 return ok;
728}
729
05079acc 730bool wxGetHostName(wxChar *buf, int sz)
0fb67cd1
VZ
731{
732 bool ok = wxGetHostNameInternal(buf, sz);
733
734 if ( ok )
735 {
736 // BSD systems return the FQDN, we only want the hostname, so extract
737 // it (we consider that dots are domain separators)
223d09f6 738 wxChar *dot = wxStrchr(buf, wxT('.'));
0fb67cd1
VZ
739 if ( dot )
740 {
741 // nuke it
223d09f6 742 *dot = wxT('\0');
0fb67cd1
VZ
743 }
744 }
745
746 return ok;
747}
748
05079acc 749bool wxGetFullHostName(wxChar *buf, int sz)
0fb67cd1
VZ
750{
751 bool ok = wxGetHostNameInternal(buf, sz);
752
753 if ( ok )
754 {
223d09f6 755 if ( !wxStrchr(buf, wxT('.')) )
0fb67cd1 756 {
e90c1d2a 757 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
0fb67cd1
VZ
758 if ( !host )
759 {
760 wxLogSysError(_("Cannot get the official hostname"));
761
762 ok = FALSE;
763 }
764 else
765 {
766 // the canonical name
e90c1d2a 767 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
0fb67cd1
VZ
768 }
769 }
770 //else: it's already a FQDN (BSD behaves this way)
771 }
772
773 return ok;
774}
775
05079acc 776bool wxGetUserId(wxChar *buf, int sz)
518b5d2f
VZ
777{
778 struct passwd *who;
779
223d09f6 780 *buf = wxT('\0');
518b5d2f
VZ
781 if ((who = getpwuid(getuid ())) != NULL)
782 {
e90c1d2a 783 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
518b5d2f
VZ
784 return TRUE;
785 }
786
787 return FALSE;
788}
789
05079acc 790bool wxGetUserName(wxChar *buf, int sz)
518b5d2f
VZ
791{
792 struct passwd *who;
518b5d2f 793
223d09f6 794 *buf = wxT('\0');
b12915c1
VZ
795 if ((who = getpwuid (getuid ())) != NULL)
796 {
797 // pw_gecos field in struct passwd is not standard
bd3277fe 798#ifdef HAVE_PW_GECOS
b12915c1 799 char *comma = strchr(who->pw_gecos, ',');
518b5d2f
VZ
800 if (comma)
801 *comma = '\0'; // cut off non-name comment fields
e90c1d2a 802 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
b12915c1 803#else // !HAVE_PW_GECOS
0fcdf6dc 804 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
b12915c1 805#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
518b5d2f
VZ
806 return TRUE;
807 }
808
809 return FALSE;
810}
811
e2478fde 812// this function is in mac/utils.cpp for wxMac
6e73695c 813#ifndef __WXMAC__
e2478fde 814
bdc72a22
VZ
815wxString wxGetOsDescription()
816{
817#ifndef WXWIN_OS_DESCRIPTION
818 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
819#else
2b5f62a0 820 return wxString::FromAscii( WXWIN_OS_DESCRIPTION );
bdc72a22
VZ
821#endif
822}
823
e2478fde 824#endif // !__WXMAC__
bd3277fe 825
c1cb4153
VZ
826unsigned long wxGetProcessId()
827{
828 return (unsigned long)getpid();
829}
830
bd3277fe
VZ
831long wxGetFreeMemory()
832{
833#if defined(__LINUX__)
834 // get it from /proc/meminfo
835 FILE *fp = fopen("/proc/meminfo", "r");
836 if ( fp )
837 {
838 long memFree = -1;
839
840 char buf[1024];
841 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
842 {
843 long memTotal, memUsed;
844 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
845 }
846
847 fclose(fp);
848
849 return memFree;
850 }
851#elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
852 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
853//#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
854#endif
855
856 // can't find it out
857 return -1;
858}
859
eadd7bd2
VZ
860bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
861{
9952adac 862#if defined(HAVE_STATFS) || defined(HAVE_STATVFS)
fbfb3fb3 863 // the case to "char *" is needed for AIX 4.3
85da04e9
VZ
864 wxStatfs_t fs;
865 if ( wxStatfs((char *)(const char*)path.fn_str(), &fs) != 0 )
eadd7bd2 866 {
401eb3de 867 wxLogSysError( wxT("Failed to get file system statistics") );
eadd7bd2
VZ
868
869 return FALSE;
870 }
871
125cb99b
VZ
872 // under Solaris we also have to use f_frsize field instead of f_bsize
873 // which is in general a multiple of f_frsize
874#ifdef HAVE_STATVFS
875 wxLongLong blockSize = fs.f_frsize;
876#else // HAVE_STATFS
877 wxLongLong blockSize = fs.f_bsize;
878#endif // HAVE_STATVFS/HAVE_STATFS
9952adac 879
eadd7bd2
VZ
880 if ( pTotal )
881 {
125cb99b 882 *pTotal = wxLongLong(fs.f_blocks) * blockSize;
eadd7bd2
VZ
883 }
884
885 if ( pFree )
886 {
125cb99b 887 *pFree = wxLongLong(fs.f_bavail) * blockSize;
eadd7bd2
VZ
888 }
889
890 return TRUE;
125cb99b 891#else // !HAVE_STATFS && !HAVE_STATVFS
eadd7bd2 892 return FALSE;
125cb99b 893#endif // HAVE_STATFS
eadd7bd2
VZ
894}
895
8fd0d89b
VZ
896// ----------------------------------------------------------------------------
897// env vars
898// ----------------------------------------------------------------------------
899
97b305b7 900bool wxGetEnv(const wxString& var, wxString *value)
308978f6
VZ
901{
902 // wxGetenv is defined as getenv()
903 wxChar *p = wxGetenv(var);
904 if ( !p )
905 return FALSE;
906
907 if ( value )
908 {
909 *value = p;
910 }
911
912 return TRUE;
913}
914
8fd0d89b
VZ
915bool wxSetEnv(const wxString& variable, const wxChar *value)
916{
917#if defined(HAVE_SETENV)
d90b2df8
VZ
918 return setenv(variable.mb_str(),
919 value ? (const char *)wxString(value).mb_str()
920 : NULL,
921 1 /* overwrite */) == 0;
8fd0d89b
VZ
922#elif defined(HAVE_PUTENV)
923 wxString s = variable;
924 if ( value )
925 s << _T('=') << value;
926
927 // transform to ANSI
928 const char *p = s.mb_str();
929
930 // the string will be free()d by libc
931 char *buf = (char *)malloc(strlen(p) + 1);
932 strcpy(buf, p);
933
934 return putenv(buf) == 0;
935#else // no way to set an env var
936 return FALSE;
937#endif
938}
939
a37a5a73
VZ
940// ----------------------------------------------------------------------------
941// signal handling
942// ----------------------------------------------------------------------------
943
944#if wxUSE_ON_FATAL_EXCEPTION
945
946#include <signal.h>
947
90350682 948extern "C" void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
a37a5a73
VZ
949{
950 if ( wxTheApp )
951 {
952 // give the user a chance to do something special about this
953 wxTheApp->OnFatalException();
954 }
955
956 abort();
957}
958
959bool wxHandleFatalExceptions(bool doit)
960{
961 // old sig handlers
962 static bool s_savedHandlers = FALSE;
963 static struct sigaction s_handlerFPE,
964 s_handlerILL,
965 s_handlerBUS,
966 s_handlerSEGV;
967
968 bool ok = TRUE;
969 if ( doit && !s_savedHandlers )
970 {
971 // install the signal handler
972 struct sigaction act;
973
974 // some systems extend it with non std fields, so zero everything
975 memset(&act, 0, sizeof(act));
976
977 act.sa_handler = wxFatalSignalHandler;
978 sigemptyset(&act.sa_mask);
979 act.sa_flags = 0;
980
981 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
982 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
983 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
984 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
985 if ( !ok )
986 {
987 wxLogDebug(_T("Failed to install our signal handler."));
988 }
989
990 s_savedHandlers = TRUE;
991 }
992 else if ( s_savedHandlers )
993 {
994 // uninstall the signal handler
995 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
996 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
997 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
998 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
999 if ( !ok )
1000 {
1001 wxLogDebug(_T("Failed to uninstall our signal handler."));
1002 }
1003
1004 s_savedHandlers = FALSE;
1005 }
1006 //else: nothing to do
1007
1008 return ok;
1009}
1010
1011#endif // wxUSE_ON_FATAL_EXCEPTION
1012
518b5d2f
VZ
1013// ----------------------------------------------------------------------------
1014// error and debug output routines (deprecated, use wxLog)
1015// ----------------------------------------------------------------------------
1016
73deed44
VZ
1017#if WXWIN_COMPATIBILITY_2_2
1018
518b5d2f
VZ
1019void wxDebugMsg( const char *format, ... )
1020{
1021 va_list ap;
1022 va_start( ap, format );
1023 vfprintf( stderr, format, ap );
1024 fflush( stderr );
1025 va_end(ap);
1026}
1027
1028void wxError( const wxString &msg, const wxString &title )
1029{
05079acc 1030 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1031 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1032 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1033 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1034}
1035
1036void wxFatalError( const wxString &msg, const wxString &title )
1037{
05079acc 1038 wxFprintf( stderr, _("Error ") );
223d09f6
KB
1039 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1040 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1041 wxFprintf( stderr, wxT(".\n") );
518b5d2f
VZ
1042 exit(3); // the same exit code as for abort()
1043}
93ccaed8 1044
73deed44
VZ
1045#endif // WXWIN_COMPATIBILITY_2_2
1046
ec67cff1 1047#endif // wxUSE_BASE
e2478fde
VZ
1048
1049#if wxUSE_GUI
1050
1051// ----------------------------------------------------------------------------
1052// wxExecute support
1053// ----------------------------------------------------------------------------
1054
1055// Darwin doesn't use the same process end detection mechanisms so we don't
1056// need wxExecute-related helpers for it
1057#if !(defined(__DARWIN__) && defined(__WXMAC__))
1058
1059bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& execData)
1060{
1061 return execData.pipeEndProcDetect.Create();
1062}
1063
1064bool wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& execData, int fd)
1065{
46446cc2 1066 return fd == (execData.pipeEndProcDetect)[wxPipe::Write];
e2478fde
VZ
1067}
1068
1069void wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& execData)
1070{
1071 execData.pipeEndProcDetect.Detach(wxPipe::Write);
1072 execData.pipeEndProcDetect.Close();
1073}
1074
1075#else // !Darwin
1076
1077bool wxGUIAppTraits::CreateEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1078{
1079 return true;
1080}
1081
1082bool
1083wxGUIAppTraits::IsWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData),
1084 int WXUNUSED(fd))
1085{
1086 return false;
1087}
1088
1089void
1090wxGUIAppTraits::DetachWriteFDOfEndProcessPipe(wxExecuteData& WXUNUSED(execData))
1091{
1092 // nothing to do here, we don't use the pipe
1093}
1094
1095#endif // !Darwin/Darwin
1096
1097int wxGUIAppTraits::WaitForChild(wxExecuteData& execData)
1098{
1099 wxEndProcessData *endProcData = new wxEndProcessData;
1100
1101 // wxAddProcessCallback is now (with DARWIN) allowed to call the
1102 // callback function directly if the process terminates before
1103 // the callback can be added to the run loop. Set up the endProcData.
1104 if ( execData.flags & wxEXEC_SYNC )
1105 {
1106 // we may have process for capturing the program output, but it's
1107 // not used in wxEndProcessData in the case of sync execution
1108 endProcData->process = NULL;
1109
1110 // sync execution: indicate it by negating the pid
1111 endProcData->pid = -execData.pid;
1112 }
1113 else
1114 {
1115 // async execution, nothing special to do -- caller will be
1116 // notified about the process termination if process != NULL, endProcData
1117 // will be deleted in GTK_EndProcessDetector
1118 endProcData->process = execData.process;
1119 endProcData->pid = execData.pid;
1120 }
1121
1122
1123#if defined(__DARWIN__) && defined(__WXMAC__)
1124 endProcData->tag = wxAddProcessCallbackForPid(endProcData, execData.pid);
1125#else
1126 endProcData->tag = wxAddProcessCallback
1127 (
1128 endProcData,
1129 execData.pipeEndProcDetect.Detach(wxPipe::Read)
1130 );
1131
1132 execData.pipeEndProcDetect.Close();
1133#endif // defined(__DARWIN__) && defined(__WXMAC__)
1134
1135 if ( execData.flags & wxEXEC_SYNC )
1136 {
1137 wxBusyCursor bc;
1138 wxWindowDisabler wd;
1139
1140 // endProcData->pid will be set to 0 from GTK_EndProcessDetector when the
1141 // process terminates
1142 while ( endProcData->pid != 0 )
1143 {
05df0f1b
VZ
1144 bool idle = true;
1145
e2478fde
VZ
1146#if wxUSE_STREAMS
1147 if ( execData.bufOut )
05df0f1b 1148 {
e2478fde 1149 execData.bufOut->Update();
05df0f1b
VZ
1150 idle = false;
1151 }
e2478fde
VZ
1152
1153 if ( execData.bufErr )
05df0f1b 1154 {
e2478fde 1155 execData.bufErr->Update();
05df0f1b
VZ
1156 idle = false;
1157 }
e2478fde
VZ
1158#endif // wxUSE_STREAMS
1159
05df0f1b
VZ
1160 // don't consume 100% of the CPU while we're sitting this in this
1161 // loop
1162 if ( idle )
1163 wxUsleep(1);
1164
e2478fde
VZ
1165 // give GTK+ a chance to call GTK_EndProcessDetector here and
1166 // also repaint the GUI
1167 wxYield();
1168 }
1169
1170 int exitcode = endProcData->exitcode;
1171
1172 delete endProcData;
1173
1174 return exitcode;
1175 }
1176 else // async execution
1177 {
1178 return execData.pid;
1179 }
1180}
1181
2dbc444a
RD
1182#endif // wxUSE_GUI
1183#if wxUSE_BASE
1184
e2478fde
VZ
1185void wxHandleProcessTermination(wxEndProcessData *proc_data)
1186{
1187 // notify user about termination if required
1188 if ( proc_data->process )
1189 {
1190 proc_data->process->OnTerminate(proc_data->pid, proc_data->exitcode);
1191 }
1192
1193 // clean up
1194 if ( proc_data->pid > 0 )
1195 {
1196 delete proc_data;
1197 }
1198 else
1199 {
1200 // let wxExecute() know that the process has terminated
1201 proc_data->pid = 0;
1202 }
1203}
1204
2dbc444a 1205#endif // wxUSE_BASE