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