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