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