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