switch (status)
{
- case eventLoopTimedOutErr :
+ case eventLoopTimedOutErr :
if ( wxTheApp->ProcessIdle() )
sleepTime = kEventDurationNoWait ;
else
sleepTime = kEventDurationSecond;
break;
- case eventLoopQuitErr :
+ case eventLoopQuitErr :
// according to QA1061 this may also occur
// when a WakeUp Process is executed
break;
switch (GetWindowVariant())
{
- case wxWINDOW_VARIANT_NORMAL:
- case wxWINDOW_VARIANT_LARGE:
+ case wxWINDOW_VARIANT_NORMAL:
+ case wxWINDOW_VARIANT_LARGE:
sz.y = 20 ;
charspace = 10 ;
break;
- case wxWINDOW_VARIANT_SMALL:
+ case wxWINDOW_VARIANT_SMALL:
sz.y = 17 ;
break;
- case wxWINDOW_VARIANT_MINI:
+ case wxWINDOW_VARIANT_MINI:
sz.y = 15 ;
break;
/////////////////////////////////////////////////////////////////////////////
-// Name: socket.cpp
+// Name: src/mac/carbon/cfsocket.cpp
// Purpose: Socket handler classes
// Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
// Created: April 1997
// License: see wxWindows licence
/////////////////////////////////////////////////////////////////////////////
-// ==========================================================================
-// Declarations
-// ==========================================================================
-
-// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
// DLL options compatibility check:
#include "wx/build.h"
+
WX_CHECK_BUILD_OPTIONS("wxNet")
-// --------------------------------------------------------------------------
-// macros and constants
-// --------------------------------------------------------------------------
// discard buffer
#define MAX_DISCARD_SIZE (10 * 1024)
#define wxTRACE_Socket _T("wxSocket")
-// --------------------------------------------------------------------------
-// wxWin macros
-// --------------------------------------------------------------------------
IMPLEMENT_CLASS(wxSocketBase, wxObject)
IMPLEMENT_CLASS(wxSocketServer, wxSocketBase)
int m_establishing;
unsigned long m_timeout;
-
- /* Callbacks */
+ // Callbacks
GSocketEventFlags m_detected;
GSocketCallback m_cbacks[GSOCK_MAX_EVENT];
char *m_data[GSOCK_MAX_EVENT];
CFRunLoopSourceRef m_runLoopSource;
CFReadStreamRef m_readStream ;
CFWriteStreamRef m_writeStream ;
-} ;
+};
struct _GAddress
{
#if 0
wxAppTraits *traits = wxAppConsole::GetInstance() ?
wxAppConsole::GetInstance()->GetTraits() : NULL;
- GSocketGUIFunctionsTable *functions =
+ GSocketGUIFunctionsTable *functions =
traits ? traits->GetSocketGUIFunctionsTable() : NULL;
GSocket_SetGUIFunctions(functions);
-
+
if ( !GSocket_Init() )
{
m_countInit--;
- return FALSE;
+ return false;
}
#endif
}
- return TRUE;
+ return true;
}
void wxSocketBase::Shutdown()
{
// we should be initialized
- wxASSERT_MSG( m_countInit, _T("extra call to Shutdown()") );
+ wxASSERT_MSG( m_countInit, wxT("extra call to Shutdown()") );
if ( !--m_countInit )
{
#if 0
m_establishing =
m_reading =
m_writing =
- m_error = FALSE;
+ m_error = false;
m_lcount = 0;
m_timeout = 600;
- m_beingDeleted = FALSE;
+ m_beingDeleted = false;
// pushback buffer
m_unread = NULL;
m_id = -1;
m_handler = NULL;
m_clientData = NULL;
- m_notify = FALSE;
+ m_notify = false;
m_eventmask = 0;
if ( !IsInitialized() )
Init();
}
-wxSocketBase::wxSocketBase(wxSocketFlags flags, wxSocketType type)
+wxSocketBase::wxSocketBase( wxSocketFlags flags, wxSocketType type)
{
Init();
// Delayed destruction: the socket will be deleted during the next
// idle loop iteration. This ensures that all pending events have
// been processed.
- m_beingDeleted = TRUE;
+ m_beingDeleted = true;
// Shutdown and close the socket
Close();
// Supress events from now on
- Notify(FALSE);
+ Notify(false);
// schedule this object for deletion
wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
delete this;
}
- return TRUE;
+ return true;
}
// --------------------------------------------------------------------------
InterruptWait();
if (m_socket)
- {
GSocket_Shutdown(m_socket);
- }
- m_connected = FALSE;
- m_establishing = FALSE;
- return TRUE;
+ m_connected = false;
+ m_establishing = false;
+
+ return true;
}
wxSocketBase& wxSocketBase::Read(void* buffer, wxUint32 nbytes)
{
// Mask read events
- m_reading = TRUE;
+ m_reading = true;
m_lcount = _Read(buffer, nbytes);
m_error = (m_lcount == 0);
// Allow read events from now on
- m_reading = FALSE;
+ m_reading = false;
return *this;
}
int total = 0;
// Try the pushback buffer first
- total = GetPushback(buffer, nbytes, FALSE);
+ total = GetPushback(buffer, nbytes, false);
nbytes -= total;
buffer = (char *)buffer + total;
}
else
{
- bool more = TRUE;
+ bool more = true;
while (more)
{
{
unsigned char sig[4];
unsigned char len[4];
- } msg;
+ }
+ msg;
// Mask read events
- m_reading = TRUE;
+ m_reading = true;
total = 0;
- error = TRUE;
+ error = true;
old_flags = m_flags;
SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
if (sig != 0xfeeddead)
{
- wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
+ wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
goto exit;
}
if (sig != 0xdeadfeed)
{
- wxLogWarning(_("wxSocket: invalid signature in ReadMsg."));
+ wxLogWarning( wxT("wxSocket: invalid signature in ReadMsg.") );
goto exit;
}
// everything was OK
- error = FALSE;
+ error = false;
exit:
m_error = error;
m_lcount = total;
- m_reading = FALSE;
+ m_reading = false;
SetFlags(old_flags);
return *this;
wxSocketBase& wxSocketBase::Peek(void* buffer, wxUint32 nbytes)
{
// Mask read events
- m_reading = TRUE;
+ m_reading = true;
m_lcount = _Read(buffer, nbytes);
Pushback(buffer, m_lcount);
m_error = (m_lcount == 0);
// Allow read events again
- m_reading = FALSE;
+ m_reading = false;
return *this;
}
wxSocketBase& wxSocketBase::Write(const void *buffer, wxUint32 nbytes)
{
// Mask write events
- m_writing = TRUE;
+ m_writing = true;
m_lcount = _Write(buffer, nbytes);
m_error = (m_lcount == 0);
// Allow write events again
- m_writing = FALSE;
+ m_writing = false;
return *this;
}
}
else
{
- bool more = TRUE;
+ bool more = true;
while (more)
{
{
unsigned char sig[4];
unsigned char len[4];
- } msg;
+ }
+ msg;
// Mask write events
- m_writing = TRUE;
+ m_writing = true;
- error = TRUE;
+ error = true;
total = 0;
SetFlags((m_flags & wxSOCKET_BLOCK) | wxSOCKET_WAITALL);
goto exit;
// everything was OK
- error = FALSE;
+ error = false;
exit:
m_error = error;
m_lcount = total;
- m_writing = FALSE;
+ m_writing = false;
return *this;
}
if (nbytes != 0)
Pushback(buffer, nbytes);
- m_error = FALSE;
+ m_error = false;
m_lcount = nbytes;
return *this;
wxUint32 total = 0;
// Mask read events
- m_reading = TRUE;
+ m_reading = true;
SetFlags(wxSOCKET_NOWAIT);
delete[] buffer;
m_lcount = total;
- m_error = FALSE;
+ m_error = false;
// Allow read events again
- m_reading = FALSE;
+ m_reading = false;
return *this;
}
bool wxSocketBase::_Wait(long seconds,
long milliseconds,
wxSocketEventFlags flags)
-{
-
+{
GSocketEventFlags result;
long timeout;
- // Set this to TRUE to interrupt ongoing waits
- m_interrupt = FALSE;
+ // Set this to true to interrupt ongoing waits
+ m_interrupt = false;
// Check for valid socket
if (!m_socket)
- return FALSE;
+ return false;
// Check for valid timeout value.
if (seconds != -1)
#if !defined(wxUSE_GUI) || !wxUSE_GUI
GSocket_SetTimeout(m_socket, timeout);
-#endif
+#endif
// Wait in an active polling loop.
//
// we are just polling). Also, if just polling, do not yield.
wxStopWatch chrono;
- bool done = FALSE;
+ bool done = false;
while (!done)
{
// Incoming connection (server) or connection established (client)
if (result & GSOCK_CONNECTION_FLAG)
{
- m_connected = TRUE;
- m_establishing = FALSE;
- return TRUE;
+ m_connected = true;
+ m_establishing = false;
+
+ return true;
}
// Data available or output buffer ready
if ((result & GSOCK_INPUT_FLAG) || (result & GSOCK_OUTPUT_FLAG))
{
- return TRUE;
+ return true;
}
// Connection lost
if (result & GSOCK_LOST_FLAG)
{
- m_connected = FALSE;
- m_establishing = FALSE;
+ m_connected = false;
+ m_establishing = false;
+
return (flags & GSOCK_LOST_FLAG) != 0;
}
// Wait more?
if ((!timeout) || (chrono.Time() > timeout) || (m_interrupt))
- done = TRUE;
+ done = true;
else
PROCESS_EVENTS();
}
- return FALSE;
+ return false;
}
bool wxSocketBase::Wait(long seconds, long milliseconds)
{
// Check pushback buffer before entering _Wait
if (m_unread)
- return TRUE;
+ return true;
// Note that GSOCK_INPUT_LOST has to be explicitly passed to
// _Wait becuase of the semantics of WaitForRead: a return
- // value of TRUE means that a GSocket_Read call will return
+ // value of true means that a GSocket_Read call will return
// immediately, not that there is actually data to read.
- return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG |
- GSOCK_LOST_FLAG);
+ return _Wait(seconds, milliseconds, GSOCK_INPUT_FLAG | GSOCK_LOST_FLAG);
}
bool wxSocketBase::WaitForWrite(long seconds, long milliseconds)
GAddress *peer;
if (!m_socket)
- return FALSE;
+ return false;
peer = GSocket_GetPeer(m_socket);
// copying a null address would just trigger an assert anyway
if (!peer)
- return FALSE;
+ return false;
addr_man.SetAddress(peer);
GAddress_destroy(peer);
- return TRUE;
+ return true;
}
bool wxSocketBase::GetLocal(wxSockAddress& addr_man) const
GAddress *local;
if (!m_socket)
- return FALSE;
+ return false;
local = GSocket_GetLocal(m_socket);
addr_man.SetAddress(local);
GAddress_destroy(local);
#endif
- return TRUE;
+
+ return true;
}
//
m_notify = state->m_notify;
m_eventmask = state->m_eventmask;
m_clientData = state->m_clientData;
-
+
m_states.Erase(node);
delete state;
}
void wxSocketBase::OnRequest(wxSocketNotify notification)
{
// NOTE: We duplicate some of the code in _Wait, but this doesn't
- // hurt. It has to be here because the (GSocket) event might arrive
- // a bit delayed, and it has to be in _Wait as well because we don't
- // know whether the Wait functions are being used.
+ // hurt. It has to be here because the (GSocket) event might arrive
+ // a bit delayed, and it has to be in _Wait as well because we don't
+ // know whether the Wait functions are being used.
- switch(notification)
+ switch (notification)
{
case wxSOCKET_CONNECTION:
- m_establishing = FALSE;
- m_connected = TRUE;
+ m_establishing = false;
+ m_connected = true;
break;
// If we are in the middle of a R/W operation, do not
break;
case wxSOCKET_LOST:
- m_connected = FALSE;
- m_establishing = FALSE;
+ m_connected = false;
+ m_establishing = false;
break;
default:
wxUnusedVar(flag);
switch (notification)
{
- case GSOCK_INPUT: flag = GSOCK_INPUT_FLAG; break;
- case GSOCK_OUTPUT: flag = GSOCK_OUTPUT_FLAG; break;
- case GSOCK_CONNECTION: flag = GSOCK_CONNECTION_FLAG; break;
- case GSOCK_LOST: flag = GSOCK_LOST_FLAG; break;
+ case GSOCK_INPUT:
+ flag = GSOCK_INPUT_FLAG;
+ break;
+
+ case GSOCK_OUTPUT:
+ flag = GSOCK_OUTPUT_FLAG;
+ break;
+
+ case GSOCK_CONNECTION:
+ flag = GSOCK_CONNECTION_FLAG;
+ break;
+
+ case GSOCK_LOST:
+ flag = GSOCK_LOST_FLAG;
+ break;
+
default:
- wxLogWarning(_("wxSocket: unknown event!."));
+ wxLogWarning( wxT("wxSocket: unknown event!") );
return;
}
void wxSocketBase::Pushback(const void *buffer, wxUint32 size)
{
- if (!size) return;
+ if (!size)
+ return;
if (m_unread == NULL)
m_unread = malloc(size);
wxSocketFlags flags)
: wxSocketBase(flags, wxSOCKET_SERVER)
{
- wxLogTrace( wxTRACE_Socket, _T("Opening wxSocketServer") );
+ wxLogTrace( wxTRACE_Socket, wxT("Opening wxSocketServer") );
m_socket = GSocket_new();
if (!m_socket)
{
- wxLogTrace( wxTRACE_Socket, _T("*** GSocket_new failed") );
+ wxLogTrace( wxTRACE_Socket, wxT("*** GSocket_new failed") );
return;
}
- // Setup the socket as server
+ // Setup the socket as server
#if 0
GSocket_SetLocal(m_socket, addr_man.GetAddress());
GSocket_destroy(m_socket);
m_socket = NULL;
- wxLogTrace( wxTRACE_Socket, _T("*** GSocket_SetServer failed") );
+ wxLogTrace( wxTRACE_Socket, wxT("*** GSocket_SetServer failed") );
return;
}
GSocket *child_socket;
if (!m_socket)
- return FALSE;
+ return false;
- // If wait == FALSE, then the call should be nonblocking.
+ // If wait == false, then the call should be nonblocking.
// When we are finished, we put the socket to blocking mode
// again.
GSocket_SetNonBlocking(m_socket, 0);
if (!child_socket)
- return FALSE;
+ return false;
sock.m_type = wxSOCKET_BASE;
sock.m_socket = child_socket;
- sock.m_connected = TRUE;
+ sock.m_connected = true;
GSocket_SetTimeout(sock.m_socket, sock.m_timeout * 1000);
GSocket_SetCallback(sock.m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
wx_socket_callback, (char *)&sock);
#endif
- return TRUE;
+
+ return true;
}
wxSocketBase *wxSocketServer::Accept(bool wait)
bool wxSocketClient::Connect(wxSockAddress& addr_man, bool wait)
{
- GSocketError err ;
+ GSocketError err;
if (m_socket)
{
}
m_socket = GSocket_new();
- m_connected = FALSE;
- m_establishing = FALSE;
+ m_connected = false;
+ m_establishing = false;
if (!m_socket)
- return FALSE;
+ return false;
GSocket_SetTimeout(m_socket, m_timeout * 1000);
GSocket_SetCallback(m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
wx_socket_callback, (char *)this);
- // If wait == FALSE, then the call should be nonblocking.
+ // If wait == false, then the call should be nonblocking.
// When we are finished, we put the socket to blocking mode
// again.
if (err != GSOCK_NOERROR)
{
if (err == GSOCK_WOULDBLOCK)
- m_establishing = TRUE;
+ m_establishing = true;
- return FALSE;
+ return false;
}
- m_connected = TRUE;
- return TRUE;
+ m_connected = true;
+ return true;
}
bool wxSocketClient::WaitOnConnect(long seconds, long milliseconds)
{
if (m_connected) // Already connected
- return TRUE;
+ return true;
if (!m_establishing || !m_socket) // No connection in progress
- return FALSE;
+ return false;
- return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG |
- GSOCK_LOST_FLAG);
+ return _Wait(seconds, milliseconds, GSOCK_CONNECTION_FLAG | GSOCK_LOST_FLAG);
}
// ==========================================================================
// Create the socket
m_socket = GSocket_new();
- if(!m_socket)
+ if (!m_socket)
return;
// Setup the socket as non connection oriented
}
// Initialize all stuff
- m_connected = FALSE;
- m_establishing = FALSE;
+ m_connected = false;
+ m_establishing = false;
GSocket_SetTimeout( m_socket, m_timeout );
GSocket_SetCallback( m_socket, GSOCK_INPUT_FLAG | GSOCK_OUTPUT_FLAG |
GSOCK_LOST_FLAG | GSOCK_CONNECTION_FLAG,
free(addr2);
return NULL;
}
+
memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
}
void GAddress_destroy(GAddress *address)
{
- assert(address != NULL);
+ assert( address != NULL );
if (address->m_addr)
free(address->m_addr);
GAddressType GAddress_GetFamily(GAddress *address)
{
- assert(address != NULL);
+ assert( address != NULL );
return address->m_family;
}
case AF_INET:
address->m_family = GSOCK_INET;
break;
+
case AF_UNIX:
address->m_family = GSOCK_UNIX;
break;
+
#ifdef AF_INET6
case AF_INET6:
address->m_family = GSOCK_INET6;
break;
#endif
+
default:
{
address->m_error = GSOCK_INVOP;
address->m_error = GSOCK_MEMERR;
return GSOCK_MEMERR;
}
+
memcpy(address->m_addr, addr, len);
return GSOCK_NOERROR;
struct hostent *he;
struct in_addr *addr;
- assert(address != NULL);
-
- CHECK_ADDRESS(address, INET);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, INET );
addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
- /* If it is a numeric host name, convert it now */
+ // If it is a numeric host name, convert it now
#if defined(HAVE_INET_ATON)
if (inet_aton(hostname, addr) == 0)
{
if ( (addr->s_addr = inet_addr(hostname)) == -1 )
{
#else
- /* Use gethostbyname by default */
+ // Use gethostbyname by default
#ifndef __WXMAC__
- int val = 1; /* VA doesn't like constants in conditional expressions */
+ int val = 1; // VA doesn't like constants in conditional expressions
if (val)
#endif
{
#endif
struct in_addr *array_addr;
- /* It is a real name, we solve it */
+ // It is a real name, we solve it
if ((he = gethostbyname(hostname)) == NULL)
{
- /* Reset to invalid address */
+ // Reset to invalid address
addr->s_addr = INADDR_NONE;
address->m_error = GSOCK_NOHOST;
return GSOCK_NOHOST;
array_addr = (struct in_addr *) *(he->h_addr_list);
addr->s_addr = array_addr[0].s_addr;
}
+
return GSOCK_NOERROR;
}
{
struct in_addr *addr;
- assert(address != NULL);
-
- CHECK_ADDRESS(address, INET);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, INET );
addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
addr->s_addr = htonl(hostaddr) ;
struct servent *se;
struct sockaddr_in *addr;
- assert(address != NULL);
- CHECK_ADDRESS(address, INET);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, INET );
if (!port)
{
address->m_error = GSOCK_INVPORT;
return GSOCK_INVPORT;
}
-
+
se = getservbyname(port, protocol);
if (!se)
{
- /* the cast to int suppresses compiler warnings about subscript having the
- type char */
+ // the cast to int suppresses compiler warnings
+ // about subscript having the type char
if (isdigit((int)port[0]))
{
int port_int;
{
struct sockaddr_in *addr;
- assert(address != NULL);
- CHECK_ADDRESS(address, INET);
-
+ assert( address != NULL );
+ CHECK_ADDRESS( address, INET );
+
addr = (struct sockaddr_in *)address->m_addr;
addr->sin_port = htons(port);
char *addr_buf;
struct sockaddr_in *addr;
- assert(address != NULL);
- CHECK_ADDRESS(address, INET);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, INET );
addr = (struct sockaddr_in *)address->m_addr;
addr_buf = (char *)&(addr->sin_addr);
{
struct sockaddr_in *addr;
- assert(address != NULL);
- CHECK_ADDRESS_RETVAL(address, INET, 0);
+ assert( address != NULL );
+ CHECK_ADDRESS_RETVAL( address, INET, 0 );
addr = (struct sockaddr_in *)address->m_addr;
{
struct sockaddr_in *addr;
- assert(address != NULL);
- CHECK_ADDRESS_RETVAL(address, INET, 0);
+ assert( address != NULL );
+ CHECK_ADDRESS_RETVAL( address, INET, 0 );
addr = (struct sockaddr_in *)address->m_addr;
+
return ntohs(addr->sin_port);
}
{
struct sockaddr_un *addr;
- assert(address != NULL);
-
- CHECK_ADDRESS(address, UNIX);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, UNIX );
addr = ((struct sockaddr_un *)address->m_addr);
strncpy(addr->sun_path, path, UNIX_SOCK_PATHLEN);
{
struct sockaddr_un *addr;
- assert(address != NULL);
- CHECK_ADDRESS(address, UNIX);
+ assert( address != NULL );
+ CHECK_ADDRESS( address, UNIX );
addr = (struct sockaddr_un *)address->m_addr;
* GSOCK_INVSOCK - the socket is not valid.
* GSOCK_INVADDR - the address is not valid.
*/
-
+
GSocketError GSocket_SetLocal(GSocket *socket, GAddress *address)
{
- assert(socket != NULL);
+ assert( socket != NULL );
- /* the socket must be initialized, or it must be a server */
+ // the socket must be initialized, or it must be a server
if ((socket->m_fd != INVALID_SOCKET && !socket->m_server))
{
socket->m_error = GSOCK_INVSOCK;
return GSOCK_INVSOCK;
}
- /* check address */
+ // check address
if (address == NULL || address->m_family == GSOCK_NOFAMILY)
{
socket->m_error = GSOCK_INVADDR;
{
assert(socket != NULL);
- /* check address */
+ // check address
if (address == NULL || address->m_family == GSOCK_NOFAMILY)
{
socket->m_error = GSOCK_INVADDR;
socklen_t size = sizeof(addr);
GSocketError err;
- assert(socket != NULL);
+ assert( socket != NULL );
- /* try to get it from the m_local var first */
+ // try to get it from the m_local var first
if (socket->m_local)
return GAddress_copy(socket->m_local);
- /* else, if the socket is initialized, try getsockname */
+ // else, if the socket is initialized, try getsockname
if (socket->m_fd == INVALID_SOCKET)
{
socket->m_error = GSOCK_INVSOCK;
return NULL;
}
- /* got a valid address from getsockname, create a GAddress object */
+ // got a valid address from getsockname, create a GAddress object
address = GAddress_new();
if (address == NULL)
{
{
assert(socket != NULL);
- /* try to get it from the m_peer var */
+ // try to get it from the m_peer var
if (socket->m_peer)
return GAddress_copy(socket->m_peer);
return NULL;
}
-//
-//
-//
-
GSocket *GSocket_new(void)
{
if (socket == NULL)
return NULL;
-
+
socket->m_fd = INVALID_SOCKET;
for (int i=0;i<GSOCK_MAX_EVENT;i++)
{
- socket->m_cbacks[i] = NULL;
+ socket->m_cbacks[i] = NULL;
}
+
socket->m_detected = 0;
socket->m_local = NULL;
socket->m_peer = NULL;
socket->m_error = GSOCK_NOERROR;
- socket->m_non_blocking = FALSE ;
- socket->m_stream = TRUE;
-// socket->m_oriented = TRUE;
- socket->m_server = FALSE;
- socket->m_establishing = FALSE;
- socket->m_timeout = 10*60*1000;
- /* 10 minutes * 60 sec * 1000 millisec */
-
+ socket->m_non_blocking = false ;
+ socket->m_stream = true;
+// socket->m_oriented = true;
+ socket->m_server = false;
+ socket->m_establishing = false;
+ socket->m_timeout = 10 * 60 * 1000;
+ // 10 minutes * 60 sec * 1000 millisec
+
socket->m_cfSocket = NULL ;
socket->m_runLoopSource = NULL ;
socket->m_readStream = NULL;
socket->m_writeStream = NULL;
-
+
return socket ;
}
void GSocket_close(GSocket *socket)
{
- if ( socket->m_cfSocket != NULL )
- {
- if ( socket->m_readStream )
- {
- CFReadStreamClose(socket->m_readStream);
- CFRelease( socket->m_readStream ) ;
- socket->m_readStream = NULL ;
- }
- if ( socket->m_writeStream )
+ if ( socket->m_cfSocket != NULL )
{
- CFWriteStreamClose(socket->m_writeStream);
- CFRelease( socket->m_writeStream ) ;
- socket->m_writeStream = NULL ;
- }
+ if ( socket->m_readStream )
+ {
+ CFReadStreamClose(socket->m_readStream);
+ CFRelease( socket->m_readStream ) ;
+ socket->m_readStream = NULL ;
+ }
- CFSocketInvalidate( socket->m_cfSocket ) ;
- CFRelease( socket->m_cfSocket ) ;
- socket->m_cfSocket = NULL ;
- socket->m_fd = INVALID_SOCKET ;
- }
+ if ( socket->m_writeStream )
+ {
+ CFWriteStreamClose(socket->m_writeStream);
+ CFRelease( socket->m_writeStream ) ;
+ socket->m_writeStream = NULL ;
+ }
+
+ CFSocketInvalidate( socket->m_cfSocket ) ;
+ CFRelease( socket->m_cfSocket ) ;
+ socket->m_cfSocket = NULL ;
+ socket->m_fd = INVALID_SOCKET ;
+ }
}
void GSocket_Shutdown(GSocket *socket)
{
- GSocket_close( socket ) ;
+ GSocket_close( socket );
- /* Disable GUI callbacks */
- for (int evt = 0; evt < GSOCK_MAX_EVENT; evt++)
- socket->m_cbacks[evt] = NULL;
+ // Disable GUI callbacks
+ for (int evt = 0; evt < GSOCK_MAX_EVENT; evt++)
+ socket->m_cbacks[evt] = NULL;
- socket->m_detected = GSOCK_LOST_FLAG;
+ socket->m_detected = GSOCK_LOST_FLAG;
}
void GSocket_destroy(GSocket *socket)
{
- assert(socket != NULL);
+ assert( socket != NULL );
- /* Check that the socket is really shutdowned */
+ // Check that the socket is really shut down
if (socket->m_fd != INVALID_SOCKET)
GSocket_Shutdown(socket);
- /* Destroy private addresses */
+ // Destroy private addresses
if (socket->m_local)
GAddress_destroy(socket->m_local);
if (socket->m_peer)
GAddress_destroy(socket->m_peer);
- /* Destroy the socket itself */
+ // Destroy the socket itself
free(socket);
}
GSocketError GSocket_Connect(GSocket *socket, GSocketStream stream)
{
- assert(socket != NULL);
+ assert( socket != NULL );
if (socket->m_fd != INVALID_SOCKET)
{
return GSOCK_INVADDR;
}
- /* Streamed or dgram socket? */
+ // Streamed or dgram socket?
socket->m_stream = (stream == GSOCK_STREAMED);
- socket->m_oriented = TRUE;
- socket->m_server = FALSE;
- socket->m_establishing = FALSE;
+ socket->m_oriented = true;
+ socket->m_server = false;
+ socket->m_establishing = false;
GSocketError returnErr = GSOCK_NOERROR ;
CFSocketError err ;
-
+
CFAllocatorRef alloc = kCFAllocatorDefault ;
CFSocketContext ctx ;
memset( &ctx , 0 , sizeof( ctx ) ) ;
ctx.info = socket ;
socket->m_cfSocket = CFSocketCreate( alloc , socket->m_peer->m_realfamily ,
- stream == GSOCK_STREAMED ? SOCK_STREAM : SOCK_DGRAM , 0 ,
+ stream == GSOCK_STREAMED ? SOCK_STREAM : SOCK_DGRAM , 0 ,
kCFSocketReadCallBack | kCFSocketWriteCallBack | kCFSocketConnectCallBack , wxMacCFSocketCallback , &ctx ) ;
_GSocket_Enable(socket, GSOCK_CONNECTION);
-
- socket->m_fd = CFSocketGetNative( socket->m_cfSocket ) ;
- CFStreamCreatePairWithSocket ( alloc , socket->m_fd , &socket->m_readStream , &socket->m_writeStream );
- if ((socket->m_readStream == NULL) || (socket->m_writeStream == NULL))
+ socket->m_fd = CFSocketGetNative( socket->m_cfSocket ) ;
+
+ CFStreamCreatePairWithSocket ( alloc , socket->m_fd , &socket->m_readStream , &socket->m_writeStream );
+ if ((socket->m_readStream == NULL) || (socket->m_writeStream == NULL))
{
GSocket_close(socket);
socket->m_error = GSOCK_IOERR;
return GSOCK_IOERR;
}
-
+
if ( !CFReadStreamOpen( socket->m_readStream ) || !CFWriteStreamOpen( socket->m_writeStream ) )
{
GSocket_close(socket);
socket->m_error = GSOCK_IOERR;
return GSOCK_IOERR;
}
-
+
CFRunLoopSourceRef rls = CFSocketCreateRunLoopSource(alloc , socket->m_cfSocket , 0);
CFRunLoopAddSource(CFRunLoopGetCurrent() , rls, kCFRunLoopCommonModes);
CFRelease(rls);
-
+
CFDataRef address = CFDataCreateWithBytesNoCopy(alloc, (const UInt8*) socket->m_peer->m_addr, socket->m_peer->m_len , kCFAllocatorNull);
if ( !address )
return GSOCK_MEMERR ;
-
+
err = CFSocketConnectToAddress( socket->m_cfSocket , address, socket->m_non_blocking ? -1 : socket->m_timeout / 1000 ) ;
CFRelease(address);
-
+
if (err != kCFSocketSuccess)
{
if ( err == kCFSocketTimeout )
- {
+ {
GSocket_close(socket);
socket->m_error = GSOCK_TIMEDOUT ;
return GSOCK_TIMEDOUT ;
}
+
// we don't know whether a connect in progress will be issued like this
if ( err != kCFSocketTimeout && socket->m_non_blocking )
{
- socket->m_establishing = TRUE;
+ socket->m_establishing = true;
socket->m_error = GSOCK_WOULDBLOCK;
return GSOCK_WOULDBLOCK;
}
-
+
GSocket_close(socket);
socket->m_error = GSOCK_IOERR;
return GSOCK_IOERR;
/* Flags */
/* GSocket_SetNonBlocking:
- * Sets the socket to non-blocking mode. All IO calls will return
- * immediately.
+ * Sets the socket to non-blocking mode.
+ * All IO calls will return immediately.
*/
void GSocket_SetNonBlocking(GSocket *socket, int non_block)
{
- assert(socket != NULL);
+ assert( socket != NULL );
// GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block) );
socket->m_non_blocking = non_block;
}
-/* GSocket_SetTimeout:
+/*
+ * GSocket_SetTimeout:
* Sets the timeout for blocking calls. Time is expressed in
* milliseconds.
*/
void GSocket_SetTimeout(GSocket *socket, unsigned long millisec)
{
- assert(socket != NULL);
+ assert( socket != NULL );
socket->m_timeout = millisec;
}
*/
GSocketError GSocket_GetError(GSocket *socket)
{
- assert(socket != NULL);
+ assert( socket != NULL );
return socket->m_error;
}
* operation, there is still data available, the callback function will
* be called again.
* GSOCK_OUTPUT:
- * The socket is available for writing. That is, the next write call
+ * The socket is available for writing. That is, the next write call
* won't block. This event is generated only once, when the connection is
* first established, and then only if a call failed with GSOCK_WOULDBLOCK,
* when the output buffer empties again. This means that the app should
{
int count;
- assert(socket != NULL);
+ assert( socket != NULL );
for (count = 0; count < GSOCK_MAX_EVENT; count++)
{
switch (event)
{
case GSOCK_CONNECTION:
- if(socket->m_server)
+ if (socket->m_server)
c = kCFSocketReadCallBack;
else
c = kCFSocketConnectCallBack;
break;
+
case GSOCK_LOST:
case GSOCK_INPUT:
c = kCFSocketReadCallBack;
break;
+
case GSOCK_OUTPUT:
c = kCFSocketWriteCallBack;
break;
+
default:
c = 0;
}
+
CFSocketEnableCallBacks(socket->m_cfSocket, c);
}
switch (event)
{
case GSOCK_CONNECTION:
- if(socket->m_server)
+ if (socket->m_server)
c = kCFSocketReadCallBack;
else
c = kCFSocketConnectCallBack;
break;
+
case GSOCK_LOST:
case GSOCK_INPUT:
c = kCFSocketReadCallBack;
break;
+
case GSOCK_OUTPUT:
c = kCFSocketWriteCallBack;
break;
+
default:
c = 0;
+ break;
}
+
CFSocketDisableCallBacks(socket->m_cfSocket, c);
}
CALL_CALLBACK( socket , GSOCK_CONNECTION ) ;
}
break;
+
case kCFSocketReadCallBack:
CALL_CALLBACK( socket , GSOCK_INPUT ) ;
break;
+
case kCFSocketWriteCallBack:
CALL_CALLBACK( socket , GSOCK_OUTPUT ) ;
break;
+
default:
- break; /* We shouldn't get here. */
+ break; // We shouldn't get here.
}
}
}
int GSocket_Write(GSocket *socket, const char *buffer, int size)
-{
+{
int ret;
assert(socket != NULL);
ret = CFWriteStreamWrite( socket->m_writeStream , (UInt8*) buffer , size ) ;
+
return ret;
}
GSocketEventFlags GSocket_Select(GSocket *socket, GSocketEventFlags flags)
{
- assert(socket != NULL);
+ assert( socket != NULL );
+
return flags & socket->m_detected;
}
virtual bool OnInit()
{
// wxSocketBase will call GSocket_Init() itself when/if needed
- return TRUE;
+ return true;
}
virtual void OnExit()
#endif
// wxUSE_SOCKETS
-
+
/////////////////////////////////////////////////////////////////////////////
-// Name: checkbox.cpp
+// Name: src/mac/carbon/checkbox.cpp
// Purpose: wxCheckBox
// Author: Stefan Csomor
// Modified by:
switch (origState)
{
- case wxCHK_UNCHECKED:
+ case wxCHK_UNCHECKED:
newState = wxCHK_CHECKED;
break;
- case wxCHK_CHECKED:
+ case wxCHK_CHECKED:
// If the style flag to allow the user setting the undetermined state is set,
// then set the state to undetermined; otherwise set state to unchecked.
newState = Is3rdStateAllowedForUser() ? wxCHK_UNDETERMINED : wxCHK_UNCHECKED;
break;
- case wxCHK_UNDETERMINED:
+ case wxCHK_UNDETERMINED:
newState = wxCHK_UNCHECKED;
break;
- default:
+ default:
break;
}
/////////////////////////////////////////////////////////////////////////////
-// Name: cursor.cpp
+// Name: src/mac/carbon/cursor.cpp
// Purpose: wxCursor class
// Author: Stefan Csomor
// Modified by:
#include "wx/mac/private.h"
+
IMPLEMENT_DYNAMIC_CLASS(wxCursor, wxBitmap)
+
class WXDLLEXPORT wxCursorRefData: public wxBitmapRefData
{
DECLARE_NO_COPY_CLASS(wxCursorRefData)
-
+
friend class WXDLLEXPORT wxBitmap;
friend class WXDLLEXPORT wxCursor;
+
public:
wxCursorRefData();
~wxCursorRefData();
WXHCURSOR m_hCursor;
bool m_disposeHandle;
bool m_releaseHandle;
- bool m_isColorCursor ;
- long m_themeCursor ;
+ bool m_isColorCursor;
+ long m_themeCursor;
};
#define M_CURSORDATA ((wxCursorRefData *)m_refData)
#define M_CURSORHANDLERDATA ((wxCursorRefData *)bitmap->m_refData)
-const short kwxCursorBullseye = 0 ;
-const short kwxCursorBlank = 1 ;
-const short kwxCursorPencil = 2 ;
-const short kwxCursorMagnifier = 3 ;
-const short kwxCursorNoEntry = 4 ;
-const short kwxCursorPaintBrush = 5 ;
-const short kwxCursorPointRight = 6 ;
-const short kwxCursorPointLeft = 7 ;
-const short kwxCursorQuestionArrow = 8 ;
-const short kwxCursorRightArrow = 9 ;
-const short kwxCursorSizeNS = 10 ;
-const short kwxCursorSize = 11 ;
-const short kwxCursorSizeNESW = 12 ;
-const short kwxCursorSizeNWSE = 13 ;
-const short kwxCursorRoller = 14 ;
-const short kwxCursorLast = kwxCursorRoller ;
+const short kwxCursorBullseye = 0;
+const short kwxCursorBlank = 1;
+const short kwxCursorPencil = 2;
+const short kwxCursorMagnifier = 3;
+const short kwxCursorNoEntry = 4;
+const short kwxCursorPaintBrush = 5;
+const short kwxCursorPointRight = 6;
+const short kwxCursorPointLeft = 7;
+const short kwxCursorQuestionArrow = 8;
+const short kwxCursorRightArrow = 9;
+const short kwxCursorSizeNS = 10;
+const short kwxCursorSize = 11;
+const short kwxCursorSizeNESW = 12;
+const short kwxCursorSizeNWSE = 13;
+const short kwxCursorRoller = 14;
+const short kwxCursorLast = kwxCursorRoller;
Cursor gMacCursors[kwxCursorLast+1] =
{
{0x000A, 0x0006}
},
-} ;
+};
wxCursor gMacCurrentCursor ;
{
wxASSERT_MSG( number >= 0 && number <=kwxCursorLast , wxT("invalid stock cursor id") ) ;
CursHandle c = (CursHandle) NewHandle( sizeof(Cursor) ) ;
- memcpy( *c , &gMacCursors[number] , sizeof( Cursor ) ) ;
- return c ;
+ memcpy( *c, &gMacCursors[number], sizeof(Cursor) ) ;
+
+ return c ;
}
wxCursorRefData::wxCursorRefData()
{
- SetWidth( 16 );
+ SetWidth( 16 );
SetHeight( 16 );
- m_hCursor = NULL ;
- m_disposeHandle = false ;
- m_releaseHandle = false ;
- m_isColorCursor = false ;
- m_themeCursor = -1 ;
+ m_hCursor = NULL;
+ m_disposeHandle = false;
+ m_releaseHandle = false;
+ m_isColorCursor = false;
+ m_themeCursor = -1;
}
wxCursorRefData::~wxCursorRefData()
else if ( m_disposeHandle )
{
::DisposeHandle( (Handle ) m_hCursor ) ;
- }
+ }
else if ( m_releaseHandle )
{
// we don't release the resource since it may already
}
}
-// Cursors
wxCursor::wxCursor()
{
}
#endif
}
-wxCursor::wxCursor(const char **bits)
+wxCursor::wxCursor(const char **bits)
{
(void) CreateFromXpm(bits);
}
-wxCursor::wxCursor(char **bits)
+wxCursor::wxCursor(char **bits)
{
(void) CreateFromXpm((const char **)bits);
}
bool wxCursor::CreateFromXpm(const char **bits)
{
#if wxUSE_IMAGE
- wxCHECK_MSG( bits != NULL, FALSE, wxT("invalid cursor data") )
+ wxCHECK_MSG( bits != NULL, false, wxT("invalid cursor data") )
wxXPMDecoder decoder;
wxImage img = decoder.ReadData(bits);
- wxCHECK_MSG( img.Ok(), FALSE, wxT("invalid cursor data") )
- CreateFromImage( img ) ;
- return TRUE;
+ wxCHECK_MSG( img.Ok(), false, wxT("invalid cursor data") )
+ CreateFromImage( img ) ;
+ return true;
#else
- return FALSE;
+ return false;
#endif
}
-WXHCURSOR wxCursor::GetHCURSOR() const
-{
- return (M_CURSORDATA ? M_CURSORDATA->m_hCursor : 0);
+WXHCURSOR wxCursor::GetHCURSOR() const
+{
+ return (M_CURSORDATA ? M_CURSORDATA->m_hCursor : 0);
}
-bool wxCursor::Ok() const
-{
- return (m_refData != NULL && ( M_CURSORDATA->m_hCursor != NULL || M_CURSORDATA->m_themeCursor != -1 ) ) ;
+bool wxCursor::Ok() const
+{
+ return (m_refData != NULL && ( M_CURSORDATA->m_hCursor != NULL || M_CURSORDATA->m_themeCursor != -1 ) ) ;
}
short GetCTabIndex( CTabHandle colors , RGBColor *col )
{
short retval = 0 ;
unsigned long bestdiff = 0xFFFF ;
+
for ( int i = 0 ; i < (**colors).ctSize ; ++i )
{
unsigned long diff = abs(col->red - (**colors).ctTable[i].rgb.red ) +
abs(col->green - (**colors).ctTable[i].rgb.green ) +
abs(col->blue - (**colors).ctTable[i].rgb.blue ) ;
+
if ( diff < bestdiff )
{
bestdiff = diff ;
retval = (**colors).ctTable[i].value ;
}
}
+
return retval ;
}
#if wxUSE_IMAGE
-void wxCursor::CreateFromImage(const wxImage & image)
+void wxCursor::CreateFromImage(const wxImage & image)
{
m_refData = new wxCursorRefData;
wxASSERT_MSG( hotSpotX >= 0 && hotSpotX < image_w &&
hotSpotY >= 0 && hotSpotY < image_h,
- _T("invalid cursor hot spot coordinates") );
+ wxT("invalid cursor hot spot coordinates") );
wxImage image16(image); // final image of correct size
-
+
// if image is too small then place it in the center, resize it if too big
if ((w > image_w) && (h > image_h))
{
- wxPoint offset((w - image_w)/2, (h - image_h)/2);
+ wxPoint offset((w - image_w) / 2, (h - image_h) / 2);
hotSpotX = hotSpotX + offset.x;
hotSpotY = hotSpotY + offset.y;
-
+
image16 = image.Size(wxSize(w, h), offset);
}
else if ((w != image_w) || (h != image_h))
{
- hotSpotX = int(hotSpotX * double(w) / double(image_w));
- hotSpotY = int(hotSpotY * double(h) / double(image_h));
+ hotSpotX = int(hotSpotX * double(w) / double(image_w));
+ hotSpotY = int(hotSpotY * double(h) / double(image_h));
image16 = image.Scale(w, h);
}
unsigned char * rgbBits = image16.GetData();
bool bHasMask = image16.HasMask() ;
-
- PixMapHandle pm = (PixMapHandle) NewHandleClear( sizeof (PixMap)) ;
+ PixMapHandle pm = (PixMapHandle) NewHandleClear( sizeof(PixMap) ) ;
short extent = 16 ;
short bytesPerPixel = 1 ;
short depth = 8 ;
Rect bounds = { 0 , 0 , extent , extent } ;
- CCrsrHandle ch = (CCrsrHandle) NewHandleClear ( sizeof( CCrsr ) ) ;
+ CCrsrHandle ch = (CCrsrHandle) NewHandleClear( sizeof(CCrsr) ) ;
CTabHandle newColors = GetCTable( 8 ) ;
- HandToHand((Handle *) &newColors);
+ HandToHand( (Handle *) &newColors );
+
// set the values to the indices
for ( int i = 0 ; i < (**newColors).ctSize ; ++i )
{
(**newColors).ctTable[i].value = i ;
}
- HLock( (Handle) ch) ;
- (**ch).crsrType = 0x8001 ; // color cursors
- (**ch).crsrMap = pm ;
- short bytesPerRow = bytesPerPixel * extent ;
- (**pm).baseAddr = 0;
+ HLock( (Handle)ch );
+ (**ch).crsrType = 0x8001; // color cursors
+ (**ch).crsrMap = pm;
+ short bytesPerRow = bytesPerPixel * extent;
+
+ (**pm).baseAddr = 0;
(**pm).rowBytes = bytesPerRow | 0x8000;
- (**pm).bounds = bounds;
- (**pm).pmVersion = 0;
- (**pm).packType = 0;
- (**pm).packSize = 0;
- (**pm).hRes = 0x00480000; /* 72 DPI default res */
- (**pm).vRes = 0x00480000; /* 72 DPI default res */
+ (**pm).bounds = bounds;
+ (**pm).pmVersion = 0;
+ (**pm).packType = 0;
+ (**pm).packSize = 0;
+ (**pm).hRes = 0x00480000; // 72 DPI default res
+ (**pm).vRes = 0x00480000; // 72 DPI default res
(**pm).pixelSize = depth;
(**pm).pixelType = 0;
- (**pm).cmpCount = 1;
+ (**pm).cmpCount = 1;
(**pm).cmpSize = depth;
(**pm).pmTable = newColors;
- (**ch).crsrData = NewHandleClear( extent * bytesPerRow ) ;
+ (**ch).crsrData = NewHandleClear( extent * bytesPerRow ) ;
(**ch).crsrXData = NULL ;
(**ch).crsrXValid = 0;
(**ch).crsrXHandle = NULL;
(**ch).crsrHotSpot.h = hotSpotX ;
(**ch).crsrHotSpot.v = hotSpotY ;
- (**ch).crsrXTable = 0 ;
+ (**ch).crsrXTable = 0 ;
(**ch).crsrID = GetCTSeed() ;
-
+
memset( (**ch).crsr1Data , 0 , sizeof( Bits16 ) ) ;
memset( (**ch).crsrMask , 0 , sizeof( Bits16 ) ) ;
-
+
unsigned char mr = image16.GetMaskRed() ;
unsigned char mg = image16.GetMaskGreen() ;
unsigned char mb = image16.GetMaskBlue() ;
+
for ( int y = 0 ; y < h ; ++y )
{
- short rowbits = 0 ;
- short maskbits = 0 ;
-
+ short rowbits = 0, maskbits = 0 ;
+
for ( int x = 0 ; x < w ; ++x )
{
long pos = (y * w + x) * 3;
unsigned char r = rgbBits[pos] ;
- unsigned char g = rgbBits[pos+1] ;
- unsigned char b = rgbBits[pos+2] ;
- RGBColor col = { 0xFFFF ,0xFFFF, 0xFFFF } ;
-
- if ( bHasMask && r==mr && g==mg && b==mb )
+ unsigned char g = rgbBits[pos + 1] ;
+ unsigned char b = rgbBits[pos + 2] ;
+ RGBColor col = { 0xFFFF, 0xFFFF, 0xFFFF } ;
+
+ if ( bHasMask && r == mr && g == mg && b == mb )
{
// masked area, does not appear anywhere
}
else
{
if ( (int)r + (int)g + (int)b < 0x0200 )
- {
- rowbits |= ( 1 << (15-x) ) ;
- }
- maskbits |= ( 1 << (15-x) ) ;
-
+ rowbits |= ( 1 << (15 - x) ) ;
+
+ maskbits |= ( 1 << (15 - x) ) ;
+
col = *((RGBColor*) wxColor( r , g , b ).GetPixel()) ;
}
- *((*(**ch).crsrData) + y * bytesPerRow + x) =
+
+ *((*(**ch).crsrData) + y * bytesPerRow + x) =
GetCTabIndex( newColors , &col) ;
}
+
(**ch).crsr1Data[y] = rowbits ;
(**ch).crsrMask[y] = maskbits ;
}
+
if ( !bHasMask )
- {
memcpy( (**ch).crsrMask , (**ch).crsr1Data , sizeof( Bits16) ) ;
- }
-
- HUnlock((Handle) ch) ;
+
+ HUnlock( (Handle)ch ) ;
M_CURSORDATA->m_hCursor = ch ;
M_CURSORDATA->m_isColorCursor = true ;
}
if ( flags == wxBITMAP_TYPE_MACCURSOR_RESOURCE )
{
Str255 theName ;
- wxMacStringToPascal( cursor_file , theName ) ;
-
+ wxMacStringToPascal( cursor_file , theName ) ;
+
Handle resHandle = ::GetNamedResource( 'crsr' , theName ) ;
if ( resHandle )
{
short theId = -1 ;
OSType theType ;
+
GetResInfo( resHandle , &theId , &theType , theName ) ;
ReleaseResource( resHandle ) ;
+
M_CURSORDATA->m_hCursor = GetCCursor( theId ) ;
if ( M_CURSORDATA->m_hCursor )
M_CURSORDATA->m_isColorCursor = true ;
}
else
- {
+ {
Handle resHandle = ::GetNamedResource( 'CURS' , theName ) ;
if ( resHandle )
{
short theId = -1 ;
OSType theType ;
+
GetResInfo( resHandle , &theId , &theType , theName ) ;
ReleaseResource( resHandle ) ;
- M_CURSORDATA->m_hCursor = GetCursor( theId ) ;
+
+ M_CURSORDATA->m_hCursor = GetCursor( theId ) ;
if ( M_CURSORDATA->m_hCursor )
M_CURSORDATA->m_releaseHandle = true ;
}
{
#if wxUSE_IMAGE
wxImage image ;
- image.LoadFile( cursor_file , flags ) ;
- if( image.Ok() )
+ image.LoadFile( cursor_file, flags ) ;
+ if ( image.Ok() )
{
- image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X,hotSpotX ) ;
- image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y,hotSpotY ) ;
+ image.SetOption( wxIMAGE_OPTION_CUR_HOTSPOT_X, hotSpotX ) ;
+ image.SetOption( wxIMAGE_OPTION_CUR_HOTSPOT_Y, hotSpotY ) ;
delete m_refData ;
- CreateFromImage(image) ;
+ CreateFromImage( image ) ;
}
#endif
}
wxCursor::wxCursor(int cursor_type)
{
m_refData = new wxCursorRefData;
-
+
switch (cursor_type)
{
case wxCURSOR_COPY_ARROW:
- M_CURSORDATA->m_themeCursor = kThemeCopyArrowCursor ;
+ M_CURSORDATA->m_themeCursor = kThemeCopyArrowCursor;
break;
+
case wxCURSOR_WAIT:
- M_CURSORDATA->m_themeCursor = kThemeWatchCursor ;
+ M_CURSORDATA->m_themeCursor = kThemeWatchCursor;
break;
+
case wxCURSOR_IBEAM:
- M_CURSORDATA->m_themeCursor = kThemeIBeamCursor ;
+ M_CURSORDATA->m_themeCursor = kThemeIBeamCursor;
break;
+
case wxCURSOR_CROSS:
M_CURSORDATA->m_themeCursor = kThemeCrossCursor;
break;
+
case wxCURSOR_SIZENWSE:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNWSE);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNWSE);
break;
+
case wxCURSOR_SIZENESW:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNESW);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNESW);
break;
+
case wxCURSOR_SIZEWE:
- {
- M_CURSORDATA->m_themeCursor = kThemeResizeLeftRightCursor;
- }
+ M_CURSORDATA->m_themeCursor = kThemeResizeLeftRightCursor;
break;
+
case wxCURSOR_SIZENS:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNS);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSizeNS);
break;
+
case wxCURSOR_SIZING:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSize);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorSize);
break;
+
case wxCURSOR_HAND:
- {
- M_CURSORDATA->m_themeCursor = kThemePointingHandCursor;
- }
+ M_CURSORDATA->m_themeCursor = kThemePointingHandCursor;
break;
+
case wxCURSOR_BULLSEYE:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorBullseye);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorBullseye);
break;
+
case wxCURSOR_PENCIL:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPencil);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPencil);
break;
+
case wxCURSOR_MAGNIFIER:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorMagnifier);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorMagnifier);
break;
+
case wxCURSOR_NO_ENTRY:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorNoEntry);
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorNoEntry);
break;
+
case wxCURSOR_WATCH:
- {
- M_CURSORDATA->m_themeCursor = kThemeWatchCursor;
- break;
- }
+ M_CURSORDATA->m_themeCursor = kThemeWatchCursor;
+ break;
+
case wxCURSOR_PAINT_BRUSH:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPaintBrush);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPaintBrush);
+ break;
+
case wxCURSOR_POINT_LEFT:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPointLeft);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPointLeft);
+ break;
+
case wxCURSOR_POINT_RIGHT:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPointRight);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorPointRight);
+ break;
+
case wxCURSOR_QUESTION_ARROW:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorQuestionArrow);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorQuestionArrow);
+ break;
+
case wxCURSOR_BLANK:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorBlank);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorBlank);
+ break;
+
case wxCURSOR_RIGHT_ARROW:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorRightArrow);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorRightArrow);
+ break;
+
case wxCURSOR_SPRAYCAN:
- {
- M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorRoller);
- break;
- }
+ M_CURSORDATA->m_hCursor = wxGetStockCursor(kwxCursorRoller);
+ break;
+
case wxCURSOR_CHAR:
case wxCURSOR_ARROW:
case wxCURSOR_LEFT_BUTTON:
case wxCURSOR_RIGHT_BUTTON:
case wxCURSOR_MIDDLE_BUTTON:
default:
- M_CURSORDATA->m_themeCursor = kThemeArrowCursor ;
+ M_CURSORDATA->m_themeCursor = kThemeArrowCursor;
break;
}
+
if ( M_CURSORDATA->m_themeCursor == -1 )
- M_CURSORDATA->m_releaseHandle = true ;
+ M_CURSORDATA->m_releaseHandle = true;
}
-void wxCursor::MacInstall() const
+void wxCursor::MacInstall() const
{
gMacCurrentCursor = *this ;
if ( m_refData && M_CURSORDATA->m_themeCursor != -1 )
{
cursor.MacInstall() ;
}
-
-
#include "wx/tokenzr.h"
#include "wx/filename.h"
-#ifndef __DARWIN__
- #include "PLStringFuncs.h"
-#endif
-
-IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
-
-// begin wxmac
-
#include "wx/mac/private.h"
#ifndef __DARWIN__
-#include <Navigation.h>
+ #include <Navigation.h>
+ #include "PLStringFuncs.h"
#endif
#include "MoreFilesX.h"
-extern bool gUseNavServices ;
+IMPLEMENT_CLASS(wxFileDialog, wxFileDialogBase)
+
+extern bool gUseNavServices;
// the data we need to pass to our standard file hook routine
// includes a pointer to the dialog, a pointer to the standard
// and a copy of the "previous" file spec of the reply record
// so we can see if the selection has changed
-struct OpenUserDataRec {
+struct OpenUserDataRec
+{
int currentfilter ;
bool saveMode ;
wxArrayString name ;
typedef struct OpenUserDataRec
OpenUserDataRec, *OpenUserDataRecPtr;
-static pascal void NavEventProc(
- NavEventCallbackMessage inSelector,
- NavCBRecPtr ioParams,
- NavCallBackUserData ioUserData);
+static pascal void NavEventProc(
+ NavEventCallbackMessage inSelector,
+ NavCBRecPtr ioParams,
+ NavCallBackUserData ioUserData );
-static NavEventUPP sStandardNavEventFilter = NewNavEventUPP(NavEventProc);
+static NavEventUPP sStandardNavEventFilter = NewNavEventUPP(NavEventProc);
-static pascal void
-NavEventProc(
- NavEventCallbackMessage inSelector,
- NavCBRecPtr ioParams,
- NavCallBackUserData ioUserData )
+static pascal void NavEventProc(
+ NavEventCallbackMessage inSelector,
+ NavCBRecPtr ioParams,
+ NavCallBackUserData ioUserData )
{
OpenUserDataRec * data = ( OpenUserDataRec *) ioUserData ;
- if (inSelector == kNavCBEvent) {
+ if (inSelector == kNavCBEvent)
+ {
}
else if ( inSelector == kNavCBStart )
{
// Apple Technical Q&A 1151
FSSpec theFSSpec;
wxMacFilename2FSSpec(data->defaultLocation, &theFSSpec);
- AEDesc theLocation = {typeNull, NULL};
+ AEDesc theLocation = { typeNull, NULL };
if (noErr == ::AECreateDesc(typeFSS, &theFSSpec, sizeof(FSSpec), &theLocation))
::NavCustomControl(ioParams->context, kNavCtlSetLocation, (void *) &theLocation);
}
}
}
-
-void MakeUserDataRec(OpenUserDataRec *myData , const wxString& filter )
+void MakeUserDataRec(OpenUserDataRec *myData , const wxString& filter )
{
myData->menuitems = NULL ;
myData->currentfilter = 0 ;
int filterIndex = 0;
bool isName = true ;
wxString current ;
- for( unsigned int i = 0; i < filter2.Len() ; i++ )
+
+ for ( unsigned int i = 0; i < filter2.Len() ; i++ )
{
- if( filter2.GetChar(i) == wxT('|') )
+ if ( filter2.GetChar(i) == wxT('|') )
{
- if( isName ) {
+ if ( isName )
+ {
myData->name.Add( current ) ;
}
- else {
+ else
+ {
myData->extensions.Add( current.MakeUpper() ) ;
++filterIndex ;
}
+
isName = !isName ;
current = wxEmptyString ;
}
const size_t extCount = myData->extensions.GetCount();
for ( size_t i = 0 ; i < extCount; i++ )
{
- wxUint32 fileType;
- wxUint32 creator;
+ wxUint32 fileType, creator;
wxString extension = myData->extensions[i];
+ // Remove leading '*'
if (extension.GetChar(0) == '*')
- extension = extension.Mid(1); // Remove leading *
+ extension = extension.Mid( 1 );
+ // Remove leading '.'
if (extension.GetChar(0) == '.')
- {
- extension = extension.Mid(1); // Remove leading .
- }
+ extension = extension.Mid( 1 );
if (wxFileName::MacFindDefaultTypeAndCreator( extension, &fileType, &creator ))
- {
myData->filtermactypes.Add( (OSType)fileType );
- }
else
- {
- myData->filtermactypes.Add( '****' ) ; // We'll fail safe if it's not recognized
- }
+ myData->filtermactypes.Add( '****' ); // We'll fail safe if it's not recognized
}
}
}
return true ;
wxStringTokenizer tokenizer( data->extensions[i] , wxT(";") ) ;
- while( tokenizer.HasMoreTokens() )
+ while ( tokenizer.HasMoreTokens() )
{
wxString extension = tokenizer.GetNextToken() ;
if ( extension.GetChar(0) == '*' )
return true ;
}
}
+
return false ;
}
+
return true ;
}
// end wxmac
-wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
- const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
- long style, const wxPoint& pos)
- :wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos)
+wxFileDialog::wxFileDialog(
+ wxWindow *parent, const wxString& message,
+ const wxString& defaultDir, const wxString& defaultFileName, const wxString& wildCard,
+ long style, const wxPoint& pos)
+ : wxFileDialogBase(parent, message, defaultDir, defaultFileName, wildCard, style, pos)
{
wxASSERT_MSG( NavServicesAvailable() , wxT("Navigation Services are not running") ) ;
}
-pascal Boolean CrossPlatformFilterCallback (
+pascal Boolean CrossPlatformFilterCallback(
AEDesc *theItem,
void *info,
void *callBackUD,
- NavFilterModes filterMode
-)
+ NavFilterModes filterMode )
{
bool display = true;
OpenUserDataRecPtr data = (OpenUserDataRecPtr) callBackUD ;
NavFileOrFolderInfo* theInfo = (NavFileOrFolderInfo*) info ;
if ( !theInfo->isFolder )
{
- if (theItem->descriptorType == typeFSS )
+ if (theItem->descriptorType == typeFSS)
{
FSSpec spec;
memcpy( &spec , *theItem->dataHandle , sizeof(FSSpec) ) ;
{
OSErr err;
NavDialogCreationOptions dialogCreateOptions;
+
// set default options
::NavGetDefaultDialogCreationOptions(&dialogCreateOptions);
{
myData.saveMode = true;
- if (!numFilters)
- {
- dialogCreateOptions.optionFlags |= kNavNoTypePopup;
- }
dialogCreateOptions.optionFlags |= kNavDontAutoTranslate;
dialogCreateOptions.optionFlags |= kNavDontAddTranslateItems;
+ if (!numFilters)
+ dialogCreateOptions.optionFlags |= kNavNoTypePopup;
// The extension is important
if (numFilters < 2)
#if TARGET_API_MAC_OSX
if (!(m_dialogStyle & wxOVERWRITE_PROMPT))
- {
- dialogCreateOptions.optionFlags |= kNavDontConfirmReplacement;
- }
+ dialogCreateOptions.optionFlags |= kNavDontConfirmReplacement;
#endif
- err = ::NavCreatePutFileDialog(&dialogCreateOptions,
- // Suppresses the 'Default' (top) menu item
- kNavGenericSignature, kNavGenericSignature,
- sStandardNavEventFilter,
- &myData, // for defaultLocation
- &dialog);
+
+ err = ::NavCreatePutFileDialog(
+ &dialogCreateOptions,
+ kNavGenericSignature, // Suppresses the 'Default' (top) menu item
+ kNavGenericSignature,
+ sStandardNavEventFilter,
+ &myData, // for defaultLocation
+ &dialog );
}
else
{
-
- //let people select bundles/programs in dialogs
+ // let the user select bundles/programs in dialogs
dialogCreateOptions.optionFlags |= kNavSupportPackages;
navFilterUPP = NewNavObjectFilterUPP(CrossPlatformFilterCallback);
- err = ::NavCreateGetFileDialog(&dialogCreateOptions,
- NULL, // NavTypeListHandle
- sStandardNavEventFilter,
- NULL, // NavPreviewUPP
- navFilterUPP,
- (void *) &myData, // inClientData
- &dialog);
+ err = ::NavCreateGetFileDialog(
+ &dialogCreateOptions,
+ NULL, // NavTypeListHandle
+ sStandardNavEventFilter,
+ NULL, // NavPreviewUPP
+ navFilterUPP,
+ (void *) &myData, // inClientData
+ &dialog );
}
if (err == noErr)
Size actualSize;
FSRef theFSRef;
wxString thePath ;
-
- m_filterIndex = myData.currentfilter ;
-
long count;
- ::AECountItems(&navReply.selection , &count);
+
+ m_filterIndex = myData.currentfilter;
+ ::AECountItems( &navReply.selection, &count );
for (long i = 1; i <= count; ++i)
{
- err = ::AEGetNthPtr(&(navReply.selection), i, typeFSRef, &theKeyword, &actualType,
- &theFSRef, sizeof(theFSRef), &actualSize);
+ err = ::AEGetNthPtr(
+ &(navReply.selection), i, typeFSRef, &theKeyword, &actualType,
+ &theFSRef, sizeof(theFSRef), &actualSize );
if (err != noErr)
break;
if (m_dialogStyle & wxSAVE)
- thePath = wxMacFSRefToPath( &theFSRef , navReply.saveFileName ) ;
+ thePath = wxMacFSRefToPath( &theFSRef, navReply.saveFileName );
else
- thePath = wxMacFSRefToPath( &theFSRef ) ;
+ thePath = wxMacFSRefToPath( &theFSRef );
if (!thePath)
{
::NavDisposeReply(&navReply);
return wxID_CANCEL;
}
+
m_path = thePath;
m_paths.Add(m_path);
m_fileName = wxFileNameFromPath(m_path);
m_fileNames.Add(m_fileName);
}
+
// set these to the first hit
m_path = m_paths[0];
m_fileName = wxFileNameFromPath(m_path);
m_dir = wxPathOnly(m_path);
}
+
::NavDisposeReply(&navReply);
return (err == noErr) ? wxID_OK : wxID_CANCEL;
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
-// ============================================================================
-// declarations
-// ============================================================================
-
-// ----------------------------------------------------------------------------
-// headers
-// ----------------------------------------------------------------------------
-
-// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#include "wx/string.h"
#include "wx/log.h"
#include "wx/intl.h"
-#endif //WX_PRECOMP
+#endif
#include "wx/fontutil.h"
#include "wx/fontmap.h"
#include "wx/encinfo.h"
-
#include "wx/tokenzr.h"
-// ============================================================================
-// implementation
-// ============================================================================
-
-// ----------------------------------------------------------------------------
-// wxNativeEncodingInfo
-// ----------------------------------------------------------------------------
-
-// convert to/from the string representation: format is
-// facename[;charset]
-bool wxNativeEncodingInfo::FromString(const wxString& s)
+// convert to/from the string representation:
+// format is facename[;charset]
+//
+bool wxNativeEncodingInfo::FromString( const wxString& s )
{
- wxStringTokenizer tokenizer(s, _T(";"));
+ wxStringTokenizer tokenizer(s, wxT(";"));
facename = tokenizer.GetNextToken();
if ( !facename )
- return FALSE;
+ return false;
wxString tmp = tokenizer.GetNextToken();
if ( !tmp )
}
else
{
- if ( wxSscanf(tmp, _T("%u"), &charset) != 1 )
- {
+ if ( wxSscanf( tmp, wxT("%u"), &charset ) != 1 )
// should be a number!
- return FALSE;
- }
+ return false;
}
- return TRUE;
+ return true;
}
wxString wxNativeEncodingInfo::ToString() const
{
wxString s(facename);
if ( charset != 0 )
- {
- s << _T(';') << charset;
- }
+ s << wxT(';') << charset;
return s;
}
// helper functions
// ----------------------------------------------------------------------------
-bool wxGetNativeFontEncoding(wxFontEncoding encoding,
- wxNativeEncodingInfo *info)
+bool wxGetNativeFontEncoding( wxFontEncoding encoding, wxNativeEncodingInfo *info )
{
- wxCHECK_MSG( info, FALSE, _T("bad pointer in wxGetNativeFontEncoding") );
+ wxCHECK_MSG( info, false, wxT("bad pointer in wxGetNativeFontEncoding") );
if ( encoding == wxFONTENCODING_DEFAULT )
- {
encoding = wxFont::GetDefaultEncoding();
- }
- info->encoding = encoding ;
+ info->encoding = encoding;
- return TRUE;
+ return true;
}
-bool wxTestFontEncoding(const wxNativeEncodingInfo& info)
+bool wxTestFontEncoding( const wxNativeEncodingInfo& info )
{
- // basically we should be able to support every encoding via the OS
- return true ;
+ // basically we should be able to support every encoding via the OS
+ return true;
}
-
-
/////////////////////////////////////////////////////////////////////////////
-// Name: thread.cpp
-// Purpose: wxThread Implementation
-// Author: Original from Wolfram Gloger/Guilhem Lavaux/Vadim Zeitlin
+// Name: src/mac/carbon/thread.cpp
+// Purpose: wxThread Implementation
+// Author: Original from Wolfram Gloger/Guilhem Lavaux/Vadim Zeitlin
// Modified by: Aj Lavin, Stefan Csomor
-// Created: 04/22/98
-// RCS-ID: $Id$
-// Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
-// Vadim Zeitlin (1999) , Stefan Csomor (2000)
-// Licence: wxWindows licence
+// Created: 04/22/98
+// RCS-ID: $Id$
+// Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
+// Vadim Zeitlin (1999), Stefan Csomor (2000)
+// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
-// ----------------------------------------------------------------------------
-// headers
-// ----------------------------------------------------------------------------
-
-// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if defined(__BORLANDC__)
#ifdef __WXMAC__
#ifdef __DARWIN__
-#include <CoreServices/CoreServices.h>
+ #include <CoreServices/CoreServices.h>
#else
-#include <DriverServices.h>
-#include <Multiprocessing.h>
-#include "wx/math.h"
+ #include <DriverServices.h>
+ #include <Multiprocessing.h>
+ #include "wx/math.h"
#endif
+
#include "wx/mac/uma.h"
#endif
#include "wx/mac/macnotfy.h"
-// ----------------------------------------------------------------------------
-// constants
-// ----------------------------------------------------------------------------
-// the possible states of the thread ("=>" shows all possible transitions from
-// this state)
+// the possible states of the thread:
+// ("=>" shows all possible transitions from this state)
enum wxThreadState
{
- STATE_NEW, // didn't start execution yet (=> RUNNING)
- STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
- STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
- STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
- STATE_EXITED // thread is terminating
+ STATE_NEW, // didn't start execution yet (=> RUNNING)
+ STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
+ STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
+ STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
+ STATE_EXITED // thread is terminating
};
// ----------------------------------------------------------------------------
-// this module globals
+// globals
// ----------------------------------------------------------------------------
-
// the task ID of the main thread
static wxThreadIdType gs_idMainThread = kInvalidID;
// this is the Per-Task Storage for the pointer to the appropriate wxThread
-TaskStorageIndex gs_tlsForWXThread = 0 ;
+TaskStorageIndex gs_tlsForWXThread = 0;
// if it's false, some secondary thread is holding the GUI lock
static bool gs_bGuiOwnedByMainThread = true;
// number of threads waiting for GUI in wxMutexGuiEnter()
static size_t gs_nWaitingForGui = 0;
-// overall number of threads, needed for determining the sleep value of the main
-// event loop
+// overall number of threads, needed for determining
+// the sleep value of the main event loop
size_t g_numberOfThreads = 0;
-
#if wxUSE_GUI
-
MPCriticalRegionID gs_guiCritical = kInvalidID;
-
#endif
// ============================================================================
/*
Notes :
-
+
The implementation is very close to the phtreads implementation, the reason for
using MPServices is the fact that these are also available under OS 9. Thus allowing
for one common API for all current builds.
-
+
As soon as wxThreads are on a 64 bit address space, the TLS must be extended
to use two indices one for each 32 bit part as the MP implementation is limited
to longs.
-
+
I have three implementations for mutexes :
- version A based on a binary semaphore, problem - not reentrant, version B based
+ version A based on a binary semaphore, problem - not reentrant, version B based
on a critical region, allows for reentrancy, performance implications not
yet tested, and third a plain pthreads implementation
The same for condition internal, one implementation by Aj Lavin and the other one
copied from the thrimpl.cpp which I assume has been more broadly tested, I've just
- replaced the interlock increment with the appropriate PPC calls
+ replaced the interlock increment with the appropriate PPC calls
*/
// ----------------------------------------------------------------------------
wxCriticalSection::wxCriticalSection()
{
- MPCreateCriticalRegion( (MPCriticalRegionID*) &m_critRegion ) ;
+ MPCreateCriticalRegion( (MPCriticalRegionID*) &m_critRegion );
}
wxCriticalSection::~wxCriticalSection()
{
- MPDeleteCriticalRegion( (MPCriticalRegionID) m_critRegion ) ;
+ MPDeleteCriticalRegion( (MPCriticalRegionID) m_critRegion );
}
void wxCriticalSection::Enter()
{
- MPEnterCriticalRegion( (MPCriticalRegionID) m_critRegion , kDurationForever ) ;
-}
+ MPEnterCriticalRegion( (MPCriticalRegionID) m_critRegion, kDurationForever );
+}
void wxCriticalSection::Leave()
{
- MPExitCriticalRegion((MPCriticalRegionID) m_critRegion ) ;
+ MPExitCriticalRegion( (MPCriticalRegionID) m_critRegion );
}
// ----------------------------------------------------------------------------
#define wxUSE_MAC_PTHREADS_MUTEX 0
#endif
-#if wxUSE_MAC_PTHREADS_MUTEX
+#if wxUSE_MAC_PTHREADS_MUTEX
#include <pthread.h>
+
class wxMutexInternal
{
public:
- wxMutexInternal(wxMutexType mutexType);
+ wxMutexInternal( wxMutexType mutexType );
~wxMutexInternal();
wxMutexError Lock();
wxMutexError TryLock();
wxMutexError Unlock();
- bool IsOk() const { return m_isOk; }
+ bool IsOk() const
+ { return m_isOk; }
private:
pthread_mutex_t m_mutex;
#ifdef HAVE_PTHREAD_MUTEXATTR_T
// on some systems pthread_mutexattr_settype() is not in the headers (but it is
// in the library, otherwise we wouldn't compile this code at all)
-extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t *, int);
+extern "C" int pthread_mutexattr_settype( pthread_mutexattr_t *, int );
#endif
-wxMutexInternal::wxMutexInternal(wxMutexType mutexType)
+wxMutexInternal::wxMutexInternal( wxMutexType mutexType )
{
int err;
switch ( mutexType )
#ifdef HAVE_PTHREAD_MUTEXATTR_T
{
pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+ pthread_mutexattr_init( &attr );
+ pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE );
- err = pthread_mutex_init(&m_mutex, &attr);
+ err = pthread_mutex_init( &m_mutex, &attr );
}
#elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
// we can use this only as initializer so we have to assign it
break;
default:
- wxFAIL_MSG( _T("unknown mutex type") );
+ wxFAIL_MSG( wxT("unknown mutex type") );
// fall through
case wxMUTEX_DEFAULT:
- err = pthread_mutex_init(&m_mutex, NULL);
+ err = pthread_mutex_init( &m_mutex, NULL );
break;
}
m_isOk = err == 0;
if ( !m_isOk )
{
- wxLogApiError( wxT("pthread_mutex_init()"), err);
+ wxLogApiError( wxT("pthread_mutex_init()"), err );
}
}
{
if ( m_isOk )
{
- int err = pthread_mutex_destroy(&m_mutex);
+ int err = pthread_mutex_destroy( &m_mutex );
if ( err != 0 )
{
- wxLogApiError( wxT("pthread_mutex_destroy()"), err);
+ wxLogApiError( wxT("pthread_mutex_destroy()"), err );
}
}
}
wxMutexError wxMutexInternal::Lock()
{
- int err = pthread_mutex_lock(&m_mutex);
+ int err = pthread_mutex_lock( &m_mutex );
switch ( err )
{
case EDEADLK:
// only error checking mutexes return this value and so it's an
// unexpected situation -- hence use assert, not wxLogDebug
- wxFAIL_MSG( _T("mutex deadlock prevented") );
+ wxFAIL_MSG( wxT("mutex deadlock prevented") );
return wxMUTEX_DEAD_LOCK;
case EINVAL:
- wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
+ wxLogDebug( wxT("pthread_mutex_lock(): mutex not initialized.") );
break;
case 0:
return wxMUTEX_NO_ERROR;
default:
- wxLogApiError(_T("pthread_mutex_lock()"), err);
+ wxLogApiError( wxT("pthread_mutex_lock()"), err );
}
return wxMUTEX_MISC_ERROR;
wxMutexError wxMutexInternal::TryLock()
{
- int err = pthread_mutex_trylock(&m_mutex);
+ int err = pthread_mutex_trylock( &m_mutex );
switch ( err )
{
case EBUSY:
- // not an error: mutex is already locked, but we're prepared for
- // this
+ // not an error: mutex is already locked, but we're prepared for this case
return wxMUTEX_BUSY;
case EINVAL:
- wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
+ wxLogDebug( wxT("pthread_mutex_trylock(): mutex not initialized.") );
break;
case 0:
return wxMUTEX_NO_ERROR;
default:
- wxLogApiError(_T("pthread_mutex_trylock()"), err);
+ wxLogApiError( wxT("pthread_mutex_trylock()"), err );
}
return wxMUTEX_MISC_ERROR;
wxMutexError wxMutexInternal::Unlock()
{
- int err = pthread_mutex_unlock(&m_mutex);
+ int err = pthread_mutex_unlock( &m_mutex );
switch ( err )
{
case EPERM:
return wxMUTEX_UNLOCKED;
case EINVAL:
- wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
+ wxLogDebug( wxT("pthread_mutex_unlock(): mutex not initialized.") );
break;
case 0:
return wxMUTEX_NO_ERROR;
default:
- wxLogApiError(_T("pthread_mutex_unlock()"), err);
+ wxLogApiError( wxT("pthread_mutex_unlock()"), err );
}
return wxMUTEX_MISC_ERROR;
}
-
#endif
-#if wxUSE_MAC_SEMAPHORE_MUTEX
+#if wxUSE_MAC_SEMAPHORE_MUTEX
class wxMutexInternal
{
public:
- wxMutexInternal(wxMutexType mutexType) ;
- ~wxMutexInternal() ;
- bool IsOk() const { return m_isOk; }
-
- wxMutexError Lock() ;
- wxMutexError TryLock() ;
- wxMutexError Unlock();
-private:
+ wxMutexInternal( wxMutexType mutexType );
+ virtual ~wxMutexInternal();
+
+ bool IsOk() const
+ { return m_isOk; }
+
+ wxMutexError Lock();
+ wxMutexError TryLock();
+ wxMutexError Unlock();
+
+private:
MPSemaphoreID m_semaphore;
- bool m_isOk ;
+ bool m_isOk;
};
wxMutexInternal::wxMutexInternal(wxMutexType mutexType )
{
- m_isOk = false ;
- m_semaphore = kInvalidID ;
-
- OSStatus err = noErr ;
- switch( mutexType )
+ m_isOk = false;
+ m_semaphore = kInvalidID;
+ OSStatus err = noErr;
+
+ switch ( mutexType )
{
case wxMUTEX_DEFAULT :
- {
- verify_noerr( MPCreateBinarySemaphore( & m_semaphore) );
- m_isOk = ( m_semaphore != kInvalidID ) ;
- }
- break ;
+ verify_noerr( MPCreateBinarySemaphore( &m_semaphore ) );
+ m_isOk = ( m_semaphore != kInvalidID );
+ break;
+
case wxMUTEX_RECURSIVE :
- wxFAIL_MSG(wxT("Recursive Mutex not supported yet") ) ;
- break ;
+ wxFAIL_MSG( wxT("Recursive Mutex not supported yet") );
+ break;
+
default :
- wxFAIL_MSG(wxT("Unknown mutex type") ) ;
- break ;
+ wxFAIL_MSG( wxT("Unknown mutex type") );
+ break;
}
}
wxMutexInternal::~wxMutexInternal()
{
if ( m_semaphore != kInvalidID )
- MPDeleteSemaphore( m_semaphore);
- MPYield() ;
+ MPDeleteSemaphore( m_semaphore );
+
+ MPYield();
}
wxMutexError wxMutexInternal::Lock()
{
- wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPWaitOnSemaphore( m_semaphore, kDurationForever);
- if ( err)
+ wxCHECK_MSG( m_isOk, wxMUTEX_MISC_ERROR, wxT("Invalid Mutex") );
+ OSStatus err = MPWaitOnSemaphore( m_semaphore, kDurationForever );
+ if (err != noErr)
{
- wxLogSysError(wxT("Could not lock mutex"));
- return wxMUTEX_MISC_ERROR;
+ wxLogSysError( wxT("Could not lock mutex") );
+
+ return wxMUTEX_MISC_ERROR;
}
-
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
wxMutexError wxMutexInternal::TryLock()
{
- wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPWaitOnSemaphore( m_semaphore, kDurationImmediate);
- if ( err)
+ wxCHECK_MSG( m_isOk, wxMUTEX_MISC_ERROR, wxT("Invalid Mutex") );
+ OSStatus err = MPWaitOnSemaphore( m_semaphore, kDurationImmediate );
+ if (err != noErr)
{
- if ( err == kMPTimeoutErr)
- {
- return wxMUTEX_BUSY;
- }
- wxLogSysError(wxT("Could not try lock mutex"));
- return wxMUTEX_MISC_ERROR;
+ if (err == kMPTimeoutErr)
+ return wxMUTEX_BUSY;
+
+ wxLogSysError( wxT("Could not try lock mutex") );
+
+ return wxMUTEX_MISC_ERROR;
}
-
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
wxMutexError wxMutexInternal::Unlock()
{
- wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPSignalSemaphore( m_semaphore);
- MPYield() ;
- if ( err)
+ wxCHECK_MSG( m_isOk, wxMUTEX_MISC_ERROR, wxT("Invalid Mutex") );
+ OSStatus err = MPSignalSemaphore( m_semaphore );
+
+ MPYield();
+ if (err != noErr)
{
- wxLogSysError(_("Could not unlock mutex"));
- return wxMUTEX_MISC_ERROR;
+ wxLogSysError( wxT("Could not unlock mutex") );
+ return wxMUTEX_MISC_ERROR;
}
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
#endif
class wxMutexInternal
{
public:
- wxMutexInternal(wxMutexType mutexType) ;
- ~wxMutexInternal() ;
- bool IsOk() const { return m_isOk; }
-
- wxMutexError Lock() ;
- wxMutexError TryLock() ;
- wxMutexError Unlock();
-private:
- MPCriticalRegionID m_critRegion ;
+ wxMutexInternal( wxMutexType mutexType );
+ virtual ~wxMutexInternal();
+
+ bool IsOk() const
+ { return m_isOk; }
+
+ wxMutexError Lock() ;
+ wxMutexError TryLock();
+ wxMutexError Unlock();
+
+private:
+ MPCriticalRegionID m_critRegion;
bool m_isOk ;
};
-wxMutexInternal::wxMutexInternal(wxMutexType mutexType )
+wxMutexInternal::wxMutexInternal( wxMutexType mutexType )
{
- m_isOk = false ;
- m_critRegion = kInvalidID ;
-
- verify_noerr( MPCreateCriticalRegion( & m_critRegion) );
- m_isOk = ( m_critRegion != kInvalidID ) ;
-
+ m_isOk = false;
+ m_critRegion = kInvalidID;
+
+ verify_noerr( MPCreateCriticalRegion( &m_critRegion ) );
+ m_isOk = ( m_critRegion != kInvalidID );
if ( !IsOk() )
- wxFAIL_MSG(wxT("Error when creating mutex") ) ;
+ {
+ wxFAIL_MSG( wxT("Error when creating mutex") );
+ }
}
wxMutexInternal::~wxMutexInternal()
{
if ( m_critRegion != kInvalidID )
- MPDeleteCriticalRegion( m_critRegion);
- MPYield() ;
+ MPDeleteCriticalRegion( m_critRegion );
+
+ MPYield();
}
wxMutexError wxMutexInternal::Lock()
{
- wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPEnterCriticalRegion( m_critRegion, kDurationForever);
- if ( err)
+ wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") );
+
+ OSStatus err = MPEnterCriticalRegion( m_critRegion, kDurationForever);
+ if (err != noErr)
{
- wxLogSysError(wxT("Could not lock mutex"));
- return wxMUTEX_MISC_ERROR;
+ wxLogSysError(wxT("Could not lock mutex"));
+ return wxMUTEX_MISC_ERROR;
}
-
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
wxMutexError wxMutexInternal::TryLock()
{
wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPEnterCriticalRegion( m_critRegion, kDurationImmediate);
- if ( err)
+
+ OSStatus err = MPEnterCriticalRegion( m_critRegion, kDurationImmediate);
+ if (err != noErr)
{
- if ( err == kMPTimeoutErr)
- {
- return wxMUTEX_BUSY;
- }
- wxLogSysError(wxT("Could not try lock mutex"));
- return wxMUTEX_MISC_ERROR;
+ if ( err == kMPTimeoutErr)
+ return wxMUTEX_BUSY;
+
+ wxLogSysError( wxT("Could not try lock mutex") );
+ return wxMUTEX_MISC_ERROR;
}
-
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
wxMutexError wxMutexInternal::Unlock()
{
wxCHECK_MSG( m_isOk , wxMUTEX_MISC_ERROR , wxT("Invalid Mutex") ) ;
- OSStatus err = MPExitCriticalRegion( m_critRegion);
- MPYield() ;
- if ( err)
+
+ OSStatus err = MPExitCriticalRegion( m_critRegion );
+ MPYield() ;
+
+ if (err != noErr)
{
- wxLogSysError(_("Could not unlock mutex"));
- return wxMUTEX_MISC_ERROR;
+ wxLogSysError( wxT("Could not unlock mutex") );
+
+ return wxMUTEX_MISC_ERROR;
}
-
- return wxMUTEX_NO_ERROR;
+
+ return wxMUTEX_NO_ERROR;
}
#endif
class wxSemaphoreInternal
{
public:
- wxSemaphoreInternal(int initialcount, int maxcount);
- ~wxSemaphoreInternal();
-
- bool IsOk() const { return m_isOk; }
-
- wxSemaError WaitTimeout(unsigned long milliseconds);
-
- wxSemaError Wait() { return WaitTimeout( kDurationForever); }
-
- wxSemaError TryWait()
- {
- wxSemaError err = WaitTimeout(kDurationImmediate);
- if ( err == wxSEMA_TIMEOUT )
- err = wxSEMA_BUSY ;
- return err ;
- }
- wxSemaError Post();
-
+ wxSemaphoreInternal( int initialcount, int maxcount );
+ virtual ~wxSemaphoreInternal();
+
+ bool IsOk() const
+ { return m_isOk; }
+
+ wxSemaError Post();
+ wxSemaError WaitTimeout( unsigned long milliseconds );
+
+ wxSemaError Wait()
+ { return WaitTimeout( kDurationForever); }
+
+ wxSemaError TryWait()
+ {
+ wxSemaError err = WaitTimeout( kDurationImmediate );
+ if (err == wxSEMA_TIMEOUT)
+ err = wxSEMA_BUSY;
+
+ return err;
+ }
+
private:
MPSemaphoreID m_semaphore;
- bool m_isOk ;
+ bool m_isOk;
};
-wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
+wxSemaphoreInternal::wxSemaphoreInternal( int initialcount, int maxcount)
{
- m_isOk = false ;
- m_semaphore = kInvalidID ;
- if ( maxcount == 0 )
+ m_isOk = false;
+ m_semaphore = kInvalidID;
+ if ( maxcount == 0 )
+ // make it practically infinite
+ maxcount = INT_MAX;
+
+ verify_noerr( MPCreateSemaphore( maxcount, initialcount, &m_semaphore ) );
+ m_isOk = ( m_semaphore != kInvalidID );
+
+ if ( !IsOk() )
{
- // make it practically infinite
- maxcount = INT_MAX;
+ wxFAIL_MSG( wxT("Error when creating semaphore") );
}
- verify_noerr( MPCreateSemaphore( maxcount, initialcount, & m_semaphore) );
- m_isOk = ( m_semaphore != kInvalidID ) ;
-
- if ( !IsOk() )
- wxFAIL_MSG(wxT("Error when creating semaphore") ) ;
}
wxSemaphoreInternal::~wxSemaphoreInternal()
{
- if( m_semaphore != kInvalidID )
- MPDeleteSemaphore( m_semaphore);
- MPYield() ;
+ if (m_semaphore != kInvalidID)
+ MPDeleteSemaphore( m_semaphore );
+
+ MPYield();
}
-wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds)
+wxSemaError wxSemaphoreInternal::WaitTimeout( unsigned long milliseconds )
{
- OSStatus err = MPWaitOnSemaphore( m_semaphore, milliseconds);
- if ( err)
+ OSStatus err = MPWaitOnSemaphore( m_semaphore, milliseconds );
+ if (err != noErr)
{
- if ( err == kMPTimeoutErr)
- {
- return wxSEMA_TIMEOUT;
- }
- return wxSEMA_MISC_ERROR;
+ if (err == kMPTimeoutErr)
+ return wxSEMA_TIMEOUT;
+
+ return wxSEMA_MISC_ERROR;
}
- return wxSEMA_NO_ERROR;
+
+ return wxSEMA_NO_ERROR;
}
wxSemaError wxSemaphoreInternal::Post()
{
- OSStatus err = MPSignalSemaphore( m_semaphore);
- MPYield() ;
- if ( err)
- {
- return wxSEMA_MISC_ERROR;
- }
- return wxSEMA_NO_ERROR;
+ OSStatus err = MPSignalSemaphore( m_semaphore );
+ MPYield();
+ if (err != noErr)
+ return wxSEMA_MISC_ERROR;
+
+ return wxSEMA_NO_ERROR;
}
// ----------------------------------------------------------------------------
class wxConditionInternal
{
public:
-
- wxConditionInternal(wxMutex& mutex)
- : m_mutex( mutex),
- m_semaphore( 0, 1),
- m_gate( 1, 1)
- {
- m_waiters = 0;
- m_signals = 0;
- m_canceled = 0;
- }
-
- ~wxConditionInternal()
- {
- }
-
- bool IsOk() const { return m_mutex.IsOk() ; }
-
- wxCondError Wait()
- {
- return WaitTimeout( kDurationForever);
- }
-
- wxCondError WaitTimeout(unsigned long msectimeout);
-
- wxCondError Signal()
- {
- return DoSignal( false);
- }
-
- wxCondError Broadcast()
- {
- return DoSignal( true);
- }
-
+ wxConditionInternal( wxMutex& mutex )
+ :
+ m_mutex( mutex ),
+ m_semaphore( 0, 1 ),
+ m_gate( 1, 1 )
+ {
+ m_waiters = 0;
+ m_signals = 0;
+ m_canceled = 0;
+ }
+
+ virtual ~wxConditionInternal() {}
+
+ bool IsOk() const
+ { return m_mutex.IsOk(); }
+
+ wxCondError Wait()
+ { return WaitTimeout( kDurationForever ); }
+
+ wxCondError WaitTimeout( unsigned long msectimeout );
+
+ wxCondError Signal()
+ { return DoSignal( false); }
+
+ wxCondError Broadcast()
+ { return DoSignal( true ); }
+
private:
-
- wxCondError DoSignal( bool signalAll);
-
- wxMutex& m_mutex;
- wxSemaphoreInternal m_semaphore; // Signals the waiting threads.
- wxSemaphoreInternal m_gate;
- wxCriticalSection m_varSection;
- size_t m_waiters; // Number of threads waiting for a signal.
- size_t m_signals; // Number of signals to send.
- size_t m_canceled; // Number of canceled waiters in m_waiters.
+ wxCondError DoSignal( bool signalAll );
+
+ wxMutex& m_mutex;
+ wxSemaphoreInternal m_semaphore; // Signals the waiting threads.
+ wxSemaphoreInternal m_gate;
+ wxCriticalSection m_varSection;
+ size_t m_waiters; // Number of threads waiting for a signal.
+ size_t m_signals; // Number of signals to send.
+ size_t m_canceled; // Number of canceled waiters in m_waiters.
};
+wxCondError wxConditionInternal::WaitTimeout( unsigned long msectimeout )
+{
+ m_gate.Wait();
-wxCondError wxConditionInternal::WaitTimeout(unsigned long msectimeout)
-{
- m_gate.Wait();
- if ( ++ m_waiters == INT_MAX)
- {
- m_varSection.Enter();
- m_waiters -= m_canceled;
- m_signals -= m_canceled;
- m_canceled = 0;
- m_varSection.Leave();
- }
- m_gate.Post();
-
- m_mutex.Unlock();
-
- wxSemaError err = m_semaphore.WaitTimeout( msectimeout);
- wxASSERT( err == wxSEMA_NO_ERROR || err == wxSEMA_TIMEOUT);
-
- m_varSection.Enter();
- if ( err != wxSEMA_NO_ERROR)
+ if ( ++ m_waiters == INT_MAX )
{
- if ( m_signals > m_canceled)
- {
- // A signal is being sent after we timed out.
-
- if ( m_waiters == m_signals)
- {
- // There are no excess waiters to catch the signal, so
- // we must throw it away.
-
- wxSemaError err2 = m_semaphore.Wait();
- if ( err2 != wxSEMA_NO_ERROR)
- {
- wxLogSysError(_("Error while waiting on semaphore"));
- }
- wxASSERT( err2 == wxSEMA_NO_ERROR);
- -- m_waiters;
- if ( -- m_signals == m_canceled)
- {
- // This was the last signal. open the gate.
- wxASSERT( m_waiters == m_canceled);
- m_gate.Post();
- }
- }
- else
- {
- // There are excess waiters to catch the signal, leave
- // it be.
- -- m_waiters;
- }
- }
- else
- {
- // No signals is being sent.
- // The gate may be open or closed, so we can't touch m_waiters.
- ++ m_canceled;
- ++ m_signals;
- }
+ m_varSection.Enter();
+
+ m_waiters -= m_canceled;
+ m_signals -= m_canceled;
+ m_canceled = 0;
+
+ m_varSection.Leave();
}
- else
+
+ m_gate.Post();
+ m_mutex.Unlock();
+
+ wxSemaError err = m_semaphore.WaitTimeout( msectimeout);
+ wxASSERT( err == wxSEMA_NO_ERROR || err == wxSEMA_TIMEOUT);
+
+ m_varSection.Enter();
+
+ if ( err != wxSEMA_NO_ERROR )
{
- // We caught a signal.
- wxASSERT( m_signals > m_canceled);
- -- m_waiters;
- if ( -- m_signals == m_canceled)
- {
- // This was the last signal. open the gate.
- wxASSERT( m_waiters == m_canceled);
- m_gate.Post();
- }
+ if ( m_signals > m_canceled )
+ {
+ // A signal is being sent after we timed out.
+ if ( m_waiters == m_signals )
+ {
+ // There are no excess waiters to catch the signal, so
+ // we must throw it away.
+ wxSemaError err2 = m_semaphore.Wait();
+ if ( err2 != wxSEMA_NO_ERROR )
+ {
+ wxLogSysError( wx("Error while waiting on semaphore") );
+ }
+
+ wxASSERT( err2 == wxSEMA_NO_ERROR);
+
+ --m_waiters;
+ if ( --m_signals == m_canceled )
+ {
+ // This was the last signal. open the gate.
+ wxASSERT( m_waiters == m_canceled );
+ m_gate.Post();
+ }
+ }
+ else
+ {
+ // There are excess waiters to catch the signal, leave it be.
+ --m_waiters;
+ }
+ }
+ else
+ {
+ // No signals is being sent:
+ // the gate may be open or closed, so we can't touch m_waiters.
+ ++m_canceled;
+ ++m_signals;
+ }
}
- m_varSection.Leave();
-
- m_mutex.Lock();
-
- if ( err)
+ else
{
- return err == wxSEMA_TIMEOUT ? wxCOND_TIMEOUT : wxCOND_MISC_ERROR;
+ // We caught a signal.
+ wxASSERT( m_signals > m_canceled );
+
+ --m_waiters;
+
+ if ( --m_signals == m_canceled)
+ {
+ // This was the last signal. open the gate.
+ wxASSERT( m_waiters == m_canceled );
+
+ m_gate.Post();
+ }
}
-
- return wxCOND_NO_ERROR;
+
+ m_varSection.Leave();
+ m_mutex.Lock();
+
+ if (err != noErr)
+ return err == wxSEMA_TIMEOUT ? wxCOND_TIMEOUT : wxCOND_MISC_ERROR;
+
+ return wxCOND_NO_ERROR;
}
wxCondError wxConditionInternal::DoSignal( bool signalAll)
{
- m_gate.Wait();
- m_varSection.Enter();
-
- wxASSERT( m_signals == m_canceled);
-
- if ( m_waiters == m_canceled)
+ m_gate.Wait();
+ m_varSection.Enter();
+
+ wxASSERT( m_signals == m_canceled );
+
+ if ( m_waiters == m_canceled)
{
- m_varSection.Leave();
- m_gate.Post();
- return wxCOND_NO_ERROR;
+ m_varSection.Leave();
+ m_gate.Post();
+ return wxCOND_NO_ERROR;
}
-
- if ( m_canceled > 0)
+
+ if ( m_canceled > 0)
{
- m_waiters -= m_canceled;
- m_signals = 0;
- m_canceled = 0;
+ m_waiters -= m_canceled;
+ m_signals = 0;
+ m_canceled = 0;
}
-
- m_signals = signalAll ? m_waiters : 1;
- size_t n = m_signals;
-
- m_varSection.Leave();
-
- // Let the waiters inherit the gate lock.
-
- do
+
+ m_signals = signalAll ? m_waiters : 1;
+ size_t n = m_signals;
+
+ m_varSection.Leave();
+
+ // Let the waiters inherit the gate lock.
+
+ do
{
- wxSemaError err = m_semaphore.Post();
- wxASSERT( err == wxSEMA_NO_ERROR);
- } while ( -- n);
-
- return wxCOND_NO_ERROR;
+ wxSemaError err = m_semaphore.Post();
+ wxASSERT( err == wxSEMA_NO_ERROR );
+ }
+ while ( --n );
+
+ return wxCOND_NO_ERROR;
}
#else
class wxConditionInternal
{
public:
- wxConditionInternal(wxMutex& mutex);
+ wxConditionInternal( wxMutex& mutex );
- bool IsOk() const { return m_mutex.IsOk() && m_semaphore.IsOk(); }
+ bool IsOk() const
+ { return m_mutex.IsOk() && m_semaphore.IsOk(); }
wxCondError Wait();
- wxCondError WaitTimeout(unsigned long milliseconds);
+ wxCondError WaitTimeout( unsigned long milliseconds );
wxCondError Signal();
wxCondError Broadcast();
DECLARE_NO_COPY_CLASS(wxConditionInternal)
};
-wxConditionInternal::wxConditionInternal(wxMutex& mutex)
- : m_mutex(mutex)
+wxConditionInternal::wxConditionInternal( wxMutex& mutex )
+ : m_mutex(mutex)
{
// another thread can't access it until we return from ctor, so no need to
// protect access to m_numWaiters here
wxCondError wxConditionInternal::Wait()
{
// increment the number of waiters
- IncrementAtomic(&m_numWaiters);
+ IncrementAtomic( &m_numWaiters );
m_mutex.Unlock();
return err == wxSEMA_NO_ERROR ? wxCOND_NO_ERROR : wxCOND_MISC_ERROR;
}
-wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds)
+wxCondError wxConditionInternal::WaitTimeout( unsigned long milliseconds )
{
- IncrementAtomic(&m_numWaiters);
+ IncrementAtomic( &m_numWaiters );
m_mutex.Unlock();
public:
wxThreadInternal()
{
- m_tid = kInvalidID;
- m_state = STATE_NEW;
- m_prio = WXTHREAD_DEFAULT_PRIORITY;
- m_notifyQueueId = kInvalidID;
+ m_tid = kInvalidID;
+ m_state = STATE_NEW;
+ m_prio = WXTHREAD_DEFAULT_PRIORITY;
+ m_notifyQueueId = kInvalidID;
m_exitcode = 0;
- m_cancelled = FALSE ;
+ m_cancelled = false ;
- // set to TRUE only when the thread starts waiting on m_semSuspend
- m_isPaused = FALSE;
+ // set to true only when the thread starts waiting on m_semSuspend
+ m_isPaused = false;
// defaults for joinable threads
- m_shouldBeJoined = TRUE;
- m_isDetached = FALSE;
+ m_shouldBeJoined = true;
+ m_isDetached = false;
}
- ~wxThreadInternal()
+
+ virtual ~wxThreadInternal()
{
- if ( m_notifyQueueId)
- {
- MPDeleteQueue( m_notifyQueueId);
- m_notifyQueueId = kInvalidID ;
- }
+ if ( m_notifyQueueId)
+ {
+ MPDeleteQueue( m_notifyQueueId );
+ m_notifyQueueId = kInvalidID ;
+ }
}
- // thread function
- static OSStatus MacThreadStart(void* arg);
+ // thread function
+ static OSStatus MacThreadStart(void* arg);
// create a new (suspended) thread (for the given thread object)
bool Create(wxThread *thread, unsigned int stackSize);
// thread actions
+
// start the thread
wxThreadError Run();
+
// unblock the thread allowing it to run
void SignalRun() { m_semRun.Post(); }
+
// ask the thread to terminate
void Wait();
+
// go to sleep until Resume() is called
void Pause();
+
// resume the thread
void Resume();
// accessors
// priority
- int GetPriority() const { return m_prio; }
- void SetPriority(int prio) ;
+ int GetPriority() const
+ { return m_prio; }
+ void SetPriority(int prio);
+
// state
- wxThreadState GetState() const { return m_state; }
- void SetState(wxThreadState state) { m_state = state; }
+ wxThreadState GetState() const
+ { return m_state; }
+ void SetState(wxThreadState state)
+ { m_state = state; }
+
+ // Get the ID of this thread's underlying MP Services task.
+ MPTaskID GetId() const
+ { return m_tid; }
- // Get the ID of this thread's underlying MP Services task.
- MPTaskID GetId() const { return m_tid; }
+ void SetCancelFlag()
+ { m_cancelled = true; }
+
+ bool WasCancelled() const
+ { return m_cancelled; }
- void SetCancelFlag() { m_cancelled = TRUE; }
- bool WasCancelled() const { return m_cancelled; }
// exit code
- void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }
- wxThread::ExitCode GetExitCode() const { return m_exitcode; }
+ void SetExitCode(wxThread::ExitCode exitcode)
+ { m_exitcode = exitcode; }
+ wxThread::ExitCode GetExitCode() const
+ { return m_exitcode; }
// the pause flag
- void SetReallyPaused(bool paused) { m_isPaused = paused; }
- bool IsReallyPaused() const { return m_isPaused; }
+ void SetReallyPaused(bool paused)
+ { m_isPaused = paused; }
+ bool IsReallyPaused() const
+ { return m_isPaused; }
// tell the thread that it is a detached one
void Detach()
{
wxCriticalSectionLocker lock(m_csJoinFlag);
- m_shouldBeJoined = FALSE;
- m_isDetached = TRUE;
+ m_shouldBeJoined = false;
+ m_isDetached = true;
}
private:
// the thread we're associated with
wxThread * m_thread;
- MPTaskID m_tid; // thread id
- MPQueueID m_notifyQueueId; // its notification queue
+ MPTaskID m_tid; // thread id
+ MPQueueID m_notifyQueueId; // its notification queue
wxThreadState m_state; // see wxThreadState enum
int m_prio; // in wxWidgets units: from 0 to 100
OSStatus wxThreadInternal::MacThreadStart(void *parameter)
{
- wxThread* thread = (wxThread*) parameter ;
+ wxThread* thread = (wxThread*) parameter ;
wxThreadInternal *pthread = thread->m_internal;
// add to TLS so that This() will work
- verify_noerr( MPSetTaskStorageValue( gs_tlsForWXThread , (long) thread ) ) ;
+ verify_noerr( MPSetTaskStorageValue( gs_tlsForWXThread , (long) thread ) ) ;
// have to declare this before pthread_cleanup_push() which defines a
// block!
{
wxCriticalSectionLocker lock(thread->m_critsect);
- pthread->SetState(STATE_EXITED);
+ pthread->SetState( STATE_EXITED );
}
}
-
+
if ( dontRunAtAll )
{
if ( pthread->m_isDetached )
delete thread;
- return -1 ;
+ return -1;
}
else
{
- // on mac for the running code the correct thread termination is to
- // return
+ // on Mac for the running code,
+ // the correct thread termination is to return
// terminate the thread
- thread->Exit(pthread->m_exitcode);
+ thread->Exit( pthread->m_exitcode );
- return (OSStatus) NULL ; // pthread->m_exitcode;
+ return (OSStatus) NULL; // pthread->m_exitcode;
}
}
-bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
+bool wxThreadInternal::Create( wxThread *thread, unsigned int stackSize )
{
wxASSERT_MSG( m_state == STATE_NEW && !m_tid,
- _T("Create()ing thread twice?") );
+ wxT("Create()ing thread twice?") );
- OSStatus err = noErr ;
- m_thread = thread;
-
- if ( m_notifyQueueId == kInvalidID )
- {
- OSStatus err = MPCreateQueue( & m_notifyQueueId);
- if( err)
- {
- wxLogSysError(_("Cant create the thread event queue"));
- return false;
- }
- }
-
- m_state = STATE_NEW;
-
- err = MPCreateTask( MacThreadStart,
- (void*) m_thread,
- stackSize,
- m_notifyQueueId,
- &m_exitcode,
- 0,
- 0,
- &m_tid);
-
- if ( err)
+ OSStatus err = noErr;
+ m_thread = thread;
+
+ if ( m_notifyQueueId == kInvalidID )
{
- wxLogSysError(_("Can't create thread"));
- return false;
+ OSStatus err = MPCreateQueue( &m_notifyQueueId );
+ if (err != noErr)
+ {
+ wxLogSysError( wxT("Cant create the thread event queue") );
+
+ return false;
+ }
}
-
- if ( m_prio != WXTHREAD_DEFAULT_PRIORITY )
+
+ m_state = STATE_NEW;
+
+ err = MPCreateTask(
+ MacThreadStart, (void*)m_thread, stackSize,
+ m_notifyQueueId, &m_exitcode, 0, 0, &m_tid );
+
+ if (err != noErr)
{
- SetPriority(m_prio);
+ wxLogSysError( wxT("Can't create thread") );
+
+ return false;
}
-
- return true;
+
+ if ( m_prio != WXTHREAD_DEFAULT_PRIORITY )
+ SetPriority( m_prio );
+
+ return true;
}
-void wxThreadInternal::SetPriority( int priority)
+void wxThreadInternal::SetPriority( int priority )
{
- m_prio = priority;
-
- if ( m_tid)
+ m_prio = priority;
+
+ if (m_tid)
{
- // Mac priorities range from 1 to 10,000, with a default of 100.
- // wxWidgets priorities range from 0 to 100 with a default of 50.
- // We can map wxWidgets to Mac priorities easily by assuming
- // the former uses a logarithmic scale.
- const unsigned int macPriority = ( int)( exp( priority / 25.0 * log( 10.0)) + 0.5);
-
- MPSetTaskWeight( m_tid, macPriority);
+ // Mac priorities range from 1 to 10,000, with a default of 100.
+ // wxWidgets priorities range from 0 to 100 with a default of 50.
+ // We can map wxWidgets to Mac priorities easily by assuming
+ // the former uses a logarithmic scale.
+ const unsigned int macPriority = (int)( exp( priority / 25.0 * log( 10.0)) + 0.5);
+
+ MPSetTaskWeight( m_tid, macPriority );
}
}
wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
wxT("thread may only be started once after Create()") );
- SetState(STATE_RUNNING);
+ SetState( STATE_RUNNING );
// wake up threads waiting for our start
SignalRun();
void wxThreadInternal::Wait()
{
- wxCHECK_RET( !m_isDetached, _T("can't wait for a detached thread") );
+ wxCHECK_RET( !m_isDetached, wxT("can't wait for a detached thread") );
// if the thread we're waiting for is waiting for the GUI mutex, we will
// deadlock so make sure we release it temporarily
if ( wxThread::IsMain() )
{
// give the thread we're waiting for chance to do the GUI call
- // it might be in, we don't do this conditionally as the to be waited on
+ // it might be in, we don't do this conditionally as the to be waited on
// thread might have to acquire the mutex later but before terminating
if ( wxGuiOwnedByMainThread() )
- {
wxMutexGuiLeave();
- }
}
{
if ( m_shouldBeJoined )
{
- void * param1;
- void * param2;
- void * rc;
-
- OSStatus err = MPWaitOnQueue ( m_notifyQueueId,
- & param1,
- & param2,
- & rc,
- kDurationForever);
- if ( err)
+ void *param1, *param2, *rc;
+
+ OSStatus err = MPWaitOnQueue(
+ m_notifyQueueId,
+ ¶m1,
+ ¶m2,
+ &rc,
+ kDurationForever );
+ if (err != noErr)
{
- wxLogSysError( _( "Cannot wait for thread termination."));
+ wxLogSysError( wxT( "Cannot wait for thread termination."));
rc = (void*) -1;
}
// but we don't need this here
m_exitcode = rc;
- m_shouldBeJoined = FALSE;
+ m_shouldBeJoined = false;
}
}
}
m_semSuspend.Post();
// reset the flag
- SetReallyPaused(FALSE);
+ SetReallyPaused( false );
}
- SetState(STATE_RUNNING);
+ SetState( STATE_RUNNING );
}
// static functions
wxThread *wxThread::This()
{
wxThread* thr = (wxThread*) MPGetTaskStorageValue( gs_tlsForWXThread ) ;
- return thr;
+
+ return thr;
}
bool wxThread::IsMain()
{
- return GetCurrentId() == gs_idMainThread || gs_idMainThread == kInvalidID ;
+ return GetCurrentId() == gs_idMainThread || gs_idMainThread == kInvalidID ;
}
#ifdef Yield
void wxThread::Yield()
{
#if TARGET_API_MAC_OSX
- CFRunLoopRunInMode( kCFRunLoopDefaultMode , 0 , true ) ;
+ CFRunLoopRunInMode( kCFRunLoopDefaultMode , 0 , true ) ;
#endif
- MPYield();
-}
+ MPYield();
+}
-void wxThread::Sleep(unsigned long milliseconds)
+void wxThread::Sleep( unsigned long milliseconds )
{
- AbsoluteTime wakeup = AddDurationToAbsolute( milliseconds, UpTime());
- MPDelayUntil( & wakeup);
+ AbsoluteTime wakeup = AddDurationToAbsolute( milliseconds, UpTime() );
+ MPDelayUntil( &wakeup );
}
-
int wxThread::GetCPUCount()
{
- return MPProcessors();
+ return MPProcessors();
}
unsigned long wxThread::GetCurrentId()
{
- return (unsigned long)MPCurrentTaskID();
+ return (unsigned long)MPCurrentTaskID();
}
-
-bool wxThread::SetConcurrency(size_t level)
+bool wxThread::SetConcurrency( size_t level )
{
// Cannot be set in MacOS.
- return false;
+ return false;
}
-
-wxThread::wxThread(wxThreadKind kind)
+wxThread::wxThread( wxThreadKind kind )
{
- g_numberOfThreads++;
- m_internal = new wxThreadInternal();
-
- m_isDetached = (kind == wxTHREAD_DETACHED);
+ g_numberOfThreads++;
+ m_internal = new wxThreadInternal();
+
+ m_isDetached = (kind == wxTHREAD_DETACHED);
}
wxThread::~wxThread()
{
wxASSERT_MSG( g_numberOfThreads>0 , wxT("More threads deleted than created.") ) ;
+
g_numberOfThreads--;
#ifdef __WXDEBUG__
if ( m_internal->GetState() != STATE_EXITED &&
m_internal->GetState() != STATE_NEW )
{
- wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."), GetId());
+ wxLogDebug(
+ wxT("The thread %ld is being destroyed although it is still running! The application may crash."),
+ GetId() );
}
m_critsect.Leave();
-#endif // __WXDEBUG__
+#endif
wxDELETE( m_internal ) ;
}
-
-wxThreadError wxThread::Create(unsigned int stackSize)
+wxThreadError wxThread::Create( unsigned int stackSize )
{
- wxCriticalSectionLocker lock(m_critsect);
-
+ wxCriticalSectionLocker lock(m_critsect);
+
if ( m_isDetached )
- {
m_internal->Detach() ;
- }
- if ( m_internal->Create(this, stackSize) == false )
+
+ if ( !m_internal->Create(this, stackSize) )
{
- m_internal->SetState(STATE_EXITED);
+ m_internal->SetState( STATE_EXITED );
+
return wxTHREAD_NO_RESOURCE;
}
-
- return wxTHREAD_NO_ERROR;
+
+ return wxTHREAD_NO_ERROR;
}
wxThreadError wxThread::Run()
if ( m_internal->GetState() != STATE_RUNNING )
{
- wxLogDebug(wxT("Can't pause thread which is not running."));
+ wxLogDebug( wxT("Can't pause thread which is not running.") );
return wxTHREAD_NOT_RUNNING;
}
// just set a flag, the thread will be really paused only during the next
// call to TestDestroy()
- m_internal->SetState(STATE_PAUSED);
+ m_internal->SetState( STATE_PAUSED );
return wxTHREAD_NO_ERROR;
}
wxThreadError wxThread::Resume()
{
wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
- _T("a thread can't resume itself") );
+ wxT("a thread can't resume itself") );
wxCriticalSectionLocker lock(m_critsect);
case STATE_PAUSED:
m_internal->Resume();
return wxTHREAD_NO_ERROR;
+
case STATE_EXITED:
return wxTHREAD_NO_ERROR;
default:
- wxLogDebug(_T("Attempt to resume a thread which is not paused."));
+ wxLogDebug( wxT("Attempt to resume a thread which is not paused.") );
return wxTHREAD_MISC_ERROR;
}
wxThread::ExitCode wxThread::Wait()
{
wxCHECK_MSG( This() != this, (ExitCode)-1,
- _T("a thread can't wait for itself") );
+ wxT("a thread can't wait for itself") );
wxCHECK_MSG( !m_isDetached, (ExitCode)-1,
- _T("can't wait for detached thread") );
+ wxT("can't wait for detached thread") );
m_internal->Wait();
wxThreadError wxThread::Delete(ExitCode *rc)
{
wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
- _T("a thread can't delete itself") );
+ wxT("a thread can't delete itself") );
bool isDetached = m_isDetached;
wxThreadError wxThread::Kill()
{
wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
- _T("a thread can't kill itself") );
+ wxT("a thread can't kill itself") );
switch ( m_internal->GetState() )
{
default:
OSStatus err = MPTerminateTask( m_internal->GetId() , -1 ) ;
- if ( err )
+ if (err != noErr)
{
- wxLogError(_("Failed to terminate a thread."));
+ wxLogError( wxT("Failed to terminate a thread.") );
return wxTHREAD_MISC_ERROR;
}
else
{
// this should be retrieved by Wait actually
- m_internal->SetExitCode((void*)-1);
+ m_internal->SetExitCode( (void*)-1 );
}
return wxTHREAD_NO_ERROR;
}
}
-void wxThread::Exit(ExitCode status)
+void wxThread::Exit( ExitCode status )
{
wxASSERT_MSG( This() == this,
- _T("wxThread::Exit() can only be called in the context of the same thread") );
+ wxT("wxThread::Exit() can only be called in the context of the same thread") );
// don't enter m_critsect before calling OnExit() because the user code
// might deadlock if, for example, it signals a condition in OnExit() (a
// m_critsect on us (almost all of them do)
OnExit();
- MPTaskID threadid = m_internal->GetId() ;
-
+ MPTaskID threadid = m_internal->GetId();
+
if ( IsDetached() )
{
delete this;
else // joinable
{
// update the status of the joinable thread
- wxCriticalSectionLocker lock(m_critsect);
- m_internal->SetState(STATE_EXITED);
+ wxCriticalSectionLocker lock( m_critsect );
+ m_internal->SetState( STATE_EXITED );
}
- MPTerminateTask( threadid , (long) status) ;
+
+ MPTerminateTask( threadid, (long)status );
}
// also test whether we were paused
bool wxThread::TestDestroy()
{
wxASSERT_MSG( This() == this,
- _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
+ wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
m_critsect.Enter();
if ( m_internal->GetState() == STATE_PAUSED )
{
- m_internal->SetReallyPaused(TRUE);
+ m_internal->SetReallyPaused( true );
- // leave the crit section or the other threads will stop too if they
- // try to call any of (seemingly harmless) IsXXX() functions while we
- // sleep
+ // leave the crit section or the other threads will stop too if they attempt
+ // to call any of (seemingly harmless) IsXXX() functions while we sleep
m_critsect.Leave();
m_internal->Pause();
case STATE_PAUSED:
case STATE_NEW:
// thread not yet started, priority will be set when it is
- m_internal->SetPriority(prio);
+ m_internal->SetPriority( prio );
break;
case STATE_EXITED:
default:
- wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
+ wxFAIL_MSG( wxT("impossible to set thread priority in this state") );
}
}
{
case STATE_RUNNING:
case STATE_PAUSED:
- return TRUE;
+ return true;
default:
- return FALSE;
+ return false;
}
}
class wxThreadModule : public wxModule
{
public:
- virtual bool OnInit();
- virtual void OnExit();
-
+ virtual bool OnInit();
+ virtual void OnExit();
+
private:
- DECLARE_DYNAMIC_CLASS(wxThreadModule)
+ DECLARE_DYNAMIC_CLASS(wxThreadModule)
};
IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
bool wxThreadModule::OnInit()
{
- bool hasThreadManager = false ;
- hasThreadManager = MPLibraryIsLoaded();
-
- if ( !hasThreadManager )
+ bool hasThreadManager = MPLibraryIsLoaded();
+
+ if ( !hasThreadManager )
{
- wxLogError( _("MP Thread Support is not available on this System" ) ) ;
- return FALSE ;
+ wxLogError( wxT("MP thread support is not available on this system" ) ) ;
+
+ return false;
}
-
- verify_noerr( MPAllocateTaskStorageIndex( &gs_tlsForWXThread ) ) ;
- // main thread's This() is NULL
- verify_noerr( MPSetTaskStorageValue( gs_tlsForWXThread , 0 ) ) ;
- gs_idMainThread = wxThread::GetCurrentId() ;
-
+ // main thread's This() is NULL
+ verify_noerr( MPAllocateTaskStorageIndex( &gs_tlsForWXThread ) ) ;
+ verify_noerr( MPSetTaskStorageValue( gs_tlsForWXThread, 0 ) ) ;
+
+ gs_idMainThread = wxThread::GetCurrentId();
gs_critsectWaitingForGui = new wxCriticalSection();
gs_critsectGui = new wxCriticalSection();
gs_critsectGui->Enter();
-
- return TRUE;
+
+ return true;
}
void wxThreadModule::OnExit()
gs_critsectGui->Enter();
gs_bGuiOwnedByMainThread = true;
}
+
gs_critsectGui->Leave();
delete gs_critsectGui;
gs_critsectGui = NULL;
wxASSERT_MSG( wxThread::IsMain(),
wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
- if( !gs_critsectWaitingForGui )
+ if ( !gs_critsectWaitingForGui )
return;
-
+
wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
if ( gs_nWaitingForGui == 0 )
{
// some threads are waiting, release the GUI lock if we have it
if ( wxGuiOwnedByMainThread() )
- {
wxMutexGuiLeave();
- }
//else: some other worker thread is doing GUI
}
}
// wake up the main thread
void WXDLLEXPORT wxWakeUpMainThread()
{
- wxMacWakeUp() ;
+ wxMacWakeUp();
}
// ----------------------------------------------------------------------------