set svn:eol-style=native for Externals/**.cpp

git-svn-id: https://dolphin-emu.googlecode.com/svn/trunk@1440 8ced0084-cf51-0410-be5f-012b33b47a6e
This commit is contained in:
bushing 2008-12-08 05:17:03 +00:00
parent 18ceeda47a
commit 9146b9b261
402 changed files with 295007 additions and 295007 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
// stdafx.cpp : source file that includes just the standard includes // stdafx.cpp : source file that includes just the standard includes
// Bochs_disasm.pch will be the pre-compiled header // Bochs_disasm.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information // stdafx.obj will contain the pre-compiled type information
#include "stdafx.h" #include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H // TODO: reference any additional headers you need in STDAFX.H
// and not in this file // and not in this file

View File

@ -1,120 +1,120 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: wx/arrimpl.cpp // Name: wx/arrimpl.cpp
// Purpose: helper file for implementation of dynamic lists // Purpose: helper file for implementation of dynamic lists
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 16.10.97 // Created: 16.10.97
// RCS-ID: $Id: arrimpl.cpp 34241 2005-05-22 12:10:55Z JS $ // RCS-ID: $Id: arrimpl.cpp 34241 2005-05-22 12:10:55Z JS $
// Copyright: (c) 1997 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Copyright: (c) 1997 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows license // Licence: wxWindows license
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/***************************************************************************** /*****************************************************************************
* Purpose: implements methods of "template" class declared in * * Purpose: implements methods of "template" class declared in *
* DECLARE_OBJARRAY macro and which couldn't be implemented inline * * DECLARE_OBJARRAY macro and which couldn't be implemented inline *
* (because they need the full definition of type T in scope) * * (because they need the full definition of type T in scope) *
* * * *
* Usage: 1) #include dynarray.h * * Usage: 1) #include dynarray.h *
* 2) WX_DECLARE_OBJARRAY * * 2) WX_DECLARE_OBJARRAY *
* 3) #include arrimpl.cpp * * 3) #include arrimpl.cpp *
* 4) WX_DEFINE_OBJARRAY * * 4) WX_DEFINE_OBJARRAY *
*****************************************************************************/ *****************************************************************************/
// needed to resolve the conflict between global T and macro parameter T // needed to resolve the conflict between global T and macro parameter T
#define _WX_ERROR_REMOVE2(x) wxT("bad index in ") wxT(#x) wxT("::RemoveAt()") #define _WX_ERROR_REMOVE2(x) wxT("bad index in ") wxT(#x) wxT("::RemoveAt()")
// macro implements remaining (not inline) methods of template list // macro implements remaining (not inline) methods of template list
// (it's private to this file) // (it's private to this file)
#undef _DEFINE_OBJARRAY #undef _DEFINE_OBJARRAY
#define _DEFINE_OBJARRAY(T, name) \ #define _DEFINE_OBJARRAY(T, name) \
name::~name() \ name::~name() \
{ \ { \
Empty(); \ Empty(); \
} \ } \
\ \
void name::DoCopy(const name& src) \ void name::DoCopy(const name& src) \
{ \ { \
for ( size_t ui = 0; ui < src.size(); ui++ ) \ for ( size_t ui = 0; ui < src.size(); ui++ ) \
Add(src[ui]); \ Add(src[ui]); \
} \ } \
\ \
name& name::operator=(const name& src) \ name& name::operator=(const name& src) \
{ \ { \
Empty(); \ Empty(); \
DoCopy(src); \ DoCopy(src); \
\ \
return *this; \ return *this; \
} \ } \
\ \
name::name(const name& src) : wxArrayPtrVoid() \ name::name(const name& src) : wxArrayPtrVoid() \
{ \ { \
DoCopy(src); \ DoCopy(src); \
} \ } \
\ \
void name::DoEmpty() \ void name::DoEmpty() \
{ \ { \
for ( size_t ui = 0; ui < size(); ui++ ) \ for ( size_t ui = 0; ui < size(); ui++ ) \
delete (T*)base_array::operator[](ui); \ delete (T*)base_array::operator[](ui); \
} \ } \
\ \
void name::RemoveAt(size_t uiIndex, size_t nRemove) \ void name::RemoveAt(size_t uiIndex, size_t nRemove) \
{ \ { \
wxCHECK_RET( uiIndex < size(), _WX_ERROR_REMOVE2(name) ); \ wxCHECK_RET( uiIndex < size(), _WX_ERROR_REMOVE2(name) ); \
\ \
for (size_t i = 0; i < nRemove; i++ ) \ for (size_t i = 0; i < nRemove; i++ ) \
delete (T*)base_array::operator[](uiIndex + i); \ delete (T*)base_array::operator[](uiIndex + i); \
\ \
base_array::erase(begin() + uiIndex, begin() + uiIndex + nRemove); \ base_array::erase(begin() + uiIndex, begin() + uiIndex + nRemove); \
} \ } \
\ \
void name::Add(const T& item, size_t nInsert) \ void name::Add(const T& item, size_t nInsert) \
{ \ { \
if (nInsert == 0) \ if (nInsert == 0) \
return; \ return; \
T* pItem = new T(item); \ T* pItem = new T(item); \
size_t nOldSize = size(); \ size_t nOldSize = size(); \
if ( pItem != NULL ) \ if ( pItem != NULL ) \
base_array::insert(end(), nInsert, pItem); \ base_array::insert(end(), nInsert, pItem); \
for (size_t i = 1; i < nInsert; i++) \ for (size_t i = 1; i < nInsert; i++) \
base_array::operator[](nOldSize + i) = new T(item); \ base_array::operator[](nOldSize + i) = new T(item); \
} \ } \
\ \
void name::Insert(const T& item, size_t uiIndex, size_t nInsert) \ void name::Insert(const T& item, size_t uiIndex, size_t nInsert) \
{ \ { \
if (nInsert == 0) \ if (nInsert == 0) \
return; \ return; \
T* pItem = new T(item); \ T* pItem = new T(item); \
if ( pItem != NULL ) \ if ( pItem != NULL ) \
base_array::insert(begin() + uiIndex, nInsert, pItem); \ base_array::insert(begin() + uiIndex, nInsert, pItem); \
for (size_t i = 1; i < nInsert; i++) \ for (size_t i = 1; i < nInsert; i++) \
base_array::operator[](uiIndex + i) = new T(item); \ base_array::operator[](uiIndex + i) = new T(item); \
} \ } \
\ \
int name::Index(const T& Item, bool bFromEnd) const \ int name::Index(const T& Item, bool bFromEnd) const \
{ \ { \
if ( bFromEnd ) { \ if ( bFromEnd ) { \
if ( size() > 0 ) { \ if ( size() > 0 ) { \
size_t ui = size() - 1; \ size_t ui = size() - 1; \
do { \ do { \
if ( (T*)base_array::operator[](ui) == &Item ) \ if ( (T*)base_array::operator[](ui) == &Item ) \
return wx_static_cast(int, ui); \ return wx_static_cast(int, ui); \
ui--; \ ui--; \
} \ } \
while ( ui != 0 ); \ while ( ui != 0 ); \
} \ } \
} \ } \
else { \ else { \
for( size_t ui = 0; ui < size(); ui++ ) { \ for( size_t ui = 0; ui < size(); ui++ ) { \
if( (T*)base_array::operator[](ui) == &Item ) \ if( (T*)base_array::operator[](ui) == &Item ) \
return wx_static_cast(int, ui); \ return wx_static_cast(int, ui); \
} \ } \
} \ } \
\ \
return wxNOT_FOUND; \ return wxNOT_FOUND; \
} }
// redefine the macro so that now it will generate the class implementation // redefine the macro so that now it will generate the class implementation
// old value would provoke a compile-time error if this file is not included // old value would provoke a compile-time error if this file is not included
#undef WX_DEFINE_OBJARRAY #undef WX_DEFINE_OBJARRAY
#define WX_DEFINE_OBJARRAY(name) _DEFINE_OBJARRAY(_wxObjArray##name, name) #define WX_DEFINE_OBJARRAY(name) _DEFINE_OBJARRAY(_wxObjArray##name, name)

View File

@ -1,39 +1,39 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: listimpl.cpp // Name: listimpl.cpp
// Purpose: second-part of macro based implementation of template lists // Purpose: second-part of macro based implementation of template lists
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 16/11/98 // Created: 16/11/98
// RCS-ID: $Id: listimpl.cpp 38893 2006-04-24 17:59:10Z VZ $ // RCS-ID: $Id: listimpl.cpp 38893 2006-04-24 17:59:10Z VZ $
// Copyright: (c) 1998 Vadim Zeitlin // Copyright: (c) 1998 Vadim Zeitlin
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#if wxUSE_STL #if wxUSE_STL
#undef WX_DEFINE_LIST #undef WX_DEFINE_LIST
#define WX_DEFINE_LIST(name) \ #define WX_DEFINE_LIST(name) \
void _WX_LIST_HELPER_##name::DeleteFunction( _WX_LIST_ITEM_TYPE_##name X )\ void _WX_LIST_HELPER_##name::DeleteFunction( _WX_LIST_ITEM_TYPE_##name X )\
{ \ { \
delete X; \ delete X; \
} \ } \
name::BaseListType name::EmptyList; name::BaseListType name::EmptyList;
#else // !wxUSE_STL #else // !wxUSE_STL
#define _DEFINE_LIST(T, name) \ #define _DEFINE_LIST(T, name) \
void wx##name##Node::DeleteData() \ void wx##name##Node::DeleteData() \
{ \ { \
delete (T *)GetData(); \ delete (T *)GetData(); \
} }
// redefine the macro so that now it will generate the class implementation // redefine the macro so that now it will generate the class implementation
// old value would provoke a compile-time error if this file is not included // old value would provoke a compile-time error if this file is not included
#undef WX_DEFINE_LIST #undef WX_DEFINE_LIST
#define WX_DEFINE_LIST(name) _DEFINE_LIST(_WX_LIST_ITEM_TYPE_##name, name) #define WX_DEFINE_LIST(name) _DEFINE_LIST(_WX_LIST_ITEM_TYPE_##name, name)
// don't pollute preprocessor's name space // don't pollute preprocessor's name space
//#undef _DEFINE_LIST //#undef _DEFINE_LIST
#endif // wxUSE_STL/!wxUSE_STL #endif // wxUSE_STL/!wxUSE_STL

View File

@ -1,330 +1,330 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: include/wx/thrimpl.cpp // Name: include/wx/thrimpl.cpp
// Purpose: common part of wxThread Implementations // Purpose: common part of wxThread Implementations
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 04.06.02 (extracted from src/*/thread.cpp files) // Created: 04.06.02 (extracted from src/*/thread.cpp files)
// RCS-ID: $Id: thrimpl.cpp 42206 2006-10-21 16:06:11Z VZ $ // RCS-ID: $Id: thrimpl.cpp 42206 2006-10-21 16:06:11Z VZ $
// Copyright: (c) Vadim Zeitlin (2002) // Copyright: (c) Vadim Zeitlin (2002)
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// this file is supposed to be included only by the various thread.cpp // this file is supposed to be included only by the various thread.cpp
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxMutex // wxMutex
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxMutex::wxMutex(wxMutexType mutexType) wxMutex::wxMutex(wxMutexType mutexType)
{ {
m_internal = new wxMutexInternal(mutexType); m_internal = new wxMutexInternal(mutexType);
if ( !m_internal->IsOk() ) if ( !m_internal->IsOk() )
{ {
delete m_internal; delete m_internal;
m_internal = NULL; m_internal = NULL;
} }
} }
wxMutex::~wxMutex() wxMutex::~wxMutex()
{ {
delete m_internal; delete m_internal;
} }
bool wxMutex::IsOk() const bool wxMutex::IsOk() const
{ {
return m_internal != NULL; return m_internal != NULL;
} }
wxMutexError wxMutex::Lock() wxMutexError wxMutex::Lock()
{ {
wxCHECK_MSG( m_internal, wxMUTEX_INVALID, wxCHECK_MSG( m_internal, wxMUTEX_INVALID,
_T("wxMutex::Lock(): not initialized") ); _T("wxMutex::Lock(): not initialized") );
return m_internal->Lock(); return m_internal->Lock();
} }
wxMutexError wxMutex::TryLock() wxMutexError wxMutex::TryLock()
{ {
wxCHECK_MSG( m_internal, wxMUTEX_INVALID, wxCHECK_MSG( m_internal, wxMUTEX_INVALID,
_T("wxMutex::TryLock(): not initialized") ); _T("wxMutex::TryLock(): not initialized") );
return m_internal->TryLock(); return m_internal->TryLock();
} }
wxMutexError wxMutex::Unlock() wxMutexError wxMutex::Unlock()
{ {
wxCHECK_MSG( m_internal, wxMUTEX_INVALID, wxCHECK_MSG( m_internal, wxMUTEX_INVALID,
_T("wxMutex::Unlock(): not initialized") ); _T("wxMutex::Unlock(): not initialized") );
return m_internal->Unlock(); return m_internal->Unlock();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// wxConditionInternal // wxConditionInternal
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// Win32 and OS/2 don't have explicit support for the POSIX condition // Win32 and OS/2 don't have explicit support for the POSIX condition
// variables and their events/event semaphores have quite different semantics, // variables and their events/event semaphores have quite different semantics,
// so we reimplement the conditions from scratch using the mutexes and // so we reimplement the conditions from scratch using the mutexes and
// semaphores // semaphores
#if defined(__WXMSW__) || defined(__OS2__) || defined(__EMX__) #if defined(__WXMSW__) || defined(__OS2__) || defined(__EMX__)
class wxConditionInternal class wxConditionInternal
{ {
public: 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 Wait();
wxCondError WaitTimeout(unsigned long milliseconds); wxCondError WaitTimeout(unsigned long milliseconds);
wxCondError Signal(); wxCondError Signal();
wxCondError Broadcast(); wxCondError Broadcast();
private: private:
// the number of threads currently waiting for this condition // the number of threads currently waiting for this condition
LONG m_numWaiters; LONG m_numWaiters;
// the critical section protecting m_numWaiters // the critical section protecting m_numWaiters
wxCriticalSection m_csWaiters; wxCriticalSection m_csWaiters;
wxMutex& m_mutex; wxMutex& m_mutex;
wxSemaphore m_semaphore; wxSemaphore m_semaphore;
DECLARE_NO_COPY_CLASS(wxConditionInternal) DECLARE_NO_COPY_CLASS(wxConditionInternal)
}; };
wxConditionInternal::wxConditionInternal(wxMutex& mutex) wxConditionInternal::wxConditionInternal(wxMutex& mutex)
: m_mutex(mutex) : m_mutex(mutex)
{ {
// another thread can't access it until we return from ctor, so no need to // another thread can't access it until we return from ctor, so no need to
// protect access to m_numWaiters here // protect access to m_numWaiters here
m_numWaiters = 0; m_numWaiters = 0;
} }
wxCondError wxConditionInternal::Wait() wxCondError wxConditionInternal::Wait()
{ {
// increment the number of waiters // increment the number of waiters
{ {
wxCriticalSectionLocker lock(m_csWaiters); wxCriticalSectionLocker lock(m_csWaiters);
m_numWaiters++; m_numWaiters++;
} }
m_mutex.Unlock(); m_mutex.Unlock();
// a potential race condition can occur here // a potential race condition can occur here
// //
// after a thread increments m_numWaiters, and unlocks the mutex and before // after a thread increments m_numWaiters, and unlocks the mutex and before
// the semaphore.Wait() is called, if another thread can cause a signal to // the semaphore.Wait() is called, if another thread can cause a signal to
// be generated // be generated
// //
// this race condition is handled by using a semaphore and incrementing the // this race condition is handled by using a semaphore and incrementing the
// semaphore only if m_numWaiters is greater that zero since the semaphore, // semaphore only if m_numWaiters is greater that zero since the semaphore,
// can 'remember' signals the race condition will not occur // can 'remember' signals the race condition will not occur
// wait ( if necessary ) and decrement semaphore // wait ( if necessary ) and decrement semaphore
wxSemaError err = m_semaphore.Wait(); wxSemaError err = m_semaphore.Wait();
m_mutex.Lock(); m_mutex.Lock();
if ( err == wxSEMA_NO_ERROR ) if ( err == wxSEMA_NO_ERROR )
return wxCOND_NO_ERROR; return wxCOND_NO_ERROR;
else if ( err == wxSEMA_TIMEOUT ) else if ( err == wxSEMA_TIMEOUT )
return wxCOND_TIMEOUT; return wxCOND_TIMEOUT;
else else
return wxCOND_MISC_ERROR; return wxCOND_MISC_ERROR;
} }
wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds) wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds)
{ {
{ {
wxCriticalSectionLocker lock(m_csWaiters); wxCriticalSectionLocker lock(m_csWaiters);
m_numWaiters++; m_numWaiters++;
} }
m_mutex.Unlock(); m_mutex.Unlock();
// a race condition can occur at this point in the code // a race condition can occur at this point in the code
// //
// please see the comments in Wait(), for details // please see the comments in Wait(), for details
wxSemaError err = m_semaphore.WaitTimeout(milliseconds); wxSemaError err = m_semaphore.WaitTimeout(milliseconds);
if ( err == wxSEMA_TIMEOUT ) if ( err == wxSEMA_TIMEOUT )
{ {
// another potential race condition exists here it is caused when a // another potential race condition exists here it is caused when a
// 'waiting' thread times out, and returns from WaitForSingleObject, // 'waiting' thread times out, and returns from WaitForSingleObject,
// but has not yet decremented m_numWaiters // but has not yet decremented m_numWaiters
// //
// at this point if another thread calls signal() then the semaphore // at this point if another thread calls signal() then the semaphore
// will be incremented, but the waiting thread will miss it. // will be incremented, but the waiting thread will miss it.
// //
// to handle this particular case, the waiting thread calls // to handle this particular case, the waiting thread calls
// WaitForSingleObject again with a timeout of 0, after locking // WaitForSingleObject again with a timeout of 0, after locking
// m_csWaiters. This call does not block because of the zero // m_csWaiters. This call does not block because of the zero
// timeout, but will allow the waiting thread to catch the missed // timeout, but will allow the waiting thread to catch the missed
// signals. // signals.
wxCriticalSectionLocker lock(m_csWaiters); wxCriticalSectionLocker lock(m_csWaiters);
wxSemaError err2 = m_semaphore.WaitTimeout(0); wxSemaError err2 = m_semaphore.WaitTimeout(0);
if ( err2 != wxSEMA_NO_ERROR ) if ( err2 != wxSEMA_NO_ERROR )
{ {
m_numWaiters--; m_numWaiters--;
} }
} }
m_mutex.Lock(); m_mutex.Lock();
return err == wxSEMA_NO_ERROR ? wxCOND_NO_ERROR return err == wxSEMA_NO_ERROR ? wxCOND_NO_ERROR
: err == wxSEMA_TIMEOUT ? wxCOND_TIMEOUT : err == wxSEMA_TIMEOUT ? wxCOND_TIMEOUT
: wxCOND_MISC_ERROR; : wxCOND_MISC_ERROR;
} }
wxCondError wxConditionInternal::Signal() wxCondError wxConditionInternal::Signal()
{ {
wxCriticalSectionLocker lock(m_csWaiters); wxCriticalSectionLocker lock(m_csWaiters);
if ( m_numWaiters > 0 ) if ( m_numWaiters > 0 )
{ {
// increment the semaphore by 1 // increment the semaphore by 1
if ( m_semaphore.Post() != wxSEMA_NO_ERROR ) if ( m_semaphore.Post() != wxSEMA_NO_ERROR )
return wxCOND_MISC_ERROR; return wxCOND_MISC_ERROR;
m_numWaiters--; m_numWaiters--;
} }
return wxCOND_NO_ERROR; return wxCOND_NO_ERROR;
} }
wxCondError wxConditionInternal::Broadcast() wxCondError wxConditionInternal::Broadcast()
{ {
wxCriticalSectionLocker lock(m_csWaiters); wxCriticalSectionLocker lock(m_csWaiters);
while ( m_numWaiters > 0 ) while ( m_numWaiters > 0 )
{ {
if ( m_semaphore.Post() != wxSEMA_NO_ERROR ) if ( m_semaphore.Post() != wxSEMA_NO_ERROR )
return wxCOND_MISC_ERROR; return wxCOND_MISC_ERROR;
m_numWaiters--; m_numWaiters--;
} }
return wxCOND_NO_ERROR; return wxCOND_NO_ERROR;
} }
#endif // MSW or OS2 #endif // MSW or OS2
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxCondition // wxCondition
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxCondition::wxCondition(wxMutex& mutex) wxCondition::wxCondition(wxMutex& mutex)
{ {
m_internal = new wxConditionInternal(mutex); m_internal = new wxConditionInternal(mutex);
if ( !m_internal->IsOk() ) if ( !m_internal->IsOk() )
{ {
delete m_internal; delete m_internal;
m_internal = NULL; m_internal = NULL;
} }
} }
wxCondition::~wxCondition() wxCondition::~wxCondition()
{ {
delete m_internal; delete m_internal;
} }
bool wxCondition::IsOk() const bool wxCondition::IsOk() const
{ {
return m_internal != NULL; return m_internal != NULL;
} }
wxCondError wxCondition::Wait() wxCondError wxCondition::Wait()
{ {
wxCHECK_MSG( m_internal, wxCOND_INVALID, wxCHECK_MSG( m_internal, wxCOND_INVALID,
_T("wxCondition::Wait(): not initialized") ); _T("wxCondition::Wait(): not initialized") );
return m_internal->Wait(); return m_internal->Wait();
} }
wxCondError wxCondition::WaitTimeout(unsigned long milliseconds) wxCondError wxCondition::WaitTimeout(unsigned long milliseconds)
{ {
wxCHECK_MSG( m_internal, wxCOND_INVALID, wxCHECK_MSG( m_internal, wxCOND_INVALID,
_T("wxCondition::Wait(): not initialized") ); _T("wxCondition::Wait(): not initialized") );
return m_internal->WaitTimeout(milliseconds); return m_internal->WaitTimeout(milliseconds);
} }
wxCondError wxCondition::Signal() wxCondError wxCondition::Signal()
{ {
wxCHECK_MSG( m_internal, wxCOND_INVALID, wxCHECK_MSG( m_internal, wxCOND_INVALID,
_T("wxCondition::Signal(): not initialized") ); _T("wxCondition::Signal(): not initialized") );
return m_internal->Signal(); return m_internal->Signal();
} }
wxCondError wxCondition::Broadcast() wxCondError wxCondition::Broadcast()
{ {
wxCHECK_MSG( m_internal, wxCOND_INVALID, wxCHECK_MSG( m_internal, wxCOND_INVALID,
_T("wxCondition::Broadcast(): not initialized") ); _T("wxCondition::Broadcast(): not initialized") );
return m_internal->Broadcast(); return m_internal->Broadcast();
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// wxSemaphore // wxSemaphore
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
wxSemaphore::wxSemaphore(int initialcount, int maxcount) wxSemaphore::wxSemaphore(int initialcount, int maxcount)
{ {
m_internal = new wxSemaphoreInternal( initialcount, maxcount ); m_internal = new wxSemaphoreInternal( initialcount, maxcount );
if ( !m_internal->IsOk() ) if ( !m_internal->IsOk() )
{ {
delete m_internal; delete m_internal;
m_internal = NULL; m_internal = NULL;
} }
} }
wxSemaphore::~wxSemaphore() wxSemaphore::~wxSemaphore()
{ {
delete m_internal; delete m_internal;
} }
bool wxSemaphore::IsOk() const bool wxSemaphore::IsOk() const
{ {
return m_internal != NULL; return m_internal != NULL;
} }
wxSemaError wxSemaphore::Wait() wxSemaError wxSemaphore::Wait()
{ {
wxCHECK_MSG( m_internal, wxSEMA_INVALID, wxCHECK_MSG( m_internal, wxSEMA_INVALID,
_T("wxSemaphore::Wait(): not initialized") ); _T("wxSemaphore::Wait(): not initialized") );
return m_internal->Wait(); return m_internal->Wait();
} }
wxSemaError wxSemaphore::TryWait() wxSemaError wxSemaphore::TryWait()
{ {
wxCHECK_MSG( m_internal, wxSEMA_INVALID, wxCHECK_MSG( m_internal, wxSEMA_INVALID,
_T("wxSemaphore::TryWait(): not initialized") ); _T("wxSemaphore::TryWait(): not initialized") );
return m_internal->TryWait(); return m_internal->TryWait();
} }
wxSemaError wxSemaphore::WaitTimeout(unsigned long milliseconds) wxSemaError wxSemaphore::WaitTimeout(unsigned long milliseconds)
{ {
wxCHECK_MSG( m_internal, wxSEMA_INVALID, wxCHECK_MSG( m_internal, wxSEMA_INVALID,
_T("wxSemaphore::WaitTimeout(): not initialized") ); _T("wxSemaphore::WaitTimeout(): not initialized") );
return m_internal->WaitTimeout(milliseconds); return m_internal->WaitTimeout(milliseconds);
} }
wxSemaError wxSemaphore::Post() wxSemaError wxSemaphore::Post()
{ {
wxCHECK_MSG( m_internal, wxSEMA_INVALID, wxCHECK_MSG( m_internal, wxSEMA_INVALID,
_T("wxSemaphore::Post(): not initialized") ); _T("wxSemaphore::Post(): not initialized") );
return m_internal->Post(); return m_internal->Post();
} }

View File

@ -1,26 +1,26 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: common/accesscmn.cpp // Name: common/accesscmn.cpp
// Author: Julian Smart // Author: Julian Smart
// Modified by: // Modified by:
// Created: 2003-02-12 // Created: 2003-02-12
// RCS-ID: $Id: accesscmn.cpp 35650 2005-09-23 12:56:45Z MR $ // RCS-ID: $Id: accesscmn.cpp 35650 2005-09-23 12:56:45Z MR $
// Copyright: (c) Julian Smart // Copyright: (c) Julian Smart
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_ACCESSIBILITY #if wxUSE_ACCESSIBILITY
#include "wx/access.h" #include "wx/access.h"
#endif #endif

View File

@ -1,345 +1,345 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/anidecod.cpp // Name: src/common/anidecod.cpp
// Purpose: wxANIDecoder, ANI reader for wxImage and wxAnimation // Purpose: wxANIDecoder, ANI reader for wxImage and wxAnimation
// Author: Francesco Montorsi // Author: Francesco Montorsi
// RCS-ID: $Id: anidecod.cpp 43898 2006-12-10 14:18:37Z VZ $ // RCS-ID: $Id: anidecod.cpp 43898 2006-12-10 14:18:37Z VZ $
// Copyright: (c) Francesco Montorsi // Copyright: (c) Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_STREAMS && wxUSE_ICO_CUR #if wxUSE_STREAMS && wxUSE_ICO_CUR
#include "wx/anidecod.h" #include "wx/anidecod.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/palette.h" #include "wx/palette.h"
#endif #endif
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
// static // static
wxCURHandler wxANIDecoder::sm_handler; wxCURHandler wxANIDecoder::sm_handler;
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// wxANIFrameInfo // wxANIFrameInfo
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
class wxANIFrameInfo class wxANIFrameInfo
{ {
public: public:
wxANIFrameInfo(unsigned int delay = 0, int idx = -1) wxANIFrameInfo(unsigned int delay = 0, int idx = -1)
{ m_delay=delay; m_imageIndex=idx; } { m_delay=delay; m_imageIndex=idx; }
unsigned int m_delay; unsigned int m_delay;
int m_imageIndex; int m_imageIndex;
}; };
#include "wx/arrimpl.cpp" // this is a magic incantation which must be done! #include "wx/arrimpl.cpp" // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(wxImageArray) WX_DEFINE_OBJARRAY(wxImageArray)
#include "wx/arrimpl.cpp" // this is a magic incantation which must be done! #include "wx/arrimpl.cpp" // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(wxANIFrameInfoArray) WX_DEFINE_OBJARRAY(wxANIFrameInfoArray)
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// wxANIDecoder // wxANIDecoder
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
wxANIDecoder::wxANIDecoder() wxANIDecoder::wxANIDecoder()
{ {
} }
wxANIDecoder::~wxANIDecoder() wxANIDecoder::~wxANIDecoder()
{ {
} }
bool wxANIDecoder::ConvertToImage(unsigned int frame, wxImage *image) const bool wxANIDecoder::ConvertToImage(unsigned int frame, wxImage *image) const
{ {
unsigned int idx = m_info[frame].m_imageIndex; unsigned int idx = m_info[frame].m_imageIndex;
*image = m_images[idx]; // copy *image = m_images[idx]; // copy
return image->IsOk(); return image->IsOk();
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// Data accessors // Data accessors
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
wxSize wxANIDecoder::GetFrameSize(unsigned int WXUNUSED(frame)) const wxSize wxANIDecoder::GetFrameSize(unsigned int WXUNUSED(frame)) const
{ {
// all frames are of the same size... // all frames are of the same size...
return m_szAnimation; return m_szAnimation;
} }
wxPoint wxANIDecoder::GetFramePosition(unsigned int WXUNUSED(frame)) const wxPoint wxANIDecoder::GetFramePosition(unsigned int WXUNUSED(frame)) const
{ {
// all frames are of the same size... // all frames are of the same size...
return wxPoint(0,0); return wxPoint(0,0);
} }
wxAnimationDisposal wxANIDecoder::GetDisposalMethod(unsigned int WXUNUSED(frame)) const wxAnimationDisposal wxANIDecoder::GetDisposalMethod(unsigned int WXUNUSED(frame)) const
{ {
// this disposal is implicit for all frames inside an ANI file // this disposal is implicit for all frames inside an ANI file
return wxANIM_TOBACKGROUND; return wxANIM_TOBACKGROUND;
} }
long wxANIDecoder::GetDelay(unsigned int frame) const long wxANIDecoder::GetDelay(unsigned int frame) const
{ {
return m_info[frame].m_delay; return m_info[frame].m_delay;
} }
wxColour wxANIDecoder::GetTransparentColour(unsigned int frame) const wxColour wxANIDecoder::GetTransparentColour(unsigned int frame) const
{ {
unsigned int idx = m_info[frame].m_imageIndex; unsigned int idx = m_info[frame].m_imageIndex;
if (!m_images[idx].HasMask()) if (!m_images[idx].HasMask())
return wxNullColour; return wxNullColour;
return wxColour(m_images[idx].GetMaskRed(), return wxColour(m_images[idx].GetMaskRed(),
m_images[idx].GetMaskGreen(), m_images[idx].GetMaskGreen(),
m_images[idx].GetMaskBlue()); m_images[idx].GetMaskBlue());
} }
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
// ANI reading and decoding // ANI reading and decoding
//--------------------------------------------------------------------------- //---------------------------------------------------------------------------
bool wxANIDecoder::CanRead(wxInputStream& stream) const bool wxANIDecoder::CanRead(wxInputStream& stream) const
{ {
wxInt32 FCC1, FCC2; wxInt32 FCC1, FCC2;
wxUint32 datalen ; wxUint32 datalen ;
wxInt32 riff32; wxInt32 riff32;
memcpy( &riff32, "RIFF", 4 ); memcpy( &riff32, "RIFF", 4 );
wxInt32 list32; wxInt32 list32;
memcpy( &list32, "LIST", 4 ); memcpy( &list32, "LIST", 4 );
wxInt32 ico32; wxInt32 ico32;
memcpy( &ico32, "icon", 4 ); memcpy( &ico32, "icon", 4 );
wxInt32 anih32; wxInt32 anih32;
memcpy( &anih32, "anih", 4 ); memcpy( &anih32, "anih", 4 );
stream.SeekI(0); stream.SeekI(0);
if ( !stream.Read(&FCC1, 4) ) if ( !stream.Read(&FCC1, 4) )
return false; return false;
if ( FCC1 != riff32 ) if ( FCC1 != riff32 )
return false; return false;
// we have a riff file: // we have a riff file:
while ( stream.IsOk() ) while ( stream.IsOk() )
{ {
if ( FCC1 == anih32 ) if ( FCC1 == anih32 )
return true; // found the ANIH chunk - this should be an ANI file return true; // found the ANIH chunk - this should be an ANI file
// we always have a data size: // we always have a data size:
stream.Read(&datalen, 4); stream.Read(&datalen, 4);
datalen = wxINT32_SWAP_ON_BE(datalen) ; datalen = wxINT32_SWAP_ON_BE(datalen) ;
// data should be padded to make even number of bytes // data should be padded to make even number of bytes
if (datalen % 2 == 1) datalen ++ ; if (datalen % 2 == 1) datalen ++ ;
// now either data or a FCC: // now either data or a FCC:
if ( (FCC1 == riff32) || (FCC1 == list32) ) if ( (FCC1 == riff32) || (FCC1 == list32) )
{ {
stream.Read(&FCC2, 4); stream.Read(&FCC2, 4);
} }
else else
{ {
stream.SeekI(stream.TellI() + datalen); stream.SeekI(stream.TellI() + datalen);
} }
// try to read next data chunk: // try to read next data chunk:
if ( !stream.Read(&FCC1, 4) ) if ( !stream.Read(&FCC1, 4) )
{ {
// reading failed -- either EOF or IO error, bail out anyhow // reading failed -- either EOF or IO error, bail out anyhow
return false; return false;
} }
} }
return false; return false;
} }
// the "anih" RIFF chunk // the "anih" RIFF chunk
struct wxANIHeader struct wxANIHeader
{ {
wxInt32 cbSizeOf; // Num bytes in AniHeader (36 bytes) wxInt32 cbSizeOf; // Num bytes in AniHeader (36 bytes)
wxInt32 cFrames; // Number of unique Icons in this cursor wxInt32 cFrames; // Number of unique Icons in this cursor
wxInt32 cSteps; // Number of Blits before the animation cycles wxInt32 cSteps; // Number of Blits before the animation cycles
wxInt32 cx; // width of the frames wxInt32 cx; // width of the frames
wxInt32 cy; // height of the frames wxInt32 cy; // height of the frames
wxInt32 cBitCount; // bit depth wxInt32 cBitCount; // bit depth
wxInt32 cPlanes; // 1 wxInt32 cPlanes; // 1
wxInt32 JifRate; // Default Jiffies (1/60th of a second) if rate chunk not present. wxInt32 JifRate; // Default Jiffies (1/60th of a second) if rate chunk not present.
wxInt32 flags; // Animation Flag (see AF_ constants) wxInt32 flags; // Animation Flag (see AF_ constants)
// ANI files are always little endian so we need to swap bytes on big // ANI files are always little endian so we need to swap bytes on big
// endian architectures // endian architectures
#ifdef WORDS_BIGENDIAN #ifdef WORDS_BIGENDIAN
void AdjustEndianness() void AdjustEndianness()
{ {
// this works because all our fields are wxInt32 and they must be // this works because all our fields are wxInt32 and they must be
// packed without holes between them (if they're not, they wouldn't map // packed without holes between them (if they're not, they wouldn't map
// to the file header!) // to the file header!)
wxInt32 * const start = (wxInt32 *)this; wxInt32 * const start = (wxInt32 *)this;
wxInt32 * const end = start + sizeof(wxANIHeader)/sizeof(wxInt32); wxInt32 * const end = start + sizeof(wxANIHeader)/sizeof(wxInt32);
for ( wxInt32 *p = start; p != end; p++ ) for ( wxInt32 *p = start; p != end; p++ )
{ {
*p = wxINT32_SWAP_ALWAYS(*p); *p = wxINT32_SWAP_ALWAYS(*p);
} }
} }
#else #else
void AdjustEndianness() { } void AdjustEndianness() { }
#endif #endif
}; };
bool wxANIDecoder::Load( wxInputStream& stream ) bool wxANIDecoder::Load( wxInputStream& stream )
{ {
wxInt32 FCC1, FCC2; wxInt32 FCC1, FCC2;
wxUint32 datalen; wxUint32 datalen;
unsigned int globaldelay=0; unsigned int globaldelay=0;
wxInt32 riff32; wxInt32 riff32;
memcpy( &riff32, "RIFF", 4 ); memcpy( &riff32, "RIFF", 4 );
wxInt32 list32; wxInt32 list32;
memcpy( &list32, "LIST", 4 ); memcpy( &list32, "LIST", 4 );
wxInt32 ico32; wxInt32 ico32;
memcpy( &ico32, "icon", 4 ); memcpy( &ico32, "icon", 4 );
wxInt32 anih32; wxInt32 anih32;
memcpy( &anih32, "anih", 4 ); memcpy( &anih32, "anih", 4 );
wxInt32 rate32; wxInt32 rate32;
memcpy( &rate32, "rate", 4 ); memcpy( &rate32, "rate", 4 );
wxInt32 seq32; wxInt32 seq32;
memcpy( &seq32, "seq ", 4 ); memcpy( &seq32, "seq ", 4 );
stream.SeekI(0); stream.SeekI(0);
stream.Read(&FCC1, 4); stream.Read(&FCC1, 4);
if ( FCC1 != riff32 ) if ( FCC1 != riff32 )
return false; return false;
m_nFrames = 0; m_nFrames = 0;
m_szAnimation = wxDefaultSize; m_szAnimation = wxDefaultSize;
m_images.Clear(); m_images.Clear();
m_info.Clear(); m_info.Clear();
// we have a riff file: // we have a riff file:
while ( stream.IsOk() ) while ( stream.IsOk() )
{ {
// we always have a data size: // we always have a data size:
stream.Read(&datalen, 4); stream.Read(&datalen, 4);
datalen = wxINT32_SWAP_ON_BE(datalen); datalen = wxINT32_SWAP_ON_BE(datalen);
//data should be padded to make even number of bytes //data should be padded to make even number of bytes
if (datalen % 2 == 1) datalen++; if (datalen % 2 == 1) datalen++;
// now either data or a FCC: // now either data or a FCC:
if ( (FCC1 == riff32) || (FCC1 == list32) ) if ( (FCC1 == riff32) || (FCC1 == list32) )
{ {
stream.Read(&FCC2, 4); stream.Read(&FCC2, 4);
} }
else if ( FCC1 == anih32 ) else if ( FCC1 == anih32 )
{ {
if ( datalen != sizeof(wxANIHeader) ) if ( datalen != sizeof(wxANIHeader) )
return false; return false;
if (m_nFrames > 0) if (m_nFrames > 0)
return false; // already parsed an ani header? return false; // already parsed an ani header?
struct wxANIHeader header; struct wxANIHeader header;
stream.Read(&header, sizeof(wxANIHeader)); stream.Read(&header, sizeof(wxANIHeader));
header.AdjustEndianness(); header.AdjustEndianness();
// we should have a global frame size // we should have a global frame size
m_szAnimation = wxSize(header.cx, header.cy); m_szAnimation = wxSize(header.cx, header.cy);
// save interesting info from the header // save interesting info from the header
m_nFrames = header.cSteps; // NB: not cFrames!! m_nFrames = header.cSteps; // NB: not cFrames!!
if ( m_nFrames == 0 ) if ( m_nFrames == 0 )
return false; return false;
globaldelay = header.JifRate * 1000 / 60; globaldelay = header.JifRate * 1000 / 60;
m_images.Alloc(header.cFrames); m_images.Alloc(header.cFrames);
m_info.Add(wxANIFrameInfo(), m_nFrames); m_info.Add(wxANIFrameInfo(), m_nFrames);
} }
else if ( FCC1 == rate32 ) else if ( FCC1 == rate32 )
{ {
// did we already process the anih32 chunk? // did we already process the anih32 chunk?
if (m_nFrames == 0) if (m_nFrames == 0)
return false; // rate chunks should always be placed after anih chunk return false; // rate chunks should always be placed after anih chunk
wxASSERT(m_info.GetCount() == m_nFrames); wxASSERT(m_info.GetCount() == m_nFrames);
for (unsigned int i=0; i<m_nFrames; i++) for (unsigned int i=0; i<m_nFrames; i++)
{ {
stream.Read(&FCC2, 4); stream.Read(&FCC2, 4);
m_info[i].m_delay = wxINT32_SWAP_ON_BE(FCC2) * 1000 / 60; m_info[i].m_delay = wxINT32_SWAP_ON_BE(FCC2) * 1000 / 60;
} }
} }
else if ( FCC1 == seq32 ) else if ( FCC1 == seq32 )
{ {
// did we already process the anih32 chunk? // did we already process the anih32 chunk?
if (m_nFrames == 0) if (m_nFrames == 0)
return false; // seq chunks should always be placed after anih chunk return false; // seq chunks should always be placed after anih chunk
wxASSERT(m_info.GetCount() == m_nFrames); wxASSERT(m_info.GetCount() == m_nFrames);
for (unsigned int i=0; i<m_nFrames; i++) for (unsigned int i=0; i<m_nFrames; i++)
{ {
stream.Read(&FCC2, 4); stream.Read(&FCC2, 4);
m_info[i].m_imageIndex = wxINT32_SWAP_ON_BE(FCC2); m_info[i].m_imageIndex = wxINT32_SWAP_ON_BE(FCC2);
} }
} }
else if ( FCC1 == ico32 ) else if ( FCC1 == ico32 )
{ {
// use DoLoadFile() and not LoadFile()! // use DoLoadFile() and not LoadFile()!
wxImage image; wxImage image;
if (!sm_handler.DoLoadFile(&image, stream, false /* verbose */, -1)) if (!sm_handler.DoLoadFile(&image, stream, false /* verbose */, -1))
return false; return false;
m_images.Add(image); m_images.Add(image);
} }
else else
{ {
stream.SeekI(stream.TellI() + datalen); stream.SeekI(stream.TellI() + datalen);
} }
// try to read next data chunk: // try to read next data chunk:
stream.Read(&FCC1, 4); stream.Read(&FCC1, 4);
} }
if (m_nFrames==0) if (m_nFrames==0)
return false; return false;
if (m_nFrames==m_images.GetCount()) if (m_nFrames==m_images.GetCount())
{ {
// if no SEQ chunk is available, display the frames in the order // if no SEQ chunk is available, display the frames in the order
// they were loaded // they were loaded
for (unsigned int i=0; i<m_nFrames; i++) for (unsigned int i=0; i<m_nFrames; i++)
if (m_info[i].m_imageIndex == -1) if (m_info[i].m_imageIndex == -1)
m_info[i].m_imageIndex = i; m_info[i].m_imageIndex = i;
} }
// if some frame has an invalid delay, use the global delay given in the // if some frame has an invalid delay, use the global delay given in the
// ANI header // ANI header
for (unsigned int i=0; i<m_nFrames; i++) for (unsigned int i=0; i<m_nFrames; i++)
if (m_info[i].m_delay == 0) if (m_info[i].m_delay == 0)
m_info[i].m_delay = globaldelay; m_info[i].m_delay = globaldelay;
// if the header did not contain a valid frame size, try to grab // if the header did not contain a valid frame size, try to grab
// it from the size of the first frame (all frames are of the same size) // it from the size of the first frame (all frames are of the same size)
if (m_szAnimation.GetWidth() == 0 || if (m_szAnimation.GetWidth() == 0 ||
m_szAnimation.GetHeight() == 0) m_szAnimation.GetHeight() == 0)
m_szAnimation = wxSize(m_images[0].GetWidth(), m_images[0].GetHeight()); m_szAnimation = wxSize(m_images[0].GetWidth(), m_images[0].GetHeight());
return m_szAnimation != wxDefaultSize; return m_szAnimation != wxDefaultSize;
} }
#endif // wxUSE_STREAMS && wxUSE_ICO_CUR #endif // wxUSE_STREAMS && wxUSE_ICO_CUR

View File

@ -1,103 +1,103 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/animatecmn.cpp // Name: src/common/animatecmn.cpp
// Purpose: wxAnimation and wxAnimationCtrl // Purpose: wxAnimation and wxAnimationCtrl
// Author: Francesco Montorsi // Author: Francesco Montorsi
// Modified By: // Modified By:
// Created: 24/09/2006 // Created: 24/09/2006
// Id: $Id: animatecmn.cpp 43494 2006-11-18 17:46:29Z RR $ // Id: $Id: animatecmn.cpp 43494 2006-11-18 17:46:29Z RR $
// Copyright: (c) Francesco Montorsi // Copyright: (c) Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#if wxUSE_ANIMATIONCTRL #if wxUSE_ANIMATIONCTRL
#include "wx/animate.h" #include "wx/animate.h"
#include "wx/bitmap.h" #include "wx/bitmap.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/brush.h" #include "wx/brush.h"
#include "wx/image.h" #include "wx/image.h"
#include "wx/dcmemory.h" #include "wx/dcmemory.h"
const wxChar wxAnimationCtrlNameStr[] = wxT("animationctrl"); const wxChar wxAnimationCtrlNameStr[] = wxT("animationctrl");
// global object // global object
wxAnimation wxNullAnimation; wxAnimation wxNullAnimation;
IMPLEMENT_ABSTRACT_CLASS(wxAnimationBase, wxObject) IMPLEMENT_ABSTRACT_CLASS(wxAnimationBase, wxObject)
IMPLEMENT_ABSTRACT_CLASS(wxAnimationCtrlBase, wxControl) IMPLEMENT_ABSTRACT_CLASS(wxAnimationCtrlBase, wxControl)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxAnimationCtrlBase // wxAnimationCtrlBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxAnimationCtrlBase::UpdateStaticImage() void wxAnimationCtrlBase::UpdateStaticImage()
{ {
if (!m_bmpStaticReal.IsOk() || !m_bmpStatic.IsOk()) if (!m_bmpStaticReal.IsOk() || !m_bmpStatic.IsOk())
return; return;
// if given bitmap is not of the right size, recreate m_bmpStaticReal accordingly // if given bitmap is not of the right size, recreate m_bmpStaticReal accordingly
const wxSize &sz = GetClientSize(); const wxSize &sz = GetClientSize();
if (sz.GetWidth() != m_bmpStaticReal.GetWidth() || if (sz.GetWidth() != m_bmpStaticReal.GetWidth() ||
sz.GetHeight() != m_bmpStaticReal.GetHeight()) sz.GetHeight() != m_bmpStaticReal.GetHeight())
{ {
if (!m_bmpStaticReal.IsOk() || if (!m_bmpStaticReal.IsOk() ||
m_bmpStaticReal.GetWidth() != sz.GetWidth() || m_bmpStaticReal.GetWidth() != sz.GetWidth() ||
m_bmpStaticReal.GetHeight() != sz.GetHeight()) m_bmpStaticReal.GetHeight() != sz.GetHeight())
{ {
// need to (re)create m_bmpStaticReal // need to (re)create m_bmpStaticReal
if (!m_bmpStaticReal.Create(sz.GetWidth(), sz.GetHeight(), if (!m_bmpStaticReal.Create(sz.GetWidth(), sz.GetHeight(),
m_bmpStatic.GetDepth())) m_bmpStatic.GetDepth()))
{ {
wxLogDebug(wxT("Cannot create the static bitmap")); wxLogDebug(wxT("Cannot create the static bitmap"));
m_bmpStatic = wxNullBitmap; m_bmpStatic = wxNullBitmap;
return; return;
} }
} }
if (m_bmpStatic.GetWidth() <= sz.GetWidth() && if (m_bmpStatic.GetWidth() <= sz.GetWidth() &&
m_bmpStatic.GetHeight() <= sz.GetHeight()) m_bmpStatic.GetHeight() <= sz.GetHeight())
{ {
// clear the background of m_bmpStaticReal // clear the background of m_bmpStaticReal
wxBrush brush(GetBackgroundColour()); wxBrush brush(GetBackgroundColour());
wxMemoryDC dc; wxMemoryDC dc;
dc.SelectObject(m_bmpStaticReal); dc.SelectObject(m_bmpStaticReal);
dc.SetBackground(brush); dc.SetBackground(brush);
dc.Clear(); dc.Clear();
// center the user-provided bitmap in m_bmpStaticReal // center the user-provided bitmap in m_bmpStaticReal
dc.DrawBitmap(m_bmpStatic, dc.DrawBitmap(m_bmpStatic,
(sz.GetWidth()-m_bmpStatic.GetWidth())/2, (sz.GetWidth()-m_bmpStatic.GetWidth())/2,
(sz.GetHeight()-m_bmpStatic.GetHeight())/2, (sz.GetHeight()-m_bmpStatic.GetHeight())/2,
true /* use mask */ ); true /* use mask */ );
} }
else else
{ {
// the user-provided bitmap is bigger than our control, strech it // the user-provided bitmap is bigger than our control, strech it
wxImage temp(m_bmpStatic.ConvertToImage()); wxImage temp(m_bmpStatic.ConvertToImage());
temp.Rescale(sz.GetWidth(), sz.GetHeight(), wxIMAGE_QUALITY_HIGH); temp.Rescale(sz.GetWidth(), sz.GetHeight(), wxIMAGE_QUALITY_HIGH);
m_bmpStaticReal = wxBitmap(temp); m_bmpStaticReal = wxBitmap(temp);
} }
} }
} }
void wxAnimationCtrlBase::SetInactiveBitmap(const wxBitmap &bmp) void wxAnimationCtrlBase::SetInactiveBitmap(const wxBitmap &bmp)
{ {
m_bmpStatic = bmp; m_bmpStatic = bmp;
m_bmpStaticReal = bmp; m_bmpStaticReal = bmp;
// if not playing, update the control now // if not playing, update the control now
// NOTE: DisplayStaticImage() will call UpdateStaticImage automatically // NOTE: DisplayStaticImage() will call UpdateStaticImage automatically
if ( !IsPlaying() ) if ( !IsPlaying() )
DisplayStaticImage(); DisplayStaticImage();
} }
#endif // wxUSE_ANIMATIONCTRL #endif // wxUSE_ANIMATIONCTRL

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,41 +1,41 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/arcall.cpp // Name: src/common/arcall.cpp
// Purpose: wxArchive link all archive streams // Purpose: wxArchive link all archive streams
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: arcall.cpp 42508 2006-10-27 09:53:38Z MW $ // RCS-ID: $Id: arcall.cpp 42508 2006-10-27 09:53:38Z MW $
// Copyright: (c) 2006 Mike Wetherell // Copyright: (c) 2006 Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_ARCHIVE_STREAMS #if wxUSE_ARCHIVE_STREAMS
#if wxUSE_ZIPSTREAM #if wxUSE_ZIPSTREAM
#include "wx/zipstrm.h" #include "wx/zipstrm.h"
#endif #endif
#if wxUSE_TARSTREAM #if wxUSE_TARSTREAM
#include "wx/tarstrm.h" #include "wx/tarstrm.h"
#endif #endif
// Reference archive classes to ensure they are linked into a statically // Reference archive classes to ensure they are linked into a statically
// linked program that uses Find or GetFirst to look for an archive handler. // linked program that uses Find or GetFirst to look for an archive handler.
// It is in its own file so that the user can override this behaviour by // It is in its own file so that the user can override this behaviour by
// providing their own implementation. // providing their own implementation.
void wxUseArchiveClasses() void wxUseArchiveClasses()
{ {
#if wxUSE_ZIPSTREAM #if wxUSE_ZIPSTREAM
wxZipClassFactory(); wxZipClassFactory();
#endif #endif
#if wxUSE_TARSTREAM #if wxUSE_TARSTREAM
wxTarClassFactory(); wxTarClassFactory();
#endif #endif
} }
#endif // wxUSE_ARCHIVE_STREAMS #endif // wxUSE_ARCHIVE_STREAMS

View File

@ -1,43 +1,43 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/arcfind.cpp // Name: src/common/arcfind.cpp
// Purpose: Streams for archive formats // Purpose: Streams for archive formats
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: arcfind.cpp 42508 2006-10-27 09:53:38Z MW $ // RCS-ID: $Id: arcfind.cpp 42508 2006-10-27 09:53:38Z MW $
// Copyright: (c) Mike Wetherell // Copyright: (c) Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_ARCHIVE_STREAMS #if wxUSE_ARCHIVE_STREAMS
#include "wx/archive.h" #include "wx/archive.h"
// These functions are in a separate file so that statically linked apps // These functions are in a separate file so that statically linked apps
// that do not call them to search for archive handlers will only link in // that do not call them to search for archive handlers will only link in
// the archive classes they use. // the archive classes they use.
const wxArchiveClassFactory * const wxArchiveClassFactory *
wxArchiveClassFactory::Find(const wxChar *protocol, wxStreamProtocolType type) wxArchiveClassFactory::Find(const wxChar *protocol, wxStreamProtocolType type)
{ {
for (const wxArchiveClassFactory *f = GetFirst(); f; f = f->GetNext()) for (const wxArchiveClassFactory *f = GetFirst(); f; f = f->GetNext())
if (f->CanHandle(protocol, type)) if (f->CanHandle(protocol, type))
return f; return f;
return NULL; return NULL;
} }
// static // static
const wxArchiveClassFactory *wxArchiveClassFactory::GetFirst() const wxArchiveClassFactory *wxArchiveClassFactory::GetFirst()
{ {
if (!sm_first) if (!sm_first)
wxUseArchiveClasses(); wxUseArchiveClasses();
return sm_first; return sm_first;
} }
#endif // wxUSE_ARCHIVE_STREAMS #endif // wxUSE_ARCHIVE_STREAMS

View File

@ -1,98 +1,98 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/archive.cpp // Name: src/common/archive.cpp
// Purpose: Streams for archive formats // Purpose: Streams for archive formats
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: archive.cpp 42508 2006-10-27 09:53:38Z MW $ // RCS-ID: $Id: archive.cpp 42508 2006-10-27 09:53:38Z MW $
// Copyright: (c) Mike Wetherell // Copyright: (c) Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS #if wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS
#include "wx/archive.h" #include "wx/archive.h"
IMPLEMENT_ABSTRACT_CLASS(wxArchiveEntry, wxObject) IMPLEMENT_ABSTRACT_CLASS(wxArchiveEntry, wxObject)
IMPLEMENT_ABSTRACT_CLASS(wxArchiveClassFactory, wxFilterClassFactoryBase) IMPLEMENT_ABSTRACT_CLASS(wxArchiveClassFactory, wxFilterClassFactoryBase)
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// wxArchiveInputStream // wxArchiveInputStream
wxArchiveInputStream::wxArchiveInputStream(wxInputStream& stream, wxArchiveInputStream::wxArchiveInputStream(wxInputStream& stream,
wxMBConv& conv) wxMBConv& conv)
: wxFilterInputStream(stream), : wxFilterInputStream(stream),
m_conv(conv) m_conv(conv)
{ {
} }
wxArchiveInputStream::wxArchiveInputStream(wxInputStream *stream, wxArchiveInputStream::wxArchiveInputStream(wxInputStream *stream,
wxMBConv& conv) wxMBConv& conv)
: wxFilterInputStream(stream), : wxFilterInputStream(stream),
m_conv(conv) m_conv(conv)
{ {
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// wxArchiveOutputStream // wxArchiveOutputStream
wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream& stream, wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream& stream,
wxMBConv& conv) wxMBConv& conv)
: wxFilterOutputStream(stream), : wxFilterOutputStream(stream),
m_conv(conv) m_conv(conv)
{ {
} }
wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream *stream, wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream *stream,
wxMBConv& conv) wxMBConv& conv)
: wxFilterOutputStream(stream), : wxFilterOutputStream(stream),
m_conv(conv) m_conv(conv)
{ {
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// wxArchiveEntry // wxArchiveEntry
void wxArchiveEntry::SetNotifier(wxArchiveNotifier& notifier) void wxArchiveEntry::SetNotifier(wxArchiveNotifier& notifier)
{ {
UnsetNotifier(); UnsetNotifier();
m_notifier = &notifier; m_notifier = &notifier;
m_notifier->OnEntryUpdated(*this); m_notifier->OnEntryUpdated(*this);
} }
wxArchiveEntry& wxArchiveEntry::operator=(const wxArchiveEntry& WXUNUSED(e)) wxArchiveEntry& wxArchiveEntry::operator=(const wxArchiveEntry& WXUNUSED(e))
{ {
m_notifier = NULL; m_notifier = NULL;
return *this; return *this;
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// wxArchiveClassFactory // wxArchiveClassFactory
wxArchiveClassFactory *wxArchiveClassFactory::sm_first = NULL; wxArchiveClassFactory *wxArchiveClassFactory::sm_first = NULL;
void wxArchiveClassFactory::Remove() void wxArchiveClassFactory::Remove()
{ {
if (m_next != this) if (m_next != this)
{ {
wxArchiveClassFactory **pp = &sm_first; wxArchiveClassFactory **pp = &sm_first;
while (*pp != this) while (*pp != this)
pp = &(*pp)->m_next; pp = &(*pp)->m_next;
*pp = m_next; *pp = m_next;
m_next = this; m_next = this;
} }
} }
#endif // wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS #endif // wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS

View File

@ -1,338 +1,338 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/artprov.cpp // Name: src/common/artprov.cpp
// Purpose: wxArtProvider class // Purpose: wxArtProvider class
// Author: Vaclav Slavik // Author: Vaclav Slavik
// Modified by: // Modified by:
// Created: 18/03/2002 // Created: 18/03/2002
// RCS-ID: $Id: artprov.cpp 41398 2006-09-23 20:16:18Z VZ $ // RCS-ID: $Id: artprov.cpp 41398 2006-09-23 20:16:18Z VZ $
// Copyright: (c) Vaclav Slavik // Copyright: (c) Vaclav Slavik
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// headers // headers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#if defined(__BORLANDC__) #if defined(__BORLANDC__)
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/artprov.h" #include "wx/artprov.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/list.h" #include "wx/list.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/hashmap.h" #include "wx/hashmap.h"
#include "wx/image.h" #include "wx/image.h"
#include "wx/module.h" #include "wx/module.h"
#endif #endif
// =========================================================================== // ===========================================================================
// implementation // implementation
// =========================================================================== // ===========================================================================
#include "wx/listimpl.cpp" #include "wx/listimpl.cpp"
WX_DECLARE_LIST(wxArtProvider, wxArtProvidersList); WX_DECLARE_LIST(wxArtProvider, wxArtProvidersList);
WX_DEFINE_LIST(wxArtProvidersList) WX_DEFINE_LIST(wxArtProvidersList)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Cache class - stores already requested bitmaps // Cache class - stores already requested bitmaps
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
WX_DECLARE_EXPORTED_STRING_HASH_MAP(wxBitmap, wxArtProviderBitmapsHash); WX_DECLARE_EXPORTED_STRING_HASH_MAP(wxBitmap, wxArtProviderBitmapsHash);
class WXDLLEXPORT wxArtProviderCache class WXDLLEXPORT wxArtProviderCache
{ {
public: public:
bool GetBitmap(const wxString& full_id, wxBitmap* bmp); bool GetBitmap(const wxString& full_id, wxBitmap* bmp);
void PutBitmap(const wxString& full_id, const wxBitmap& bmp) void PutBitmap(const wxString& full_id, const wxBitmap& bmp)
{ m_bitmapsHash[full_id] = bmp; } { m_bitmapsHash[full_id] = bmp; }
void Clear(); void Clear();
static wxString ConstructHashID(const wxArtID& id, static wxString ConstructHashID(const wxArtID& id,
const wxArtClient& client, const wxArtClient& client,
const wxSize& size); const wxSize& size);
private: private:
wxArtProviderBitmapsHash m_bitmapsHash; wxArtProviderBitmapsHash m_bitmapsHash;
}; };
bool wxArtProviderCache::GetBitmap(const wxString& full_id, wxBitmap* bmp) bool wxArtProviderCache::GetBitmap(const wxString& full_id, wxBitmap* bmp)
{ {
wxArtProviderBitmapsHash::iterator entry = m_bitmapsHash.find(full_id); wxArtProviderBitmapsHash::iterator entry = m_bitmapsHash.find(full_id);
if ( entry == m_bitmapsHash.end() ) if ( entry == m_bitmapsHash.end() )
{ {
return false; return false;
} }
else else
{ {
*bmp = entry->second; *bmp = entry->second;
return true; return true;
} }
} }
void wxArtProviderCache::Clear() void wxArtProviderCache::Clear()
{ {
m_bitmapsHash.clear(); m_bitmapsHash.clear();
} }
/*static*/ wxString wxArtProviderCache::ConstructHashID( /*static*/ wxString wxArtProviderCache::ConstructHashID(
const wxArtID& id, const wxArtClient& client, const wxArtID& id, const wxArtClient& client,
const wxSize& size) const wxSize& size)
{ {
wxString str; wxString str;
str.Printf(wxT("%s-%s-%i-%i"), id.c_str(), client.c_str(), size.x, size.y); str.Printf(wxT("%s-%s-%i-%i"), id.c_str(), client.c_str(), size.x, size.y);
return str; return str;
} }
// ============================================================================ // ============================================================================
// wxArtProvider class // wxArtProvider class
// ============================================================================ // ============================================================================
IMPLEMENT_ABSTRACT_CLASS(wxArtProvider, wxObject) IMPLEMENT_ABSTRACT_CLASS(wxArtProvider, wxObject)
wxArtProvidersList *wxArtProvider::sm_providers = NULL; wxArtProvidersList *wxArtProvider::sm_providers = NULL;
wxArtProviderCache *wxArtProvider::sm_cache = NULL; wxArtProviderCache *wxArtProvider::sm_cache = NULL;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxArtProvider ctors/dtor // wxArtProvider ctors/dtor
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxArtProvider::~wxArtProvider() wxArtProvider::~wxArtProvider()
{ {
Remove(this); Remove(this);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxArtProvider operations on provider stack // wxArtProvider operations on provider stack
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/*static*/ void wxArtProvider::CommonAddingProvider() /*static*/ void wxArtProvider::CommonAddingProvider()
{ {
if ( !sm_providers ) if ( !sm_providers )
{ {
sm_providers = new wxArtProvidersList; sm_providers = new wxArtProvidersList;
sm_cache = new wxArtProviderCache; sm_cache = new wxArtProviderCache;
} }
sm_cache->Clear(); sm_cache->Clear();
} }
/*static*/ void wxArtProvider::Push(wxArtProvider *provider) /*static*/ void wxArtProvider::Push(wxArtProvider *provider)
{ {
CommonAddingProvider(); CommonAddingProvider();
sm_providers->Insert(provider); sm_providers->Insert(provider);
} }
/*static*/ void wxArtProvider::Insert(wxArtProvider *provider) /*static*/ void wxArtProvider::Insert(wxArtProvider *provider)
{ {
CommonAddingProvider(); CommonAddingProvider();
sm_providers->Append(provider); sm_providers->Append(provider);
} }
/*static*/ bool wxArtProvider::Pop() /*static*/ bool wxArtProvider::Pop()
{ {
wxCHECK_MSG( sm_providers, false, _T("no wxArtProvider exists") ); wxCHECK_MSG( sm_providers, false, _T("no wxArtProvider exists") );
wxCHECK_MSG( !sm_providers->empty(), false, _T("wxArtProviders stack is empty") ); wxCHECK_MSG( !sm_providers->empty(), false, _T("wxArtProviders stack is empty") );
delete sm_providers->GetFirst()->GetData(); delete sm_providers->GetFirst()->GetData();
sm_cache->Clear(); sm_cache->Clear();
return true; return true;
} }
/*static*/ bool wxArtProvider::Remove(wxArtProvider *provider) /*static*/ bool wxArtProvider::Remove(wxArtProvider *provider)
{ {
wxCHECK_MSG( sm_providers, false, _T("no wxArtProvider exists") ); wxCHECK_MSG( sm_providers, false, _T("no wxArtProvider exists") );
if ( sm_providers->DeleteObject(provider) ) if ( sm_providers->DeleteObject(provider) )
{ {
sm_cache->Clear(); sm_cache->Clear();
return true; return true;
} }
return false; return false;
} }
/*static*/ bool wxArtProvider::Delete(wxArtProvider *provider) /*static*/ bool wxArtProvider::Delete(wxArtProvider *provider)
{ {
// provider will remove itself from the stack in its dtor // provider will remove itself from the stack in its dtor
delete provider; delete provider;
return true; return true;
} }
/*static*/ void wxArtProvider::CleanUpProviders() /*static*/ void wxArtProvider::CleanUpProviders()
{ {
if ( sm_providers ) if ( sm_providers )
{ {
while ( !sm_providers->empty() ) while ( !sm_providers->empty() )
delete *sm_providers->begin(); delete *sm_providers->begin();
delete sm_providers; delete sm_providers;
sm_providers = NULL; sm_providers = NULL;
delete sm_cache; delete sm_cache;
sm_cache = NULL; sm_cache = NULL;
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxArtProvider: retrieving bitmaps/icons // wxArtProvider: retrieving bitmaps/icons
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/*static*/ wxBitmap wxArtProvider::GetBitmap(const wxArtID& id, /*static*/ wxBitmap wxArtProvider::GetBitmap(const wxArtID& id,
const wxArtClient& client, const wxArtClient& client,
const wxSize& size) const wxSize& size)
{ {
// safety-check against writing client,id,size instead of id,client,size: // safety-check against writing client,id,size instead of id,client,size:
wxASSERT_MSG( client.Last() == _T('C'), _T("invalid 'client' parameter") ); wxASSERT_MSG( client.Last() == _T('C'), _T("invalid 'client' parameter") );
wxCHECK_MSG( sm_providers, wxNullBitmap, _T("no wxArtProvider exists") ); wxCHECK_MSG( sm_providers, wxNullBitmap, _T("no wxArtProvider exists") );
wxString hashId = wxArtProviderCache::ConstructHashID(id, client, size); wxString hashId = wxArtProviderCache::ConstructHashID(id, client, size);
wxBitmap bmp; wxBitmap bmp;
if ( !sm_cache->GetBitmap(hashId, &bmp) ) if ( !sm_cache->GetBitmap(hashId, &bmp) )
{ {
for (wxArtProvidersList::compatibility_iterator node = sm_providers->GetFirst(); for (wxArtProvidersList::compatibility_iterator node = sm_providers->GetFirst();
node; node = node->GetNext()) node; node = node->GetNext())
{ {
bmp = node->GetData()->CreateBitmap(id, client, size); bmp = node->GetData()->CreateBitmap(id, client, size);
if ( bmp.Ok() ) if ( bmp.Ok() )
{ {
#if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB) #if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
if ( size != wxDefaultSize && if ( size != wxDefaultSize &&
(bmp.GetWidth() != size.x || bmp.GetHeight() != size.y) ) (bmp.GetWidth() != size.x || bmp.GetHeight() != size.y) )
{ {
wxImage img = bmp.ConvertToImage(); wxImage img = bmp.ConvertToImage();
img.Rescale(size.x, size.y); img.Rescale(size.x, size.y);
bmp = wxBitmap(img); bmp = wxBitmap(img);
} }
#endif #endif
break; break;
} }
} }
sm_cache->PutBitmap(hashId, bmp); sm_cache->PutBitmap(hashId, bmp);
} }
return bmp; return bmp;
} }
/*static*/ wxIcon wxArtProvider::GetIcon(const wxArtID& id, /*static*/ wxIcon wxArtProvider::GetIcon(const wxArtID& id,
const wxArtClient& client, const wxArtClient& client,
const wxSize& size) const wxSize& size)
{ {
wxCHECK_MSG( sm_providers, wxNullIcon, _T("no wxArtProvider exists") ); wxCHECK_MSG( sm_providers, wxNullIcon, _T("no wxArtProvider exists") );
wxBitmap bmp = GetBitmap(id, client, size); wxBitmap bmp = GetBitmap(id, client, size);
if ( !bmp.Ok() ) if ( !bmp.Ok() )
return wxNullIcon; return wxNullIcon;
wxIcon icon; wxIcon icon;
icon.CopyFromBitmap(bmp); icon.CopyFromBitmap(bmp);
return icon; return icon;
} }
#if defined(__WXGTK20__) && !defined(__WXUNIVERSAL__) #if defined(__WXGTK20__) && !defined(__WXUNIVERSAL__)
#include "wx/gtk/private.h" #include "wx/gtk/private.h"
extern GtkIconSize wxArtClientToIconSize(const wxArtClient& client); extern GtkIconSize wxArtClientToIconSize(const wxArtClient& client);
#endif // defined(__WXGTK20__) && !defined(__WXUNIVERSAL__) #endif // defined(__WXGTK20__) && !defined(__WXUNIVERSAL__)
/*static*/ wxSize wxArtProvider::GetSizeHint(const wxArtClient& client, /*static*/ wxSize wxArtProvider::GetSizeHint(const wxArtClient& client,
bool platform_dependent) bool platform_dependent)
{ {
if (!platform_dependent) if (!platform_dependent)
{ {
wxArtProvidersList::compatibility_iterator node = sm_providers->GetFirst(); wxArtProvidersList::compatibility_iterator node = sm_providers->GetFirst();
if (node) if (node)
return node->GetData()->DoGetSizeHint(client); return node->GetData()->DoGetSizeHint(client);
} }
// else return platform dependent size // else return platform dependent size
#if defined(__WXGTK20__) && !defined(__WXUNIVERSAL__) #if defined(__WXGTK20__) && !defined(__WXUNIVERSAL__)
// Gtk has specific sizes for each client, see artgtk.cpp // Gtk has specific sizes for each client, see artgtk.cpp
GtkIconSize gtk_size = wxArtClientToIconSize(client); GtkIconSize gtk_size = wxArtClientToIconSize(client);
// no size hints for this client // no size hints for this client
if (gtk_size == GTK_ICON_SIZE_INVALID) if (gtk_size == GTK_ICON_SIZE_INVALID)
return wxDefaultSize; return wxDefaultSize;
gint width, height; gint width, height;
gtk_icon_size_lookup( gtk_size, &width, &height); gtk_icon_size_lookup( gtk_size, &width, &height);
return wxSize(width, height); return wxSize(width, height);
#else // !GTK+ 2 #else // !GTK+ 2
// NB: These size hints may have to be adjusted per platform // NB: These size hints may have to be adjusted per platform
if (client == wxART_TOOLBAR) if (client == wxART_TOOLBAR)
return wxSize(16, 15); return wxSize(16, 15);
else if (client == wxART_MENU) else if (client == wxART_MENU)
return wxSize(16, 15); return wxSize(16, 15);
else if (client == wxART_FRAME_ICON) else if (client == wxART_FRAME_ICON)
return wxSize(16, 15); return wxSize(16, 15);
else if (client == wxART_CMN_DIALOG || client == wxART_MESSAGE_BOX) else if (client == wxART_CMN_DIALOG || client == wxART_MESSAGE_BOX)
return wxSize(32, 32); return wxSize(32, 32);
else if (client == wxART_HELP_BROWSER) else if (client == wxART_HELP_BROWSER)
return wxSize(16, 15); return wxSize(16, 15);
else if (client == wxART_BUTTON) else if (client == wxART_BUTTON)
return wxSize(16, 15); return wxSize(16, 15);
else // wxART_OTHER or perhaps a user's client, no specified size else // wxART_OTHER or perhaps a user's client, no specified size
return wxDefaultSize; return wxDefaultSize;
#endif // GTK+ 2/else #endif // GTK+ 2/else
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// deprecated wxArtProvider methods // deprecated wxArtProvider methods
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if WXWIN_COMPATIBILITY_2_6 #if WXWIN_COMPATIBILITY_2_6
/* static */ void wxArtProvider::PushProvider(wxArtProvider *provider) /* static */ void wxArtProvider::PushProvider(wxArtProvider *provider)
{ {
Push(provider); Push(provider);
} }
/* static */ void wxArtProvider::InsertProvider(wxArtProvider *provider) /* static */ void wxArtProvider::InsertProvider(wxArtProvider *provider)
{ {
Insert(provider); Insert(provider);
} }
/* static */ bool wxArtProvider::PopProvider() /* static */ bool wxArtProvider::PopProvider()
{ {
return Pop(); return Pop();
} }
/* static */ bool wxArtProvider::RemoveProvider(wxArtProvider *provider) /* static */ bool wxArtProvider::RemoveProvider(wxArtProvider *provider)
{ {
// RemoveProvider() used to delete the provider being removed so this is // RemoveProvider() used to delete the provider being removed so this is
// not a typo, we must call Delete() and not Remove() here // not a typo, we must call Delete() and not Remove() here
return Delete(provider); return Delete(provider);
} }
#endif // WXWIN_COMPATIBILITY_2_6 #endif // WXWIN_COMPATIBILITY_2_6
// ============================================================================ // ============================================================================
// wxArtProviderModule // wxArtProviderModule
// ============================================================================ // ============================================================================
class wxArtProviderModule: public wxModule class wxArtProviderModule: public wxModule
{ {
public: public:
bool OnInit() bool OnInit()
{ {
wxArtProvider::InitStdProvider(); wxArtProvider::InitStdProvider();
wxArtProvider::InitNativeProvider(); wxArtProvider::InitNativeProvider();
return true; return true;
} }
void OnExit() void OnExit()
{ {
wxArtProvider::CleanUpProviders(); wxArtProvider::CleanUpProviders();
} }
DECLARE_DYNAMIC_CLASS(wxArtProviderModule) DECLARE_DYNAMIC_CLASS(wxArtProviderModule)
}; };
IMPLEMENT_DYNAMIC_CLASS(wxArtProviderModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxArtProviderModule, wxModule)

View File

@ -1,267 +1,267 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/artstd.cpp // Name: src/common/artstd.cpp
// Purpose: stock wxArtProvider instance with default wxWin art // Purpose: stock wxArtProvider instance with default wxWin art
// Author: Vaclav Slavik // Author: Vaclav Slavik
// Modified by: // Modified by:
// Created: 18/03/2002 // Created: 18/03/2002
// RCS-ID: $Id: artstd.cpp 52561 2008-03-16 00:36:37Z VS $ // RCS-ID: $Id: artstd.cpp 52561 2008-03-16 00:36:37Z VS $
// Copyright: (c) Vaclav Slavik // Copyright: (c) Vaclav Slavik
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// headers // headers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#if defined(__BORLANDC__) #if defined(__BORLANDC__)
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/image.h" #include "wx/image.h"
#endif #endif
#include "wx/artprov.h" #include "wx/artprov.h"
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDefaultArtProvider // wxDefaultArtProvider
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxDefaultArtProvider : public wxArtProvider class wxDefaultArtProvider : public wxArtProvider
{ {
protected: protected:
virtual wxBitmap CreateBitmap(const wxArtID& id, const wxArtClient& client, virtual wxBitmap CreateBitmap(const wxArtID& id, const wxArtClient& client,
const wxSize& size); const wxSize& size);
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// helper macros // helper macros
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Standard macro for getting a resource from XPM file: // Standard macro for getting a resource from XPM file:
#define ART(artId, xpmRc) \ #define ART(artId, xpmRc) \
if ( id == artId ) return wxBitmap(xpmRc##_xpm); if ( id == artId ) return wxBitmap(xpmRc##_xpm);
// There are two ways of getting the standard icon: either via XPMs or via // There are two ways of getting the standard icon: either via XPMs or via
// wxIcon ctor. This depends on the platform: // wxIcon ctor. This depends on the platform:
#if defined(__WXUNIVERSAL__) #if defined(__WXUNIVERSAL__)
#define CREATE_STD_ICON(iconId, xpmRc) return wxNullBitmap; #define CREATE_STD_ICON(iconId, xpmRc) return wxNullBitmap;
#elif defined(__WXGTK__) || defined(__WXMOTIF__) #elif defined(__WXGTK__) || defined(__WXMOTIF__)
#define CREATE_STD_ICON(iconId, xpmRc) return wxBitmap(xpmRc##_xpm); #define CREATE_STD_ICON(iconId, xpmRc) return wxBitmap(xpmRc##_xpm);
#else #else
#define CREATE_STD_ICON(iconId, xpmRc) \ #define CREATE_STD_ICON(iconId, xpmRc) \
{ \ { \
wxIcon icon(_T(iconId)); \ wxIcon icon(_T(iconId)); \
wxBitmap bmp; \ wxBitmap bmp; \
bmp.CopyFromIcon(icon); \ bmp.CopyFromIcon(icon); \
return bmp; \ return bmp; \
} }
#endif #endif
// Macro used in CreateBitmap to get wxICON_FOO icons: // Macro used in CreateBitmap to get wxICON_FOO icons:
#define ART_MSGBOX(artId, iconId, xpmRc) \ #define ART_MSGBOX(artId, iconId, xpmRc) \
if ( id == artId ) \ if ( id == artId ) \
{ \ { \
CREATE_STD_ICON(#iconId, xpmRc) \ CREATE_STD_ICON(#iconId, xpmRc) \
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxArtProvider::InitStdProvider // wxArtProvider::InitStdProvider
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/*static*/ void wxArtProvider::InitStdProvider() /*static*/ void wxArtProvider::InitStdProvider()
{ {
wxArtProvider::Push(new wxDefaultArtProvider); wxArtProvider::Push(new wxDefaultArtProvider);
} }
#if !defined(__WXGTK20__) || defined(__WXUNIVERSAL__) #if !defined(__WXGTK20__) || defined(__WXUNIVERSAL__)
/*static*/ void wxArtProvider::InitNativeProvider() /*static*/ void wxArtProvider::InitNativeProvider()
{ {
} }
#endif #endif
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// XPMs with the art // XPMs with the art
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if defined(__WXGTK__) #if defined(__WXGTK__)
#include "../../art/gtk/info.xpm" #include "../../art/gtk/info.xpm"
#include "../../art/gtk/error.xpm" #include "../../art/gtk/error.xpm"
#include "../../art/gtk/warning.xpm" #include "../../art/gtk/warning.xpm"
#include "../../art/gtk/question.xpm" #include "../../art/gtk/question.xpm"
#elif defined(__WXMOTIF__) #elif defined(__WXMOTIF__)
#include "../../art/motif/info.xpm" #include "../../art/motif/info.xpm"
#include "../../art/motif/error.xpm" #include "../../art/motif/error.xpm"
#include "../../art/motif/warning.xpm" #include "../../art/motif/warning.xpm"
#include "../../art/motif/question.xpm" #include "../../art/motif/question.xpm"
#endif #endif
#if wxUSE_HTML #if wxUSE_HTML
#include "../../art/htmsidep.xpm" #include "../../art/htmsidep.xpm"
#include "../../art/htmoptns.xpm" #include "../../art/htmoptns.xpm"
#include "../../art/htmbook.xpm" #include "../../art/htmbook.xpm"
#include "../../art/htmfoldr.xpm" #include "../../art/htmfoldr.xpm"
#include "../../art/htmpage.xpm" #include "../../art/htmpage.xpm"
#endif // wxUSE_HTML #endif // wxUSE_HTML
#include "../../art/missimg.xpm" #include "../../art/missimg.xpm"
#include "../../art/addbookm.xpm" #include "../../art/addbookm.xpm"
#include "../../art/delbookm.xpm" #include "../../art/delbookm.xpm"
#include "../../art/back.xpm" #include "../../art/back.xpm"
#include "../../art/forward.xpm" #include "../../art/forward.xpm"
#include "../../art/up.xpm" #include "../../art/up.xpm"
#include "../../art/down.xpm" #include "../../art/down.xpm"
#include "../../art/toparent.xpm" #include "../../art/toparent.xpm"
#include "../../art/fileopen.xpm" #include "../../art/fileopen.xpm"
#include "../../art/print.xpm" #include "../../art/print.xpm"
#include "../../art/helpicon.xpm" #include "../../art/helpicon.xpm"
#include "../../art/tipicon.xpm" #include "../../art/tipicon.xpm"
#include "../../art/home.xpm" #include "../../art/home.xpm"
#include "../../art/repview.xpm" #include "../../art/repview.xpm"
#include "../../art/listview.xpm" #include "../../art/listview.xpm"
#include "../../art/new_dir.xpm" #include "../../art/new_dir.xpm"
#include "../../art/harddisk.xpm" #include "../../art/harddisk.xpm"
#include "../../art/cdrom.xpm" #include "../../art/cdrom.xpm"
#include "../../art/floppy.xpm" #include "../../art/floppy.xpm"
#include "../../art/removable.xpm" #include "../../art/removable.xpm"
#include "../../art/folder.xpm" #include "../../art/folder.xpm"
#include "../../art/folder_open.xpm" #include "../../art/folder_open.xpm"
#include "../../art/dir_up.xpm" #include "../../art/dir_up.xpm"
#include "../../art/exefile.xpm" #include "../../art/exefile.xpm"
#include "../../art/deffile.xpm" #include "../../art/deffile.xpm"
#include "../../art/tick.xpm" #include "../../art/tick.xpm"
#include "../../art/cross.xpm" #include "../../art/cross.xpm"
#include "../../art/filesave.xpm" #include "../../art/filesave.xpm"
#include "../../art/filesaveas.xpm" #include "../../art/filesaveas.xpm"
#include "../../art/copy.xpm" #include "../../art/copy.xpm"
#include "../../art/cut.xpm" #include "../../art/cut.xpm"
#include "../../art/paste.xpm" #include "../../art/paste.xpm"
#include "../../art/delete.xpm" #include "../../art/delete.xpm"
#include "../../art/new.xpm" #include "../../art/new.xpm"
#include "../../art/undo.xpm" #include "../../art/undo.xpm"
#include "../../art/redo.xpm" #include "../../art/redo.xpm"
#include "../../art/quit.xpm" #include "../../art/quit.xpm"
#include "../../art/find.xpm" #include "../../art/find.xpm"
#include "../../art/findrepl.xpm" #include "../../art/findrepl.xpm"
wxBitmap wxDefaultArtProvider_CreateBitmap(const wxArtID& id) wxBitmap wxDefaultArtProvider_CreateBitmap(const wxArtID& id)
{ {
// wxMessageBox icons: // wxMessageBox icons:
ART_MSGBOX(wxART_ERROR, wxICON_ERROR, error) ART_MSGBOX(wxART_ERROR, wxICON_ERROR, error)
ART_MSGBOX(wxART_INFORMATION, wxICON_INFORMATION, info) ART_MSGBOX(wxART_INFORMATION, wxICON_INFORMATION, info)
ART_MSGBOX(wxART_WARNING, wxICON_WARNING, warning) ART_MSGBOX(wxART_WARNING, wxICON_WARNING, warning)
ART_MSGBOX(wxART_QUESTION, wxICON_QUESTION, question) ART_MSGBOX(wxART_QUESTION, wxICON_QUESTION, question)
// standard icons: // standard icons:
#if wxUSE_HTML #if wxUSE_HTML
ART(wxART_HELP_SIDE_PANEL, htmsidep) ART(wxART_HELP_SIDE_PANEL, htmsidep)
ART(wxART_HELP_SETTINGS, htmoptns) ART(wxART_HELP_SETTINGS, htmoptns)
ART(wxART_HELP_BOOK, htmbook) ART(wxART_HELP_BOOK, htmbook)
ART(wxART_HELP_FOLDER, htmfoldr) ART(wxART_HELP_FOLDER, htmfoldr)
ART(wxART_HELP_PAGE, htmpage) ART(wxART_HELP_PAGE, htmpage)
#endif // wxUSE_HTML #endif // wxUSE_HTML
ART(wxART_MISSING_IMAGE, missimg) ART(wxART_MISSING_IMAGE, missimg)
ART(wxART_ADD_BOOKMARK, addbookm) ART(wxART_ADD_BOOKMARK, addbookm)
ART(wxART_DEL_BOOKMARK, delbookm) ART(wxART_DEL_BOOKMARK, delbookm)
ART(wxART_GO_BACK, back) ART(wxART_GO_BACK, back)
ART(wxART_GO_FORWARD, forward) ART(wxART_GO_FORWARD, forward)
ART(wxART_GO_UP, up) ART(wxART_GO_UP, up)
ART(wxART_GO_DOWN, down) ART(wxART_GO_DOWN, down)
ART(wxART_GO_TO_PARENT, toparent) ART(wxART_GO_TO_PARENT, toparent)
ART(wxART_GO_HOME, home) ART(wxART_GO_HOME, home)
ART(wxART_FILE_OPEN, fileopen) ART(wxART_FILE_OPEN, fileopen)
ART(wxART_PRINT, print) ART(wxART_PRINT, print)
ART(wxART_HELP, helpicon) ART(wxART_HELP, helpicon)
ART(wxART_TIP, tipicon) ART(wxART_TIP, tipicon)
ART(wxART_REPORT_VIEW, repview) ART(wxART_REPORT_VIEW, repview)
ART(wxART_LIST_VIEW, listview) ART(wxART_LIST_VIEW, listview)
ART(wxART_NEW_DIR, new_dir) ART(wxART_NEW_DIR, new_dir)
ART(wxART_HARDDISK, harddisk) ART(wxART_HARDDISK, harddisk)
ART(wxART_FLOPPY, floppy) ART(wxART_FLOPPY, floppy)
ART(wxART_CDROM, cdrom) ART(wxART_CDROM, cdrom)
ART(wxART_REMOVABLE, removable) ART(wxART_REMOVABLE, removable)
ART(wxART_FOLDER, folder) ART(wxART_FOLDER, folder)
ART(wxART_FOLDER_OPEN, folder_open) ART(wxART_FOLDER_OPEN, folder_open)
ART(wxART_GO_DIR_UP, dir_up) ART(wxART_GO_DIR_UP, dir_up)
ART(wxART_EXECUTABLE_FILE, exefile) ART(wxART_EXECUTABLE_FILE, exefile)
ART(wxART_NORMAL_FILE, deffile) ART(wxART_NORMAL_FILE, deffile)
ART(wxART_TICK_MARK, tick) ART(wxART_TICK_MARK, tick)
ART(wxART_CROSS_MARK, cross) ART(wxART_CROSS_MARK, cross)
ART(wxART_FILE_SAVE, filesave) ART(wxART_FILE_SAVE, filesave)
ART(wxART_FILE_SAVE_AS, filesaveas) ART(wxART_FILE_SAVE_AS, filesaveas)
ART(wxART_COPY, copy) ART(wxART_COPY, copy)
ART(wxART_CUT, cut) ART(wxART_CUT, cut)
ART(wxART_PASTE, paste) ART(wxART_PASTE, paste)
ART(wxART_DELETE, delete) ART(wxART_DELETE, delete)
ART(wxART_UNDO, undo) ART(wxART_UNDO, undo)
ART(wxART_REDO, redo) ART(wxART_REDO, redo)
ART(wxART_QUIT, quit) ART(wxART_QUIT, quit)
ART(wxART_FIND, find) ART(wxART_FIND, find)
ART(wxART_FIND_AND_REPLACE, findrepl) ART(wxART_FIND_AND_REPLACE, findrepl)
ART(wxART_NEW, new) ART(wxART_NEW, new)
return wxNullBitmap; return wxNullBitmap;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// CreateBitmap routine // CreateBitmap routine
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxBitmap wxDefaultArtProvider::CreateBitmap(const wxArtID& id, wxBitmap wxDefaultArtProvider::CreateBitmap(const wxArtID& id,
const wxArtClient& client, const wxArtClient& client,
const wxSize& reqSize) const wxSize& reqSize)
{ {
wxBitmap bmp = wxDefaultArtProvider_CreateBitmap(id); wxBitmap bmp = wxDefaultArtProvider_CreateBitmap(id);
#if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB) #if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
if (bmp.Ok()) if (bmp.Ok())
{ {
// fit into transparent image with desired size hint from the client // fit into transparent image with desired size hint from the client
if (reqSize == wxDefaultSize) if (reqSize == wxDefaultSize)
{ {
// find out if there is a desired size for this client // find out if there is a desired size for this client
wxSize bestSize = GetSizeHint(client); wxSize bestSize = GetSizeHint(client);
if (bestSize != wxDefaultSize) if (bestSize != wxDefaultSize)
{ {
int bmp_w = bmp.GetWidth(); int bmp_w = bmp.GetWidth();
int bmp_h = bmp.GetHeight(); int bmp_h = bmp.GetHeight();
if ((bmp_h < bestSize.x) && (bmp_w < bestSize.y)) if ((bmp_h < bestSize.x) && (bmp_w < bestSize.y))
{ {
// the caller wants default size, which is larger than // the caller wants default size, which is larger than
// the image we have; to avoid degrading it visually by // the image we have; to avoid degrading it visually by
// scaling it up, paste it into transparent image instead: // scaling it up, paste it into transparent image instead:
wxPoint offset((bestSize.x - bmp_w)/2, (bestSize.y - bmp_h)/2); wxPoint offset((bestSize.x - bmp_w)/2, (bestSize.y - bmp_h)/2);
wxImage img = bmp.ConvertToImage(); wxImage img = bmp.ConvertToImage();
img.Resize(bestSize, offset); img.Resize(bestSize, offset);
bmp = wxBitmap(img); bmp = wxBitmap(img);
} }
else // scale (down or mixed, but not up) else // scale (down or mixed, but not up)
{ {
wxImage img = bmp.ConvertToImage(); wxImage img = bmp.ConvertToImage();
bmp = wxBitmap bmp = wxBitmap
( (
img.Scale(bestSize.x, bestSize.y, img.Scale(bestSize.x, bestSize.y,
wxIMAGE_QUALITY_HIGH) wxIMAGE_QUALITY_HIGH)
); );
} }
} }
} }
} }
#else #else
wxUnusedVar(client); wxUnusedVar(client);
wxUnusedVar(reqSize); wxUnusedVar(reqSize);
#endif // wxUSE_IMAGE #endif // wxUSE_IMAGE
return bmp; return bmp;
} }

View File

@ -1,211 +1,211 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/bmpbase.cpp // Name: src/common/bmpbase.cpp
// Purpose: wxBitmapBase // Purpose: wxBitmapBase
// Author: VaclavSlavik // Author: VaclavSlavik
// Created: 2001/04/11 // Created: 2001/04/11
// RCS-ID: $Id: bmpbase.cpp 42752 2006-10-30 19:26:48Z VZ $ // RCS-ID: $Id: bmpbase.cpp 42752 2006-10-30 19:26:48Z VZ $
// Copyright: (c) 2001, Vaclav Slavik // Copyright: (c) 2001, Vaclav Slavik
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/bitmap.h" #include "wx/bitmap.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/colour.h" #include "wx/colour.h"
#include "wx/icon.h" #include "wx/icon.h"
#include "wx/image.h" #include "wx/image.h"
#endif // WX_PRECOMP #endif // WX_PRECOMP
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxVariant support // wxVariant support
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_VARIANT #if wxUSE_VARIANT
IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(wxBitmap,WXDLLEXPORT) IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(wxBitmap,WXDLLEXPORT)
IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(wxIcon,WXDLLEXPORT) IMPLEMENT_VARIANT_OBJECT_EXPORTED_SHALLOWCMP(wxIcon,WXDLLEXPORT)
#endif #endif
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxBitmapBase // wxBitmapBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_BITMAP_BASE #if wxUSE_BITMAP_BASE
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/log.h" #include "wx/log.h"
#include "wx/utils.h" #include "wx/utils.h"
#include "wx/palette.h" #include "wx/palette.h"
#include "wx/module.h" #include "wx/module.h"
#endif // WX_PRECOMP #endif // WX_PRECOMP
IMPLEMENT_ABSTRACT_CLASS(wxBitmapBase, wxGDIObject) IMPLEMENT_ABSTRACT_CLASS(wxBitmapBase, wxGDIObject)
IMPLEMENT_ABSTRACT_CLASS(wxBitmapHandlerBase,wxObject) IMPLEMENT_ABSTRACT_CLASS(wxBitmapHandlerBase,wxObject)
wxList wxBitmapBase::sm_handlers; wxList wxBitmapBase::sm_handlers;
void wxBitmapBase::AddHandler(wxBitmapHandlerBase *handler) void wxBitmapBase::AddHandler(wxBitmapHandlerBase *handler)
{ {
sm_handlers.Append(handler); sm_handlers.Append(handler);
} }
void wxBitmapBase::InsertHandler(wxBitmapHandlerBase *handler) void wxBitmapBase::InsertHandler(wxBitmapHandlerBase *handler)
{ {
sm_handlers.Insert(handler); sm_handlers.Insert(handler);
} }
bool wxBitmapBase::RemoveHandler(const wxString& name) bool wxBitmapBase::RemoveHandler(const wxString& name)
{ {
wxBitmapHandler *handler = FindHandler(name); wxBitmapHandler *handler = FindHandler(name);
if ( handler ) if ( handler )
{ {
sm_handlers.DeleteObject(handler); sm_handlers.DeleteObject(handler);
return true; return true;
} }
else else
return false; return false;
} }
wxBitmapHandler *wxBitmapBase::FindHandler(const wxString& name) wxBitmapHandler *wxBitmapBase::FindHandler(const wxString& name)
{ {
wxList::compatibility_iterator node = sm_handlers.GetFirst(); wxList::compatibility_iterator node = sm_handlers.GetFirst();
while ( node ) while ( node )
{ {
wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData(); wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData();
if ( handler->GetName() == name ) if ( handler->GetName() == name )
return handler; return handler;
node = node->GetNext(); node = node->GetNext();
} }
return NULL; return NULL;
} }
wxBitmapHandler *wxBitmapBase::FindHandler(const wxString& extension, wxBitmapType bitmapType) wxBitmapHandler *wxBitmapBase::FindHandler(const wxString& extension, wxBitmapType bitmapType)
{ {
wxList::compatibility_iterator node = sm_handlers.GetFirst(); wxList::compatibility_iterator node = sm_handlers.GetFirst();
while ( node ) while ( node )
{ {
wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData(); wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData();
if ( handler->GetExtension() == extension && if ( handler->GetExtension() == extension &&
(bitmapType == wxBITMAP_TYPE_ANY || handler->GetType() == bitmapType) ) (bitmapType == wxBITMAP_TYPE_ANY || handler->GetType() == bitmapType) )
return handler; return handler;
node = node->GetNext(); node = node->GetNext();
} }
return NULL; return NULL;
} }
wxBitmapHandler *wxBitmapBase::FindHandler(wxBitmapType bitmapType) wxBitmapHandler *wxBitmapBase::FindHandler(wxBitmapType bitmapType)
{ {
wxList::compatibility_iterator node = sm_handlers.GetFirst(); wxList::compatibility_iterator node = sm_handlers.GetFirst();
while ( node ) while ( node )
{ {
wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData(); wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData();
if (handler->GetType() == bitmapType) if (handler->GetType() == bitmapType)
return handler; return handler;
node = node->GetNext(); node = node->GetNext();
} }
return NULL; return NULL;
} }
void wxBitmapBase::CleanUpHandlers() void wxBitmapBase::CleanUpHandlers()
{ {
wxList::compatibility_iterator node = sm_handlers.GetFirst(); wxList::compatibility_iterator node = sm_handlers.GetFirst();
while ( node ) while ( node )
{ {
wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData(); wxBitmapHandler *handler = (wxBitmapHandler *)node->GetData();
wxList::compatibility_iterator next = node->GetNext(); wxList::compatibility_iterator next = node->GetNext();
delete handler; delete handler;
sm_handlers.Erase(node); sm_handlers.Erase(node);
node = next; node = next;
} }
} }
bool wxBitmapHandlerBase::Create(wxBitmap*, const void*, long, int, int, int) bool wxBitmapHandlerBase::Create(wxBitmap*, const void*, long, int, int, int)
{ {
return false; return false;
} }
bool wxBitmapHandlerBase::LoadFile(wxBitmap*, const wxString&, long, int, int) bool wxBitmapHandlerBase::LoadFile(wxBitmap*, const wxString&, long, int, int)
{ {
return false; return false;
} }
bool wxBitmapHandlerBase::SaveFile(const wxBitmap*, const wxString&, int, const wxPalette*) bool wxBitmapHandlerBase::SaveFile(const wxBitmap*, const wxString&, int, const wxPalette*)
{ {
return false; return false;
} }
class wxBitmapBaseModule: public wxModule class wxBitmapBaseModule: public wxModule
{ {
DECLARE_DYNAMIC_CLASS(wxBitmapBaseModule) DECLARE_DYNAMIC_CLASS(wxBitmapBaseModule)
public: public:
wxBitmapBaseModule() {} wxBitmapBaseModule() {}
bool OnInit() { wxBitmap::InitStandardHandlers(); return true; } bool OnInit() { wxBitmap::InitStandardHandlers(); return true; }
void OnExit() { wxBitmap::CleanUpHandlers(); } void OnExit() { wxBitmap::CleanUpHandlers(); }
}; };
IMPLEMENT_DYNAMIC_CLASS(wxBitmapBaseModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxBitmapBaseModule, wxModule)
#endif // wxUSE_BITMAP_BASE #endif // wxUSE_BITMAP_BASE
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxBitmap common // wxBitmap common
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if !(defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXX11__)) #if !(defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXX11__))
wxBitmap::wxBitmap(const char* const* bits) wxBitmap::wxBitmap(const char* const* bits)
{ {
wxCHECK2_MSG(bits != NULL, return, wxT("invalid bitmap data")); wxCHECK2_MSG(bits != NULL, return, wxT("invalid bitmap data"));
#if wxUSE_IMAGE && wxUSE_XPM #if wxUSE_IMAGE && wxUSE_XPM
wxImage image(bits); wxImage image(bits);
wxCHECK2_MSG(image.Ok(), return, wxT("invalid bitmap data")); wxCHECK2_MSG(image.Ok(), return, wxT("invalid bitmap data"));
*this = wxBitmap(image); *this = wxBitmap(image);
#else #else
wxFAIL_MSG(_T("creating bitmaps from XPMs not supported")); wxFAIL_MSG(_T("creating bitmaps from XPMs not supported"));
#endif // wxUSE_IMAGE && wxUSE_XPM #endif // wxUSE_IMAGE && wxUSE_XPM
} }
#endif // !(defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXX11__)) #endif // !(defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXX11__))
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxMaskBase // wxMaskBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxMaskBase::Create(const wxBitmap& bitmap, const wxColour& colour) bool wxMaskBase::Create(const wxBitmap& bitmap, const wxColour& colour)
{ {
FreeData(); FreeData();
return InitFromColour(bitmap, colour); return InitFromColour(bitmap, colour);
} }
#if wxUSE_PALETTE #if wxUSE_PALETTE
bool wxMaskBase::Create(const wxBitmap& bitmap, int paletteIndex) bool wxMaskBase::Create(const wxBitmap& bitmap, int paletteIndex)
{ {
wxPalette *pal = bitmap.GetPalette(); wxPalette *pal = bitmap.GetPalette();
wxCHECK_MSG( pal, false, wxCHECK_MSG( pal, false,
wxT("Cannot create mask from palette index of a bitmap without palette") ); wxT("Cannot create mask from palette index of a bitmap without palette") );
unsigned char r,g,b; unsigned char r,g,b;
pal->GetRGB(paletteIndex, &r, &g, &b); pal->GetRGB(paletteIndex, &r, &g, &b);
return Create(bitmap, wxColour(r, g, b)); return Create(bitmap, wxColour(r, g, b));
} }
#endif // wxUSE_PALETTE #endif // wxUSE_PALETTE
bool wxMaskBase::Create(const wxBitmap& bitmap) bool wxMaskBase::Create(const wxBitmap& bitmap)
{ {
FreeData(); FreeData();
return InitFromMonoBitmap(bitmap); return InitFromMonoBitmap(bitmap);
} }

View File

@ -1,497 +1,497 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/bookctrl.cpp // Name: src/common/bookctrl.cpp
// Purpose: wxBookCtrlBase implementation // Purpose: wxBookCtrlBase implementation
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 19.08.03 // Created: 19.08.03
// RCS-ID: $Id: bookctrl.cpp 53783 2008-05-27 14:15:14Z SC $ // RCS-ID: $Id: bookctrl.cpp 53783 2008-05-27 14:15:14Z SC $
// Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_BOOKCTRL #if wxUSE_BOOKCTRL
#include "wx/imaglist.h" #include "wx/imaglist.h"
#include "wx/bookctrl.h" #include "wx/bookctrl.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// event table // event table
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
IMPLEMENT_ABSTRACT_CLASS(wxBookCtrlBase, wxControl) IMPLEMENT_ABSTRACT_CLASS(wxBookCtrlBase, wxControl)
BEGIN_EVENT_TABLE(wxBookCtrlBase, wxControl) BEGIN_EVENT_TABLE(wxBookCtrlBase, wxControl)
EVT_SIZE(wxBookCtrlBase::OnSize) EVT_SIZE(wxBookCtrlBase::OnSize)
#if wxUSE_HELP #if wxUSE_HELP
EVT_HELP(wxID_ANY, wxBookCtrlBase::OnHelp) EVT_HELP(wxID_ANY, wxBookCtrlBase::OnHelp)
#endif // wxUSE_HELP #endif // wxUSE_HELP
END_EVENT_TABLE() END_EVENT_TABLE()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// constructors and destructors // constructors and destructors
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxBookCtrlBase::Init() void wxBookCtrlBase::Init()
{ {
m_bookctrl = NULL; m_bookctrl = NULL;
m_imageList = NULL; m_imageList = NULL;
m_ownsImageList = false; m_ownsImageList = false;
m_fitToCurrentPage = false; m_fitToCurrentPage = false;
#if defined(__WXWINCE__) #if defined(__WXWINCE__)
m_internalBorder = 1; m_internalBorder = 1;
#else #else
m_internalBorder = 5; m_internalBorder = 5;
#endif #endif
m_controlMargin = 0; m_controlMargin = 0;
m_controlSizer = NULL; m_controlSizer = NULL;
} }
bool bool
wxBookCtrlBase::Create(wxWindow *parent, wxBookCtrlBase::Create(wxWindow *parent,
wxWindowID id, wxWindowID id,
const wxPoint& pos, const wxPoint& pos,
const wxSize& size, const wxSize& size,
long style, long style,
const wxString& name) const wxString& name)
{ {
return wxControl::Create return wxControl::Create
( (
parent, parent,
id, id,
pos, pos,
size, size,
style, style,
wxDefaultValidator, wxDefaultValidator,
name name
); );
} }
wxBookCtrlBase::~wxBookCtrlBase() wxBookCtrlBase::~wxBookCtrlBase()
{ {
if ( m_ownsImageList ) if ( m_ownsImageList )
{ {
// may be NULL, ok // may be NULL, ok
delete m_imageList; delete m_imageList;
} }
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// image list // image list
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxBookCtrlBase::SetImageList(wxImageList *imageList) void wxBookCtrlBase::SetImageList(wxImageList *imageList)
{ {
if ( m_ownsImageList ) if ( m_ownsImageList )
{ {
// may be NULL, ok // may be NULL, ok
delete m_imageList; delete m_imageList;
m_ownsImageList = false; m_ownsImageList = false;
} }
m_imageList = imageList; m_imageList = imageList;
} }
void wxBookCtrlBase::AssignImageList(wxImageList* imageList) void wxBookCtrlBase::AssignImageList(wxImageList* imageList)
{ {
SetImageList(imageList); SetImageList(imageList);
m_ownsImageList = true; m_ownsImageList = true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// geometry // geometry
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxBookCtrlBase::DoInvalidateBestSize() void wxBookCtrlBase::DoInvalidateBestSize()
{ {
// notice that it is not necessary to invalidate our own best size // notice that it is not necessary to invalidate our own best size
// explicitly if we have m_bookctrl as it will already invalidate the best // explicitly if we have m_bookctrl as it will already invalidate the best
// size of its parent when its own size is invalidated and its parent is // size of its parent when its own size is invalidated and its parent is
// this control // this control
if ( m_bookctrl ) if ( m_bookctrl )
m_bookctrl->InvalidateBestSize(); m_bookctrl->InvalidateBestSize();
else else
wxControl::InvalidateBestSize(); wxControl::InvalidateBestSize();
} }
void wxBookCtrlBase::SetPageSize(const wxSize& size) void wxBookCtrlBase::SetPageSize(const wxSize& size)
{ {
SetClientSize(CalcSizeFromPage(size)); SetClientSize(CalcSizeFromPage(size));
} }
wxSize wxBookCtrlBase::DoGetBestSize() const wxSize wxBookCtrlBase::DoGetBestSize() const
{ {
wxSize bestSize; wxSize bestSize;
// iterate over all pages, get the largest width and height // iterate over all pages, get the largest width and height
const size_t nCount = m_pages.size(); const size_t nCount = m_pages.size();
for ( size_t nPage = 0; nPage < nCount; nPage++ ) for ( size_t nPage = 0; nPage < nCount; nPage++ )
{ {
const wxWindow * const pPage = m_pages[nPage]; const wxWindow * const pPage = m_pages[nPage];
if( pPage ) if( pPage )
{ {
wxSize childBestSize(pPage->GetBestSize()); wxSize childBestSize(pPage->GetBestSize());
if ( childBestSize.x > bestSize.x ) if ( childBestSize.x > bestSize.x )
bestSize.x = childBestSize.x; bestSize.x = childBestSize.x;
if ( childBestSize.y > bestSize.y ) if ( childBestSize.y > bestSize.y )
bestSize.y = childBestSize.y; bestSize.y = childBestSize.y;
} }
} }
if (m_fitToCurrentPage && GetCurrentPage()) if (m_fitToCurrentPage && GetCurrentPage())
bestSize = GetCurrentPage()->GetBestSize(); bestSize = GetCurrentPage()->GetBestSize();
// convert display area to window area, adding the size necessary for the // convert display area to window area, adding the size necessary for the
// tabs // tabs
wxSize best = CalcSizeFromPage(bestSize); wxSize best = CalcSizeFromPage(bestSize);
CacheBestSize(best); CacheBestSize(best);
return best; return best;
} }
wxRect wxBookCtrlBase::GetPageRect() const wxRect wxBookCtrlBase::GetPageRect() const
{ {
const wxSize size = GetControllerSize(); const wxSize size = GetControllerSize();
wxPoint pt; wxPoint pt;
wxRect rectPage(pt, GetClientSize()); wxRect rectPage(pt, GetClientSize());
switch ( GetWindowStyle() & wxBK_ALIGN_MASK ) switch ( GetWindowStyle() & wxBK_ALIGN_MASK )
{ {
default: default:
wxFAIL_MSG( _T("unexpected alignment") ); wxFAIL_MSG( _T("unexpected alignment") );
// fall through // fall through
case wxBK_TOP: case wxBK_TOP:
rectPage.y = size.y + GetInternalBorder(); rectPage.y = size.y + GetInternalBorder();
// fall through // fall through
case wxBK_BOTTOM: case wxBK_BOTTOM:
rectPage.height -= size.y + GetInternalBorder(); rectPage.height -= size.y + GetInternalBorder();
if (rectPage.height < 0) if (rectPage.height < 0)
rectPage.height = 0; rectPage.height = 0;
break; break;
case wxBK_LEFT: case wxBK_LEFT:
rectPage.x = size.x + GetInternalBorder(); rectPage.x = size.x + GetInternalBorder();
// fall through // fall through
case wxBK_RIGHT: case wxBK_RIGHT:
rectPage.width -= size.x + GetInternalBorder(); rectPage.width -= size.x + GetInternalBorder();
if (rectPage.width < 0) if (rectPage.width < 0)
rectPage.width = 0; rectPage.width = 0;
break; break;
} }
return rectPage; return rectPage;
} }
// Lay out controls // Lay out controls
void wxBookCtrlBase::DoSize() void wxBookCtrlBase::DoSize()
{ {
if ( !m_bookctrl ) if ( !m_bookctrl )
{ {
// we're not fully created yet or OnSize() should be hidden by derived class // we're not fully created yet or OnSize() should be hidden by derived class
return; return;
} }
if (GetSizer()) if (GetSizer())
Layout(); Layout();
else else
{ {
// resize controller and the page area to fit inside our new size // resize controller and the page area to fit inside our new size
const wxSize sizeClient( GetClientSize() ), const wxSize sizeClient( GetClientSize() ),
sizeBorder( m_bookctrl->GetSize() - m_bookctrl->GetClientSize() ), sizeBorder( m_bookctrl->GetSize() - m_bookctrl->GetClientSize() ),
sizeCtrl( GetControllerSize() ); sizeCtrl( GetControllerSize() );
m_bookctrl->SetClientSize( sizeCtrl.x - sizeBorder.x, sizeCtrl.y - sizeBorder.y ); m_bookctrl->SetClientSize( sizeCtrl.x - sizeBorder.x, sizeCtrl.y - sizeBorder.y );
// if this changes the visibility of the scrollbars the best size changes, relayout in this case // if this changes the visibility of the scrollbars the best size changes, relayout in this case
wxSize sizeCtrl2 = GetControllerSize(); wxSize sizeCtrl2 = GetControllerSize();
if ( sizeCtrl != sizeCtrl2 ) if ( sizeCtrl != sizeCtrl2 )
{ {
wxSize sizeBorder2 = m_bookctrl->GetSize() - m_bookctrl->GetClientSize(); wxSize sizeBorder2 = m_bookctrl->GetSize() - m_bookctrl->GetClientSize();
m_bookctrl->SetClientSize( sizeCtrl2.x - sizeBorder2.x, sizeCtrl2.y - sizeBorder2.y ); m_bookctrl->SetClientSize( sizeCtrl2.x - sizeBorder2.x, sizeCtrl2.y - sizeBorder2.y );
} }
const wxSize sizeNew = m_bookctrl->GetSize(); const wxSize sizeNew = m_bookctrl->GetSize();
wxPoint posCtrl; wxPoint posCtrl;
switch ( GetWindowStyle() & wxBK_ALIGN_MASK ) switch ( GetWindowStyle() & wxBK_ALIGN_MASK )
{ {
default: default:
wxFAIL_MSG( _T("unexpected alignment") ); wxFAIL_MSG( _T("unexpected alignment") );
// fall through // fall through
case wxBK_TOP: case wxBK_TOP:
case wxBK_LEFT: case wxBK_LEFT:
// posCtrl is already ok // posCtrl is already ok
break; break;
case wxBK_BOTTOM: case wxBK_BOTTOM:
posCtrl.y = sizeClient.y - sizeNew.y; posCtrl.y = sizeClient.y - sizeNew.y;
break; break;
case wxBK_RIGHT: case wxBK_RIGHT:
posCtrl.x = sizeClient.x - sizeNew.x; posCtrl.x = sizeClient.x - sizeNew.x;
break; break;
} }
if ( m_bookctrl->GetPosition() != posCtrl ) if ( m_bookctrl->GetPosition() != posCtrl )
m_bookctrl->Move(posCtrl); m_bookctrl->Move(posCtrl);
} }
// resize all pages to fit the new control size // resize all pages to fit the new control size
const wxRect pageRect = GetPageRect(); const wxRect pageRect = GetPageRect();
const unsigned pagesCount = m_pages.Count(); const unsigned pagesCount = m_pages.Count();
for ( unsigned int i = 0; i < pagesCount; ++i ) for ( unsigned int i = 0; i < pagesCount; ++i )
{ {
wxWindow * const page = m_pages[i]; wxWindow * const page = m_pages[i];
if ( !page ) if ( !page )
{ {
wxASSERT_MSG( AllowNullPage(), wxASSERT_MSG( AllowNullPage(),
_T("Null page in a control that does not allow null pages?") ); _T("Null page in a control that does not allow null pages?") );
continue; continue;
} }
page->SetSize(pageRect); page->SetSize(pageRect);
} }
} }
void wxBookCtrlBase::OnSize(wxSizeEvent& event) void wxBookCtrlBase::OnSize(wxSizeEvent& event)
{ {
event.Skip(); event.Skip();
DoSize(); DoSize();
} }
wxSize wxBookCtrlBase::GetControllerSize() const wxSize wxBookCtrlBase::GetControllerSize() const
{ {
if(!m_bookctrl) if(!m_bookctrl)
return wxSize(0,0); return wxSize(0,0);
const wxSize sizeClient = GetClientSize(), const wxSize sizeClient = GetClientSize(),
sizeBorder = m_bookctrl->GetSize() - m_bookctrl->GetClientSize(), sizeBorder = m_bookctrl->GetSize() - m_bookctrl->GetClientSize(),
sizeCtrl = m_bookctrl->GetBestSize() + sizeBorder; sizeCtrl = m_bookctrl->GetBestSize() + sizeBorder;
wxSize size; wxSize size;
if ( IsVertical() ) if ( IsVertical() )
{ {
size.x = sizeClient.x; size.x = sizeClient.x;
size.y = sizeCtrl.y; size.y = sizeCtrl.y;
} }
else // left/right aligned else // left/right aligned
{ {
size.x = sizeCtrl.x; size.x = sizeCtrl.x;
size.y = sizeClient.y; size.y = sizeClient.y;
} }
return size; return size;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// miscellaneous stuff // miscellaneous stuff
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_HELP #if wxUSE_HELP
void wxBookCtrlBase::OnHelp(wxHelpEvent& event) void wxBookCtrlBase::OnHelp(wxHelpEvent& event)
{ {
// determine where does this even originate from to avoid redirecting it // determine where does this even originate from to avoid redirecting it
// back to the page which generated it (resulting in an infinite loop) // back to the page which generated it (resulting in an infinite loop)
// notice that we have to check in the hard(er) way instead of just testing // notice that we have to check in the hard(er) way instead of just testing
// if the event object == this because the book control can have other // if the event object == this because the book control can have other
// subcontrols inside it (e.g. wxSpinButton in case of a notebook in wxUniv) // subcontrols inside it (e.g. wxSpinButton in case of a notebook in wxUniv)
wxWindow *source = wxStaticCast(event.GetEventObject(), wxWindow); wxWindow *source = wxStaticCast(event.GetEventObject(), wxWindow);
while ( source && source != this && source->GetParent() != this ) while ( source && source != this && source->GetParent() != this )
{ {
source = source->GetParent(); source = source->GetParent();
} }
if ( source && m_pages.Index(source) == wxNOT_FOUND ) if ( source && m_pages.Index(source) == wxNOT_FOUND )
{ {
// this event is for the book control itself, redirect it to the // this event is for the book control itself, redirect it to the
// corresponding page // corresponding page
wxWindow *page = NULL; wxWindow *page = NULL;
if ( event.GetOrigin() == wxHelpEvent::Origin_HelpButton ) if ( event.GetOrigin() == wxHelpEvent::Origin_HelpButton )
{ {
// show help for the page under the mouse // show help for the page under the mouse
const int pagePos = HitTest(ScreenToClient(event.GetPosition())); const int pagePos = HitTest(ScreenToClient(event.GetPosition()));
if ( pagePos != wxNOT_FOUND) if ( pagePos != wxNOT_FOUND)
{ {
page = GetPage((size_t)pagePos); page = GetPage((size_t)pagePos);
} }
} }
else // event from keyboard or unknown source else // event from keyboard or unknown source
{ {
// otherwise show the current page help // otherwise show the current page help
page = GetCurrentPage(); page = GetCurrentPage();
} }
if ( page ) if ( page )
{ {
// change event object to the page to avoid infinite recursion if // change event object to the page to avoid infinite recursion if
// we get this event ourselves if the page doesn't handle it // we get this event ourselves if the page doesn't handle it
event.SetEventObject(page); event.SetEventObject(page);
if ( page->GetEventHandler()->ProcessEvent(event) ) if ( page->GetEventHandler()->ProcessEvent(event) )
{ {
// don't call event.Skip() // don't call event.Skip()
return; return;
} }
} }
} }
//else: event coming from one of our pages already //else: event coming from one of our pages already
event.Skip(); event.Skip();
} }
#endif // wxUSE_HELP #endif // wxUSE_HELP
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// pages management // pages management
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool bool
wxBookCtrlBase::InsertPage(size_t nPage, wxBookCtrlBase::InsertPage(size_t nPage,
wxWindow *page, wxWindow *page,
const wxString& WXUNUSED(text), const wxString& WXUNUSED(text),
bool WXUNUSED(bSelect), bool WXUNUSED(bSelect),
int WXUNUSED(imageId)) int WXUNUSED(imageId))
{ {
wxCHECK_MSG( page || AllowNullPage(), false, wxCHECK_MSG( page || AllowNullPage(), false,
_T("NULL page in wxBookCtrlBase::InsertPage()") ); _T("NULL page in wxBookCtrlBase::InsertPage()") );
wxCHECK_MSG( nPage <= m_pages.size(), false, wxCHECK_MSG( nPage <= m_pages.size(), false,
_T("invalid page index in wxBookCtrlBase::InsertPage()") ); _T("invalid page index in wxBookCtrlBase::InsertPage()") );
m_pages.Insert(page, nPage); m_pages.Insert(page, nPage);
if ( page ) if ( page )
page->SetSize(GetPageRect()); page->SetSize(GetPageRect());
DoInvalidateBestSize(); DoInvalidateBestSize();
return true; return true;
} }
bool wxBookCtrlBase::DeletePage(size_t nPage) bool wxBookCtrlBase::DeletePage(size_t nPage)
{ {
wxWindow *page = DoRemovePage(nPage); wxWindow *page = DoRemovePage(nPage);
if ( !(page || AllowNullPage()) ) if ( !(page || AllowNullPage()) )
return false; return false;
// delete NULL is harmless // delete NULL is harmless
delete page; delete page;
return true; return true;
} }
wxWindow *wxBookCtrlBase::DoRemovePage(size_t nPage) wxWindow *wxBookCtrlBase::DoRemovePage(size_t nPage)
{ {
wxCHECK_MSG( nPage < m_pages.size(), NULL, wxCHECK_MSG( nPage < m_pages.size(), NULL,
_T("invalid page index in wxBookCtrlBase::DoRemovePage()") ); _T("invalid page index in wxBookCtrlBase::DoRemovePage()") );
wxWindow *pageRemoved = m_pages[nPage]; wxWindow *pageRemoved = m_pages[nPage];
m_pages.RemoveAt(nPage); m_pages.RemoveAt(nPage);
DoInvalidateBestSize(); DoInvalidateBestSize();
return pageRemoved; return pageRemoved;
} }
int wxBookCtrlBase::GetNextPage(bool forward) const int wxBookCtrlBase::GetNextPage(bool forward) const
{ {
int nPage; int nPage;
int nMax = GetPageCount(); int nMax = GetPageCount();
if ( nMax-- ) // decrement it to get the last valid index if ( nMax-- ) // decrement it to get the last valid index
{ {
int nSel = GetSelection(); int nSel = GetSelection();
// change selection wrapping if it becomes invalid // change selection wrapping if it becomes invalid
nPage = forward ? nSel == nMax ? 0 nPage = forward ? nSel == nMax ? 0
: nSel + 1 : nSel + 1
: nSel == 0 ? nMax : nSel == 0 ? nMax
: nSel - 1; : nSel - 1;
} }
else // notebook is empty, no next page else // notebook is empty, no next page
{ {
nPage = wxNOT_FOUND; nPage = wxNOT_FOUND;
} }
return nPage; return nPage;
} }
int wxBookCtrlBase::DoSetSelection(size_t n, int flags) int wxBookCtrlBase::DoSetSelection(size_t n, int flags)
{ {
wxCHECK_MSG( n < GetPageCount(), wxNOT_FOUND, wxCHECK_MSG( n < GetPageCount(), wxNOT_FOUND,
wxT("invalid page index in wxBookCtrlBase::DoSetSelection()") ); wxT("invalid page index in wxBookCtrlBase::DoSetSelection()") );
const int oldSel = GetSelection(); const int oldSel = GetSelection();
if ( n != (size_t)oldSel ) if ( n != (size_t)oldSel )
{ {
wxBookCtrlBaseEvent *event = CreatePageChangingEvent(); wxBookCtrlBaseEvent *event = CreatePageChangingEvent();
bool allowed = false; bool allowed = false;
if ( flags & SetSelection_SendEvent ) if ( flags & SetSelection_SendEvent )
{ {
event->SetSelection(n); event->SetSelection(n);
event->SetOldSelection(oldSel); event->SetOldSelection(oldSel);
event->SetEventObject(this); event->SetEventObject(this);
allowed = !GetEventHandler()->ProcessEvent(*event) || event->IsAllowed(); allowed = !GetEventHandler()->ProcessEvent(*event) || event->IsAllowed();
} }
if ( !(flags & SetSelection_SendEvent) || allowed) if ( !(flags & SetSelection_SendEvent) || allowed)
{ {
if ( oldSel != wxNOT_FOUND ) if ( oldSel != wxNOT_FOUND )
m_pages[oldSel]->Hide(); m_pages[oldSel]->Hide();
wxWindow *page = m_pages[n]; wxWindow *page = m_pages[n];
page->SetSize(GetPageRect()); page->SetSize(GetPageRect());
page->Show(); page->Show();
// change selection now to ignore the selection change event // change selection now to ignore the selection change event
UpdateSelectedPage(n); UpdateSelectedPage(n);
if ( flags & SetSelection_SendEvent ) if ( flags & SetSelection_SendEvent )
{ {
// program allows the page change // program allows the page change
MakeChangedEvent(*event); MakeChangedEvent(*event);
(void)GetEventHandler()->ProcessEvent(*event); (void)GetEventHandler()->ProcessEvent(*event);
} }
} }
delete event; delete event;
} }
return oldSel; return oldSel;
} }
#endif // wxUSE_BOOKCTRL #endif // wxUSE_BOOKCTRL

View File

@ -1,55 +1,55 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/choiccmn.cpp // Name: src/common/choiccmn.cpp
// Purpose: common (to all ports) wxChoice functions // Purpose: common (to all ports) wxChoice functions
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 26.07.99 // Created: 26.07.99
// RCS-ID: $Id: choiccmn.cpp 39470 2006-05-30 07:34:30Z ABX $ // RCS-ID: $Id: choiccmn.cpp 39470 2006-05-30 07:34:30Z ABX $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_CHOICE #if wxUSE_CHOICE
#include "wx/choice.h" #include "wx/choice.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif #endif
const wxChar wxChoiceNameStr[] = wxT("choice"); const wxChar wxChoiceNameStr[] = wxT("choice");
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
wxChoiceBase::~wxChoiceBase() wxChoiceBase::~wxChoiceBase()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// misc // misc
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxChoiceBase::Command(wxCommandEvent& event) void wxChoiceBase::Command(wxCommandEvent& event)
{ {
SetSelection(event.GetInt()); SetSelection(event.GetInt());
(void)ProcessEvent(event); (void)ProcessEvent(event);
} }
#endif // wxUSE_CHOICE #endif // wxUSE_CHOICE

View File

@ -1,63 +1,63 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/clipcmn.cpp // Name: src/common/clipcmn.cpp
// Purpose: common (to all ports) wxClipboard functions // Purpose: common (to all ports) wxClipboard functions
// Author: Robert Roebling // Author: Robert Roebling
// Modified by: // Modified by:
// Created: 28.06.99 // Created: 28.06.99
// RCS-ID: $Id: clipcmn.cpp 40943 2006-08-31 19:31:43Z ABX $ // RCS-ID: $Id: clipcmn.cpp 40943 2006-08-31 19:31:43Z ABX $
// Copyright: (c) Robert Roebling // Copyright: (c) Robert Roebling
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_CLIPBOARD #if wxUSE_CLIPBOARD
#include "wx/clipbrd.h" #include "wx/clipbrd.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/module.h" #include "wx/module.h"
#endif #endif
static wxClipboard *gs_clipboard = NULL; static wxClipboard *gs_clipboard = NULL;
/*static*/ wxClipboard *wxClipboardBase::Get() /*static*/ wxClipboard *wxClipboardBase::Get()
{ {
if ( !gs_clipboard ) if ( !gs_clipboard )
{ {
gs_clipboard = new wxClipboard; gs_clipboard = new wxClipboard;
} }
return gs_clipboard; return gs_clipboard;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxClipboardModule: module responsible for destroying the global clipboard // wxClipboardModule: module responsible for destroying the global clipboard
// object // object
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxClipboardModule : public wxModule class wxClipboardModule : public wxModule
{ {
public: public:
bool OnInit() { return true; } bool OnInit() { return true; }
void OnExit() { wxDELETE(gs_clipboard); } void OnExit() { wxDELETE(gs_clipboard); }
private: private:
DECLARE_DYNAMIC_CLASS(wxClipboardModule) DECLARE_DYNAMIC_CLASS(wxClipboardModule)
}; };
IMPLEMENT_DYNAMIC_CLASS(wxClipboardModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxClipboardModule, wxModule)
#endif // wxUSE_CLIPBOARD #endif // wxUSE_CLIPBOARD

View File

@ -1,83 +1,83 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: common/clntdata.cpp // Name: common/clntdata.cpp
// Purpose: A mixin class for holding a wxClientData or void pointer // Purpose: A mixin class for holding a wxClientData or void pointer
// Author: Robin Dunn // Author: Robin Dunn
// Modified by: // Modified by:
// Created: 9-Oct-2001 // Created: 9-Oct-2001
// RCS-ID: $Id: clntdata.cpp 35650 2005-09-23 12:56:45Z MR $ // RCS-ID: $Id: clntdata.cpp 35650 2005-09-23 12:56:45Z MR $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/clntdata.h" #include "wx/clntdata.h"
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxClientDataContainer::wxClientDataContainer() wxClientDataContainer::wxClientDataContainer()
{ {
// no client data (yet) // no client data (yet)
m_clientData = NULL; m_clientData = NULL;
m_clientDataType = wxClientData_None; m_clientDataType = wxClientData_None;
} }
wxClientDataContainer::~wxClientDataContainer() wxClientDataContainer::~wxClientDataContainer()
{ {
// we only delete object data, not untyped // we only delete object data, not untyped
if ( m_clientDataType == wxClientData_Object ) if ( m_clientDataType == wxClientData_Object )
delete m_clientObject; delete m_clientObject;
} }
void wxClientDataContainer::DoSetClientObject( wxClientData *data ) void wxClientDataContainer::DoSetClientObject( wxClientData *data )
{ {
wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxASSERT_MSG( m_clientDataType != wxClientData_Void,
wxT("can't have both object and void client data") ); wxT("can't have both object and void client data") );
if ( m_clientObject ) if ( m_clientObject )
delete m_clientObject; delete m_clientObject;
m_clientObject = data; m_clientObject = data;
m_clientDataType = wxClientData_Object; m_clientDataType = wxClientData_Object;
} }
wxClientData *wxClientDataContainer::DoGetClientObject() const wxClientData *wxClientDataContainer::DoGetClientObject() const
{ {
// it's not an error to call GetClientObject() on a window which doesn't // it's not an error to call GetClientObject() on a window which doesn't
// have client data at all - NULL will be returned // have client data at all - NULL will be returned
wxASSERT_MSG( m_clientDataType != wxClientData_Void, wxASSERT_MSG( m_clientDataType != wxClientData_Void,
wxT("this window doesn't have object client data") ); wxT("this window doesn't have object client data") );
return m_clientObject; return m_clientObject;
} }
void wxClientDataContainer::DoSetClientData( void *data ) void wxClientDataContainer::DoSetClientData( void *data )
{ {
wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxASSERT_MSG( m_clientDataType != wxClientData_Object,
wxT("can't have both object and void client data") ); wxT("can't have both object and void client data") );
m_clientData = data; m_clientData = data;
m_clientDataType = wxClientData_Void; m_clientDataType = wxClientData_Void;
} }
void *wxClientDataContainer::DoGetClientData() const void *wxClientDataContainer::DoGetClientData() const
{ {
// it's not an error to call GetClientData() on a window which doesn't have // it's not an error to call GetClientData() on a window which doesn't have
// client data at all - NULL will be returned // client data at all - NULL will be returned
wxASSERT_MSG( m_clientDataType != wxClientData_Object, wxASSERT_MSG( m_clientDataType != wxClientData_Object,
wxT("this window doesn't have void client data") ); wxT("this window doesn't have void client data") );
return m_clientData; return m_clientData;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------

View File

@ -1,149 +1,149 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/clrpickercmn.cpp // Name: src/common/clrpickercmn.cpp
// Purpose: wxColourPickerCtrl class implementation // Purpose: wxColourPickerCtrl class implementation
// Author: Francesco Montorsi (readapted code written by Vadim Zeitlin) // Author: Francesco Montorsi (readapted code written by Vadim Zeitlin)
// Modified by: // Modified by:
// Created: 15/04/2006 // Created: 15/04/2006
// RCS-ID: $Id: clrpickercmn.cpp 42219 2006-10-21 19:53:05Z PC $ // RCS-ID: $Id: clrpickercmn.cpp 42219 2006-10-21 19:53:05Z PC $
// Copyright: (c) Vadim Zeitlin, Francesco Montorsi // Copyright: (c) Vadim Zeitlin, Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_COLOURPICKERCTRL #if wxUSE_COLOURPICKERCTRL
#include "wx/clrpicker.h" #include "wx/clrpicker.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/textctrl.h" #include "wx/textctrl.h"
#endif #endif
const wxChar wxColourPickerCtrlNameStr[] = wxT("colourpicker"); const wxChar wxColourPickerCtrlNameStr[] = wxT("colourpicker");
const wxChar wxColourPickerWidgetNameStr[] = wxT("colourpickerwidget"); const wxChar wxColourPickerWidgetNameStr[] = wxT("colourpickerwidget");
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
DEFINE_EVENT_TYPE(wxEVT_COMMAND_COLOURPICKER_CHANGED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_COLOURPICKER_CHANGED)
IMPLEMENT_DYNAMIC_CLASS(wxColourPickerCtrl, wxPickerBase) IMPLEMENT_DYNAMIC_CLASS(wxColourPickerCtrl, wxPickerBase)
IMPLEMENT_DYNAMIC_CLASS(wxColourPickerEvent, wxEvent) IMPLEMENT_DYNAMIC_CLASS(wxColourPickerEvent, wxEvent)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxColourPickerCtrl // wxColourPickerCtrl
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#define M_PICKER ((wxColourPickerWidget*)m_picker) #define M_PICKER ((wxColourPickerWidget*)m_picker)
bool wxColourPickerCtrl::Create( wxWindow *parent, wxWindowID id, bool wxColourPickerCtrl::Create( wxWindow *parent, wxWindowID id,
const wxColour &col, const wxColour &col,
const wxPoint &pos, const wxSize &size, const wxPoint &pos, const wxSize &size,
long style, const wxValidator& validator, long style, const wxValidator& validator,
const wxString &name ) const wxString &name )
{ {
if (!wxPickerBase::CreateBase(parent, id, col.GetAsString(), pos, size, if (!wxPickerBase::CreateBase(parent, id, col.GetAsString(), pos, size,
style, validator, name)) style, validator, name))
return false; return false;
// we are not interested to the ID of our picker as we connect // we are not interested to the ID of our picker as we connect
// to its "changed" event dynamically... // to its "changed" event dynamically...
m_picker = new wxColourPickerWidget(this, wxID_ANY, col, m_picker = new wxColourPickerWidget(this, wxID_ANY, col,
wxDefaultPosition, wxDefaultSize, wxDefaultPosition, wxDefaultSize,
GetPickerStyle(style)); GetPickerStyle(style));
// complete sizer creation // complete sizer creation
wxPickerBase::PostCreation(); wxPickerBase::PostCreation();
m_picker->Connect(wxEVT_COMMAND_COLOURPICKER_CHANGED, m_picker->Connect(wxEVT_COMMAND_COLOURPICKER_CHANGED,
wxColourPickerEventHandler(wxColourPickerCtrl::OnColourChange), wxColourPickerEventHandler(wxColourPickerCtrl::OnColourChange),
NULL, this); NULL, this);
return true; return true;
} }
void wxColourPickerCtrl::SetColour(const wxColour &col) void wxColourPickerCtrl::SetColour(const wxColour &col)
{ {
M_PICKER->SetColour(col); M_PICKER->SetColour(col);
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
} }
bool wxColourPickerCtrl::SetColour(const wxString &text) bool wxColourPickerCtrl::SetColour(const wxString &text)
{ {
wxColour col(text); // smart wxString->wxColour conversion wxColour col(text); // smart wxString->wxColour conversion
if ( !col.Ok() ) if ( !col.Ok() )
return false; return false;
M_PICKER->SetColour(col); M_PICKER->SetColour(col);
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
return true; return true;
} }
void wxColourPickerCtrl::UpdatePickerFromTextCtrl() void wxColourPickerCtrl::UpdatePickerFromTextCtrl()
{ {
wxASSERT(m_text); wxASSERT(m_text);
if (m_bIgnoreNextTextCtrlUpdate) if (m_bIgnoreNextTextCtrlUpdate)
{ {
// ignore this update // ignore this update
m_bIgnoreNextTextCtrlUpdate = false; m_bIgnoreNextTextCtrlUpdate = false;
return; return;
} }
// wxString -> wxColour conversion // wxString -> wxColour conversion
wxColour col(m_text->GetValue()); wxColour col(m_text->GetValue());
if ( !col.Ok() ) if ( !col.Ok() )
return; // invalid user input return; // invalid user input
if (M_PICKER->GetColour() != col) if (M_PICKER->GetColour() != col)
{ {
M_PICKER->SetColour(col); M_PICKER->SetColour(col);
// fire an event // fire an event
wxColourPickerEvent event(this, GetId(), col); wxColourPickerEvent event(this, GetId(), col);
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
} }
void wxColourPickerCtrl::UpdateTextCtrlFromPicker() void wxColourPickerCtrl::UpdateTextCtrlFromPicker()
{ {
if (!m_text) if (!m_text)
return; // no textctrl to update return; // no textctrl to update
// NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED // NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED
// which will trigger a unneeded UpdateFromTextCtrl(); thus before using // which will trigger a unneeded UpdateFromTextCtrl(); thus before using
// SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag... // SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag...
m_bIgnoreNextTextCtrlUpdate = true; m_bIgnoreNextTextCtrlUpdate = true;
m_text->SetValue(M_PICKER->GetColour().GetAsString()); m_text->SetValue(M_PICKER->GetColour().GetAsString());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxColourPickerCtrl - event handlers // wxColourPickerCtrl - event handlers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxColourPickerCtrl::OnColourChange(wxColourPickerEvent &ev) void wxColourPickerCtrl::OnColourChange(wxColourPickerEvent &ev)
{ {
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
// the wxColourPickerWidget sent us a colour-change notification. // the wxColourPickerWidget sent us a colour-change notification.
// forward this event to our parent // forward this event to our parent
wxColourPickerEvent event(this, GetId(), ev.GetColour()); wxColourPickerEvent event(this, GetId(), ev.GetColour());
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
#endif // wxUSE_COLOURPICKERCTRL #endif // wxUSE_COLOURPICKERCTRL

File diff suppressed because it is too large Load Diff

View File

@ -1,325 +1,325 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/cmdproc.cpp // Name: src/common/cmdproc.cpp
// Purpose: wxCommand and wxCommandProcessor classes // Purpose: wxCommand and wxCommandProcessor classes
// Author: Julian Smart (extracted from docview.h by VZ) // Author: Julian Smart (extracted from docview.h by VZ)
// Modified by: // Modified by:
// Created: 05.11.00 // Created: 05.11.00
// RCS-ID: $Id: cmdproc.cpp 35650 2005-09-23 12:56:45Z MR $ // RCS-ID: $Id: cmdproc.cpp 35650 2005-09-23 12:56:45Z MR $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/string.h" #include "wx/string.h"
#include "wx/menu.h" #include "wx/menu.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
#include "wx/cmdproc.h" #include "wx/cmdproc.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
IMPLEMENT_CLASS(wxCommand, wxObject) IMPLEMENT_CLASS(wxCommand, wxObject)
IMPLEMENT_DYNAMIC_CLASS(wxCommandProcessor, wxObject) IMPLEMENT_DYNAMIC_CLASS(wxCommandProcessor, wxObject)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxCommand // wxCommand
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxCommand::wxCommand(bool canUndoIt, const wxString& name) wxCommand::wxCommand(bool canUndoIt, const wxString& name)
{ {
m_canUndo = canUndoIt; m_canUndo = canUndoIt;
m_commandName = name; m_commandName = name;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Command processor // Command processor
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxCommandProcessor::wxCommandProcessor(int maxCommands) wxCommandProcessor::wxCommandProcessor(int maxCommands)
{ {
m_maxNoCommands = maxCommands; m_maxNoCommands = maxCommands;
#if wxUSE_MENUS #if wxUSE_MENUS
m_commandEditMenu = (wxMenu *) NULL; m_commandEditMenu = (wxMenu *) NULL;
#endif // wxUSE_MENUS #endif // wxUSE_MENUS
m_undoAccelerator = wxT("\tCtrl+Z"); m_undoAccelerator = wxT("\tCtrl+Z");
m_redoAccelerator = wxT("\tCtrl+Y"); m_redoAccelerator = wxT("\tCtrl+Y");
m_lastSavedCommand = m_lastSavedCommand =
m_currentCommand = wxList::compatibility_iterator(); m_currentCommand = wxList::compatibility_iterator();
} }
wxCommandProcessor::~wxCommandProcessor() wxCommandProcessor::~wxCommandProcessor()
{ {
ClearCommands(); ClearCommands();
} }
bool wxCommandProcessor::DoCommand(wxCommand& cmd) bool wxCommandProcessor::DoCommand(wxCommand& cmd)
{ {
return cmd.Do(); return cmd.Do();
} }
bool wxCommandProcessor::UndoCommand(wxCommand& cmd) bool wxCommandProcessor::UndoCommand(wxCommand& cmd)
{ {
return cmd.Undo(); return cmd.Undo();
} }
// Pass a command to the processor. The processor calls Do(); // Pass a command to the processor. The processor calls Do();
// if successful, is appended to the command history unless // if successful, is appended to the command history unless
// storeIt is false. // storeIt is false.
bool wxCommandProcessor::Submit(wxCommand *command, bool storeIt) bool wxCommandProcessor::Submit(wxCommand *command, bool storeIt)
{ {
wxCHECK_MSG( command, false, _T("no command in wxCommandProcessor::Submit") ); wxCHECK_MSG( command, false, _T("no command in wxCommandProcessor::Submit") );
if ( !DoCommand(*command) ) if ( !DoCommand(*command) )
{ {
// the user code expects the command to be deleted anyhow // the user code expects the command to be deleted anyhow
delete command; delete command;
return false; return false;
} }
if ( storeIt ) if ( storeIt )
Store(command); Store(command);
else else
delete command; delete command;
return true; return true;
} }
void wxCommandProcessor::Store(wxCommand *command) void wxCommandProcessor::Store(wxCommand *command)
{ {
wxCHECK_RET( command, _T("no command in wxCommandProcessor::Store") ); wxCHECK_RET( command, _T("no command in wxCommandProcessor::Store") );
if ( (int)m_commands.GetCount() == m_maxNoCommands ) if ( (int)m_commands.GetCount() == m_maxNoCommands )
{ {
wxList::compatibility_iterator firstNode = m_commands.GetFirst(); wxList::compatibility_iterator firstNode = m_commands.GetFirst();
wxCommand *firstCommand = (wxCommand *)firstNode->GetData(); wxCommand *firstCommand = (wxCommand *)firstNode->GetData();
delete firstCommand; delete firstCommand;
m_commands.Erase(firstNode); m_commands.Erase(firstNode);
// Make sure m_lastSavedCommand won't point to freed memory // Make sure m_lastSavedCommand won't point to freed memory
if ( m_lastSavedCommand == firstNode ) if ( m_lastSavedCommand == firstNode )
m_lastSavedCommand = wxList::compatibility_iterator(); m_lastSavedCommand = wxList::compatibility_iterator();
} }
// Correct a bug: we must chop off the current 'branch' // Correct a bug: we must chop off the current 'branch'
// so that we're at the end of the command list. // so that we're at the end of the command list.
if (!m_currentCommand) if (!m_currentCommand)
ClearCommands(); ClearCommands();
else else
{ {
wxList::compatibility_iterator node = m_currentCommand->GetNext(); wxList::compatibility_iterator node = m_currentCommand->GetNext();
while (node) while (node)
{ {
wxList::compatibility_iterator next = node->GetNext(); wxList::compatibility_iterator next = node->GetNext();
delete (wxCommand *)node->GetData(); delete (wxCommand *)node->GetData();
m_commands.Erase(node); m_commands.Erase(node);
// Make sure m_lastSavedCommand won't point to freed memory // Make sure m_lastSavedCommand won't point to freed memory
if ( m_lastSavedCommand == node ) if ( m_lastSavedCommand == node )
m_lastSavedCommand = wxList::compatibility_iterator(); m_lastSavedCommand = wxList::compatibility_iterator();
node = next; node = next;
} }
} }
m_commands.Append(command); m_commands.Append(command);
m_currentCommand = m_commands.GetLast(); m_currentCommand = m_commands.GetLast();
SetMenuStrings(); SetMenuStrings();
} }
bool wxCommandProcessor::Undo() bool wxCommandProcessor::Undo()
{ {
wxCommand *command = GetCurrentCommand(); wxCommand *command = GetCurrentCommand();
if ( command && command->CanUndo() ) if ( command && command->CanUndo() )
{ {
if ( UndoCommand(*command) ) if ( UndoCommand(*command) )
{ {
m_currentCommand = m_currentCommand->GetPrevious(); m_currentCommand = m_currentCommand->GetPrevious();
SetMenuStrings(); SetMenuStrings();
return true; return true;
} }
} }
return false; return false;
} }
bool wxCommandProcessor::Redo() bool wxCommandProcessor::Redo()
{ {
wxCommand *redoCommand = (wxCommand *) NULL; wxCommand *redoCommand = (wxCommand *) NULL;
wxList::compatibility_iterator redoNode wxList::compatibility_iterator redoNode
#if !wxUSE_STL #if !wxUSE_STL
= NULL // just to avoid warnings = NULL // just to avoid warnings
#endif // !wxUSE_STL #endif // !wxUSE_STL
; ;
if ( m_currentCommand ) if ( m_currentCommand )
{ {
// is there anything to redo? // is there anything to redo?
if ( m_currentCommand->GetNext() ) if ( m_currentCommand->GetNext() )
{ {
redoCommand = (wxCommand *)m_currentCommand->GetNext()->GetData(); redoCommand = (wxCommand *)m_currentCommand->GetNext()->GetData();
redoNode = m_currentCommand->GetNext(); redoNode = m_currentCommand->GetNext();
} }
} }
else // no current command, redo the first one else // no current command, redo the first one
{ {
if (m_commands.GetCount() > 0) if (m_commands.GetCount() > 0)
{ {
redoCommand = (wxCommand *)m_commands.GetFirst()->GetData(); redoCommand = (wxCommand *)m_commands.GetFirst()->GetData();
redoNode = m_commands.GetFirst(); redoNode = m_commands.GetFirst();
} }
} }
if (redoCommand) if (redoCommand)
{ {
bool success = DoCommand(*redoCommand); bool success = DoCommand(*redoCommand);
if (success) if (success)
{ {
m_currentCommand = redoNode; m_currentCommand = redoNode;
SetMenuStrings(); SetMenuStrings();
return true; return true;
} }
} }
return false; return false;
} }
bool wxCommandProcessor::CanUndo() const bool wxCommandProcessor::CanUndo() const
{ {
wxCommand *command = GetCurrentCommand(); wxCommand *command = GetCurrentCommand();
return command && command->CanUndo(); return command && command->CanUndo();
} }
bool wxCommandProcessor::CanRedo() const bool wxCommandProcessor::CanRedo() const
{ {
if (m_currentCommand && !m_currentCommand->GetNext()) if (m_currentCommand && !m_currentCommand->GetNext())
return false; return false;
if (m_currentCommand && m_currentCommand->GetNext()) if (m_currentCommand && m_currentCommand->GetNext())
return true; return true;
if (!m_currentCommand && (m_commands.GetCount() > 0)) if (!m_currentCommand && (m_commands.GetCount() > 0))
return true; return true;
return false; return false;
} }
void wxCommandProcessor::Initialize() void wxCommandProcessor::Initialize()
{ {
m_currentCommand = m_commands.GetLast(); m_currentCommand = m_commands.GetLast();
SetMenuStrings(); SetMenuStrings();
} }
void wxCommandProcessor::SetMenuStrings() void wxCommandProcessor::SetMenuStrings()
{ {
#if wxUSE_MENUS #if wxUSE_MENUS
if (m_commandEditMenu) if (m_commandEditMenu)
{ {
wxString undoLabel = GetUndoMenuLabel(); wxString undoLabel = GetUndoMenuLabel();
wxString redoLabel = GetRedoMenuLabel(); wxString redoLabel = GetRedoMenuLabel();
m_commandEditMenu->SetLabel(wxID_UNDO, undoLabel); m_commandEditMenu->SetLabel(wxID_UNDO, undoLabel);
m_commandEditMenu->Enable(wxID_UNDO, CanUndo()); m_commandEditMenu->Enable(wxID_UNDO, CanUndo());
m_commandEditMenu->SetLabel(wxID_REDO, redoLabel); m_commandEditMenu->SetLabel(wxID_REDO, redoLabel);
m_commandEditMenu->Enable(wxID_REDO, CanRedo()); m_commandEditMenu->Enable(wxID_REDO, CanRedo());
} }
#endif // wxUSE_MENUS #endif // wxUSE_MENUS
} }
// Gets the current Undo menu label. // Gets the current Undo menu label.
wxString wxCommandProcessor::GetUndoMenuLabel() const wxString wxCommandProcessor::GetUndoMenuLabel() const
{ {
wxString buf; wxString buf;
if (m_currentCommand) if (m_currentCommand)
{ {
wxCommand *command = (wxCommand *)m_currentCommand->GetData(); wxCommand *command = (wxCommand *)m_currentCommand->GetData();
wxString commandName(command->GetName()); wxString commandName(command->GetName());
if (commandName.empty()) commandName = _("Unnamed command"); if (commandName.empty()) commandName = _("Unnamed command");
bool canUndo = command->CanUndo(); bool canUndo = command->CanUndo();
if (canUndo) if (canUndo)
buf = wxString(_("&Undo ")) + commandName + m_undoAccelerator; buf = wxString(_("&Undo ")) + commandName + m_undoAccelerator;
else else
buf = wxString(_("Can't &Undo ")) + commandName + m_undoAccelerator; buf = wxString(_("Can't &Undo ")) + commandName + m_undoAccelerator;
} }
else else
{ {
buf = _("&Undo") + m_undoAccelerator; buf = _("&Undo") + m_undoAccelerator;
} }
return buf; return buf;
} }
// Gets the current Undo menu label. // Gets the current Undo menu label.
wxString wxCommandProcessor::GetRedoMenuLabel() const wxString wxCommandProcessor::GetRedoMenuLabel() const
{ {
wxString buf; wxString buf;
if (m_currentCommand) if (m_currentCommand)
{ {
// We can redo, if we're not at the end of the history. // We can redo, if we're not at the end of the history.
if (m_currentCommand->GetNext()) if (m_currentCommand->GetNext())
{ {
wxCommand *redoCommand = (wxCommand *)m_currentCommand->GetNext()->GetData(); wxCommand *redoCommand = (wxCommand *)m_currentCommand->GetNext()->GetData();
wxString redoCommandName(redoCommand->GetName()); wxString redoCommandName(redoCommand->GetName());
if (redoCommandName.empty()) redoCommandName = _("Unnamed command"); if (redoCommandName.empty()) redoCommandName = _("Unnamed command");
buf = wxString(_("&Redo ")) + redoCommandName + m_redoAccelerator; buf = wxString(_("&Redo ")) + redoCommandName + m_redoAccelerator;
} }
else else
{ {
buf = _("&Redo") + m_redoAccelerator; buf = _("&Redo") + m_redoAccelerator;
} }
} }
else else
{ {
if (m_commands.GetCount() == 0) if (m_commands.GetCount() == 0)
{ {
buf = _("&Redo") + m_redoAccelerator; buf = _("&Redo") + m_redoAccelerator;
} }
else else
{ {
// currentCommand is NULL but there are commands: this means that // currentCommand is NULL but there are commands: this means that
// we've undone to the start of the list, but can redo the first. // we've undone to the start of the list, but can redo the first.
wxCommand *redoCommand = (wxCommand *)m_commands.GetFirst()->GetData(); wxCommand *redoCommand = (wxCommand *)m_commands.GetFirst()->GetData();
wxString redoCommandName(redoCommand->GetName()); wxString redoCommandName(redoCommand->GetName());
if (redoCommandName.empty()) redoCommandName = _("Unnamed command"); if (redoCommandName.empty()) redoCommandName = _("Unnamed command");
buf = wxString(_("&Redo ")) + redoCommandName + m_redoAccelerator; buf = wxString(_("&Redo ")) + redoCommandName + m_redoAccelerator;
} }
} }
return buf; return buf;
} }
void wxCommandProcessor::ClearCommands() void wxCommandProcessor::ClearCommands()
{ {
wxList::compatibility_iterator node = m_commands.GetFirst(); wxList::compatibility_iterator node = m_commands.GetFirst();
while (node) while (node)
{ {
wxCommand *command = (wxCommand *)node->GetData(); wxCommand *command = (wxCommand *)node->GetData();
delete command; delete command;
m_commands.Erase(node); m_commands.Erase(node);
node = m_commands.GetFirst(); node = m_commands.GetFirst();
} }
m_currentCommand = wxList::compatibility_iterator(); m_currentCommand = wxList::compatibility_iterator();
m_lastSavedCommand = wxList::compatibility_iterator(); m_lastSavedCommand = wxList::compatibility_iterator();
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,126 +1,126 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/colourcmn.cpp // Name: src/common/colourcmn.cpp
// Purpose: wxColourBase implementation // Purpose: wxColourBase implementation
// Author: Francesco Montorsi // Author: Francesco Montorsi
// Modified by: // Modified by:
// Created: 20/4/2006 // Created: 20/4/2006
// RCS-ID: $Id: colourcmn.cpp 41538 2006-09-30 20:45:15Z RR $ // RCS-ID: $Id: colourcmn.cpp 41538 2006-09-30 20:45:15Z RR $
// Copyright: (c) Francesco Montorsi // Copyright: (c) Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/colour.h" #include "wx/colour.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/log.h" #include "wx/log.h"
#include "wx/utils.h" #include "wx/utils.h"
#include "wx/gdicmn.h" #include "wx/gdicmn.h"
#endif #endif
#if wxUSE_VARIANT #if wxUSE_VARIANT
IMPLEMENT_VARIANT_OBJECT_EXPORTED(wxColour,WXDLLEXPORT) IMPLEMENT_VARIANT_OBJECT_EXPORTED(wxColour,WXDLLEXPORT)
#endif #endif
// ============================================================================ // ============================================================================
// wxString <-> wxColour conversions // wxString <-> wxColour conversions
// ============================================================================ // ============================================================================
bool wxColourBase::FromString(const wxChar *str) bool wxColourBase::FromString(const wxChar *str)
{ {
if ( str == NULL || str[0] == wxT('\0')) if ( str == NULL || str[0] == wxT('\0'))
return false; // invalid or empty string return false; // invalid or empty string
if ( wxStrncmp(str, wxT("RGB"), 3) == 0 || if ( wxStrncmp(str, wxT("RGB"), 3) == 0 ||
wxStrncmp(str, wxT("rgb"), 3) == 0 ) wxStrncmp(str, wxT("rgb"), 3) == 0 )
{ {
// CSS-like RGB specification // CSS-like RGB specification
// according to http://www.w3.org/TR/REC-CSS2/syndata.html#color-units // according to http://www.w3.org/TR/REC-CSS2/syndata.html#color-units
// values outside 0-255 range are allowed but should be clipped // values outside 0-255 range are allowed but should be clipped
int red, green, blue; int red, green, blue;
if (wxSscanf(&str[3], wxT("(%d, %d, %d)"), &red, &green, &blue) != 3) if (wxSscanf(&str[3], wxT("(%d, %d, %d)"), &red, &green, &blue) != 3)
return false; return false;
Set((unsigned char)wxClip(red,0,255), Set((unsigned char)wxClip(red,0,255),
(unsigned char)wxClip(green,0,255), (unsigned char)wxClip(green,0,255),
(unsigned char)wxClip(blue,0,255)); (unsigned char)wxClip(blue,0,255));
} }
else if ( str[0] == wxT('#') && wxStrlen(str) == 7 ) else if ( str[0] == wxT('#') && wxStrlen(str) == 7 )
{ {
// hexadecimal prefixed with # (HTML syntax) // hexadecimal prefixed with # (HTML syntax)
unsigned long tmp; unsigned long tmp;
if (wxSscanf(&str[1], wxT("%lx"), &tmp) != 1) if (wxSscanf(&str[1], wxT("%lx"), &tmp) != 1)
return false; return false;
Set((unsigned char)(tmp >> 16), Set((unsigned char)(tmp >> 16),
(unsigned char)(tmp >> 8), (unsigned char)(tmp >> 8),
(unsigned char)tmp); (unsigned char)tmp);
} }
else if (wxTheColourDatabase) // a colour name ? else if (wxTheColourDatabase) // a colour name ?
{ {
// we can't do // we can't do
// *this = wxTheColourDatabase->Find(str) // *this = wxTheColourDatabase->Find(str)
// because this place can be called from constructor // because this place can be called from constructor
// and 'this' could not be available yet // and 'this' could not be available yet
wxColour clr = wxTheColourDatabase->Find(str); wxColour clr = wxTheColourDatabase->Find(str);
if (clr.Ok()) if (clr.Ok())
Set((unsigned char)clr.Red(), Set((unsigned char)clr.Red(),
(unsigned char)clr.Green(), (unsigned char)clr.Green(),
(unsigned char)clr.Blue()); (unsigned char)clr.Blue());
} }
if (Ok()) if (Ok())
return true; return true;
wxLogDebug(wxT("wxColour::Set - couldn't set to colour string '%s'"), str); wxLogDebug(wxT("wxColour::Set - couldn't set to colour string '%s'"), str);
return false; return false;
} }
wxString wxColourBase::GetAsString(long flags) const wxString wxColourBase::GetAsString(long flags) const
{ {
wxString colName; wxString colName;
if (flags & wxC2S_NAME) if (flags & wxC2S_NAME)
colName = wxTheColourDatabase->FindName((const wxColour &)(*this)).MakeLower(); colName = wxTheColourDatabase->FindName((const wxColour &)(*this)).MakeLower();
if ( colName.empty() && (flags & wxC2S_CSS_SYNTAX) ) if ( colName.empty() && (flags & wxC2S_CSS_SYNTAX) )
{ {
// no name for this colour; return it in CSS syntax // no name for this colour; return it in CSS syntax
colName.Printf(wxT("rgb(%d, %d, %d)"), colName.Printf(wxT("rgb(%d, %d, %d)"),
Red(), Green(), Blue()); Red(), Green(), Blue());
} }
else if ( colName.empty() && (flags & wxC2S_HTML_SYNTAX) ) else if ( colName.empty() && (flags & wxC2S_HTML_SYNTAX) )
{ {
// no name for this colour; return it in HTML syntax // no name for this colour; return it in HTML syntax
colName.Printf(wxT("#%02X%02X%02X"), colName.Printf(wxT("#%02X%02X%02X"),
Red(), Green(), Blue()); Red(), Green(), Blue());
} }
// this function always returns a non-empty string // this function always returns a non-empty string
wxASSERT_MSG(!colName.empty(), wxASSERT_MSG(!colName.empty(),
wxT("Invalid wxColour -> wxString conversion flags")); wxT("Invalid wxColour -> wxString conversion flags"));
return colName; return colName;
} }
#if WXWIN_COMPATIBILITY_2_6 #if WXWIN_COMPATIBILITY_2_6
// static // static
wxColour wxColourBase::CreateByName(const wxString& name) wxColour wxColourBase::CreateByName(const wxString& name)
{ {
return wxColour(name); return wxColour(name);
} }
void wxColourBase::InitFromName(const wxString& col) void wxColourBase::InitFromName(const wxString& col)
{ {
Set(col); Set(col);
} }
#endif // WXWIN_COMPATIBILITY_2_6 #endif // WXWIN_COMPATIBILITY_2_6

File diff suppressed because it is too large Load Diff

View File

@ -1,490 +1,490 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/config.cpp // Name: src/common/config.cpp
// Purpose: implementation of wxConfigBase class // Purpose: implementation of wxConfigBase class
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 07.04.98 // Created: 07.04.98
// RCS-ID: $Id: config.cpp 50711 2007-12-15 02:57:58Z VZ $ // RCS-ID: $Id: config.cpp 50711 2007-12-15 02:57:58Z VZ $
// Copyright: (c) 1997 Karsten Ballueder Ballueder@usa.net // Copyright: (c) 1997 Karsten Ballueder Ballueder@usa.net
// Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif //__BORLANDC__ #endif //__BORLANDC__
#ifndef wxUSE_CONFIG_NATIVE #ifndef wxUSE_CONFIG_NATIVE
#define wxUSE_CONFIG_NATIVE 1 #define wxUSE_CONFIG_NATIVE 1
#endif #endif
#include "wx/config.h" #include "wx/config.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/app.h" #include "wx/app.h"
#include "wx/utils.h" #include "wx/utils.h"
#include "wx/arrstr.h" #include "wx/arrstr.h"
#include "wx/math.h" #include "wx/math.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
#if wxUSE_CONFIG && ((wxUSE_FILE && wxUSE_TEXTFILE) || wxUSE_CONFIG_NATIVE) #if wxUSE_CONFIG && ((wxUSE_FILE && wxUSE_TEXTFILE) || wxUSE_CONFIG_NATIVE)
#include "wx/file.h" #include "wx/file.h"
#include <stdlib.h> #include <stdlib.h>
#include <ctype.h> #include <ctype.h>
#include <limits.h> // for INT_MAX #include <limits.h> // for INT_MAX
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// global and class static variables // global and class static variables
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxConfigBase *wxConfigBase::ms_pConfig = NULL; wxConfigBase *wxConfigBase::ms_pConfig = NULL;
bool wxConfigBase::ms_bAutoCreate = true; bool wxConfigBase::ms_bAutoCreate = true;
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxConfigBase // wxConfigBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Not all args will always be used by derived classes, but including them all // Not all args will always be used by derived classes, but including them all
// in each class ensures compatibility. // in each class ensures compatibility.
wxConfigBase::wxConfigBase(const wxString& appName, wxConfigBase::wxConfigBase(const wxString& appName,
const wxString& vendorName, const wxString& vendorName,
const wxString& WXUNUSED(localFilename), const wxString& WXUNUSED(localFilename),
const wxString& WXUNUSED(globalFilename), const wxString& WXUNUSED(globalFilename),
long style) long style)
: m_appName(appName), m_vendorName(vendorName), m_style(style) : m_appName(appName), m_vendorName(vendorName), m_style(style)
{ {
m_bExpandEnvVars = true; m_bExpandEnvVars = true;
m_bRecordDefaults = false; m_bRecordDefaults = false;
} }
wxConfigBase::~wxConfigBase() wxConfigBase::~wxConfigBase()
{ {
// required here for Darwin // required here for Darwin
} }
wxConfigBase *wxConfigBase::Set(wxConfigBase *pConfig) wxConfigBase *wxConfigBase::Set(wxConfigBase *pConfig)
{ {
wxConfigBase *pOld = ms_pConfig; wxConfigBase *pOld = ms_pConfig;
ms_pConfig = pConfig; ms_pConfig = pConfig;
return pOld; return pOld;
} }
wxConfigBase *wxConfigBase::Create() wxConfigBase *wxConfigBase::Create()
{ {
if ( ms_bAutoCreate && ms_pConfig == NULL ) { if ( ms_bAutoCreate && ms_pConfig == NULL ) {
ms_pConfig = ms_pConfig =
#if defined(__WXMSW__) && wxUSE_CONFIG_NATIVE #if defined(__WXMSW__) && wxUSE_CONFIG_NATIVE
new wxRegConfig(wxTheApp->GetAppName(), wxTheApp->GetVendorName()); new wxRegConfig(wxTheApp->GetAppName(), wxTheApp->GetVendorName());
#elif defined(__WXPALMOS__) && wxUSE_CONFIG_NATIVE #elif defined(__WXPALMOS__) && wxUSE_CONFIG_NATIVE
new wxPrefConfig(wxTheApp->GetAppName()); new wxPrefConfig(wxTheApp->GetAppName());
#else // either we're under Unix or wish to use files even under Windows #else // either we're under Unix or wish to use files even under Windows
new wxFileConfig(wxTheApp->GetAppName()); new wxFileConfig(wxTheApp->GetAppName());
#endif #endif
} }
return ms_pConfig; return ms_pConfig;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxConfigBase reading entries // wxConfigBase reading entries
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// implement both Read() overloads for the given type in terms of DoRead() // implement both Read() overloads for the given type in terms of DoRead()
#define IMPLEMENT_READ_FOR_TYPE(name, type, deftype, extra) \ #define IMPLEMENT_READ_FOR_TYPE(name, type, deftype, extra) \
bool wxConfigBase::Read(const wxString& key, type *val) const \ bool wxConfigBase::Read(const wxString& key, type *val) const \
{ \ { \
wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \ wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \
\ \
if ( !DoRead##name(key, val) ) \ if ( !DoRead##name(key, val) ) \
return false; \ return false; \
\ \
*val = extra(*val); \ *val = extra(*val); \
\ \
return true; \ return true; \
} \ } \
\ \
bool wxConfigBase::Read(const wxString& key, \ bool wxConfigBase::Read(const wxString& key, \
type *val, \ type *val, \
deftype defVal) const \ deftype defVal) const \
{ \ { \
wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \ wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \
\ \
bool read = DoRead##name(key, val); \ bool read = DoRead##name(key, val); \
if ( !read ) \ if ( !read ) \
{ \ { \
if ( IsRecordingDefaults() ) \ if ( IsRecordingDefaults() ) \
{ \ { \
((wxConfigBase *)this)->DoWrite##name(key, defVal); \ ((wxConfigBase *)this)->DoWrite##name(key, defVal); \
} \ } \
\ \
*val = defVal; \ *val = defVal; \
} \ } \
\ \
*val = extra(*val); \ *val = extra(*val); \
\ \
return read; \ return read; \
} }
IMPLEMENT_READ_FOR_TYPE(String, wxString, const wxString&, ExpandEnvVars) IMPLEMENT_READ_FOR_TYPE(String, wxString, const wxString&, ExpandEnvVars)
IMPLEMENT_READ_FOR_TYPE(Long, long, long, long) IMPLEMENT_READ_FOR_TYPE(Long, long, long, long)
IMPLEMENT_READ_FOR_TYPE(Int, int, int, int) IMPLEMENT_READ_FOR_TYPE(Int, int, int, int)
IMPLEMENT_READ_FOR_TYPE(Double, double, double, double) IMPLEMENT_READ_FOR_TYPE(Double, double, double, double)
IMPLEMENT_READ_FOR_TYPE(Bool, bool, bool, bool) IMPLEMENT_READ_FOR_TYPE(Bool, bool, bool, bool)
#undef IMPLEMENT_READ_FOR_TYPE #undef IMPLEMENT_READ_FOR_TYPE
// the DoReadXXX() for the other types have implementation in the base class // the DoReadXXX() for the other types have implementation in the base class
// but can be overridden in the derived ones // but can be overridden in the derived ones
bool wxConfigBase::DoReadInt(const wxString& key, int *pi) const bool wxConfigBase::DoReadInt(const wxString& key, int *pi) const
{ {
wxCHECK_MSG( pi, false, _T("wxConfig::Read(): NULL parameter") ); wxCHECK_MSG( pi, false, _T("wxConfig::Read(): NULL parameter") );
long l; long l;
if ( !DoReadLong(key, &l) ) if ( !DoReadLong(key, &l) )
return false; return false;
wxASSERT_MSG( l < INT_MAX, _T("overflow in wxConfig::DoReadInt") ); wxASSERT_MSG( l < INT_MAX, _T("overflow in wxConfig::DoReadInt") );
*pi = (int)l; *pi = (int)l;
return true; return true;
} }
bool wxConfigBase::DoReadBool(const wxString& key, bool* val) const bool wxConfigBase::DoReadBool(const wxString& key, bool* val) const
{ {
wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") );
long l; long l;
if ( !DoReadLong(key, &l) ) if ( !DoReadLong(key, &l) )
return false; return false;
wxASSERT_MSG( l == 0 || l == 1, _T("bad bool value in wxConfig::DoReadInt") ); wxASSERT_MSG( l == 0 || l == 1, _T("bad bool value in wxConfig::DoReadInt") );
*val = l != 0; *val = l != 0;
return true; return true;
} }
bool wxConfigBase::DoReadDouble(const wxString& key, double* val) const bool wxConfigBase::DoReadDouble(const wxString& key, double* val) const
{ {
wxString str; wxString str;
if ( Read(key, &str) ) if ( Read(key, &str) )
{ {
return str.ToDouble(val); return str.ToDouble(val);
} }
return false; return false;
} }
// string reading helper // string reading helper
wxString wxConfigBase::ExpandEnvVars(const wxString& str) const wxString wxConfigBase::ExpandEnvVars(const wxString& str) const
{ {
wxString tmp; // Required for BC++ wxString tmp; // Required for BC++
if (IsExpandingEnvVars()) if (IsExpandingEnvVars())
tmp = wxExpandEnvVars(str); tmp = wxExpandEnvVars(str);
else else
tmp = str; tmp = str;
return tmp; return tmp;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxConfigBase writing // wxConfigBase writing
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxConfigBase::DoWriteDouble(const wxString& key, double val) bool wxConfigBase::DoWriteDouble(const wxString& key, double val)
{ {
return DoWriteString(key, wxString::Format(_T("%g"), val)); return DoWriteString(key, wxString::Format(_T("%g"), val));
} }
bool wxConfigBase::DoWriteInt(const wxString& key, int value) bool wxConfigBase::DoWriteInt(const wxString& key, int value)
{ {
return DoWriteLong(key, (long)value); return DoWriteLong(key, (long)value);
} }
bool wxConfigBase::DoWriteBool(const wxString& key, bool value) bool wxConfigBase::DoWriteBool(const wxString& key, bool value)
{ {
return DoWriteLong(key, value ? 1l : 0l); return DoWriteLong(key, value ? 1l : 0l);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxConfigPathChanger // wxConfigPathChanger
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxConfigPathChanger::wxConfigPathChanger(const wxConfigBase *pContainer, wxConfigPathChanger::wxConfigPathChanger(const wxConfigBase *pContainer,
const wxString& strEntry) const wxString& strEntry)
{ {
m_bChanged = false; m_bChanged = false;
m_pContainer = (wxConfigBase *)pContainer; m_pContainer = (wxConfigBase *)pContainer;
// the path is everything which precedes the last slash // the path is everything which precedes the last slash
wxString strPath = strEntry.BeforeLast(wxCONFIG_PATH_SEPARATOR); wxString strPath = strEntry.BeforeLast(wxCONFIG_PATH_SEPARATOR);
// except in the special case of "/keyname" when there is nothing before "/" // except in the special case of "/keyname" when there is nothing before "/"
if ( strPath.empty() && if ( strPath.empty() &&
((!strEntry.empty()) && strEntry[0] == wxCONFIG_PATH_SEPARATOR) ) ((!strEntry.empty()) && strEntry[0] == wxCONFIG_PATH_SEPARATOR) )
{ {
strPath = wxCONFIG_PATH_SEPARATOR; strPath = wxCONFIG_PATH_SEPARATOR;
} }
if ( !strPath.empty() ) if ( !strPath.empty() )
{ {
if ( m_pContainer->GetPath() != strPath ) if ( m_pContainer->GetPath() != strPath )
{ {
// we do change the path so restore it later // we do change the path so restore it later
m_bChanged = true; m_bChanged = true;
/* JACS: work around a memory bug that causes an assert /* JACS: work around a memory bug that causes an assert
when using wxRegConfig, related to reference-counting. when using wxRegConfig, related to reference-counting.
Can be reproduced by removing (const wxChar*) below and Can be reproduced by removing (const wxChar*) below and
adding the following code to the config sample OnInit under adding the following code to the config sample OnInit under
Windows: Windows:
pConfig->SetPath(wxT("MySettings")); pConfig->SetPath(wxT("MySettings"));
pConfig->SetPath(wxT("..")); pConfig->SetPath(wxT(".."));
int value; int value;
pConfig->Read(_T("MainWindowX"), & value); pConfig->Read(_T("MainWindowX"), & value);
*/ */
m_strOldPath = (const wxChar*) m_pContainer->GetPath(); m_strOldPath = (const wxChar*) m_pContainer->GetPath();
if ( *m_strOldPath.c_str() != wxCONFIG_PATH_SEPARATOR ) if ( *m_strOldPath.c_str() != wxCONFIG_PATH_SEPARATOR )
m_strOldPath += wxCONFIG_PATH_SEPARATOR; m_strOldPath += wxCONFIG_PATH_SEPARATOR;
m_pContainer->SetPath(strPath); m_pContainer->SetPath(strPath);
} }
// in any case, use the just the name, not full path // in any case, use the just the name, not full path
m_strName = strEntry.AfterLast(wxCONFIG_PATH_SEPARATOR); m_strName = strEntry.AfterLast(wxCONFIG_PATH_SEPARATOR);
} }
else { else {
// it's a name only, without path - nothing to do // it's a name only, without path - nothing to do
m_strName = strEntry; m_strName = strEntry;
} }
} }
void wxConfigPathChanger::UpdateIfDeleted() void wxConfigPathChanger::UpdateIfDeleted()
{ {
// we don't have to do anything at all if we didn't change the path // we don't have to do anything at all if we didn't change the path
if ( !m_bChanged ) if ( !m_bChanged )
return; return;
// find the deepest still existing parent path of the original path // find the deepest still existing parent path of the original path
while ( !m_pContainer->HasGroup(m_strOldPath) ) while ( !m_pContainer->HasGroup(m_strOldPath) )
{ {
m_strOldPath = m_strOldPath.BeforeLast(wxCONFIG_PATH_SEPARATOR); m_strOldPath = m_strOldPath.BeforeLast(wxCONFIG_PATH_SEPARATOR);
if ( m_strOldPath.empty() ) if ( m_strOldPath.empty() )
m_strOldPath = wxCONFIG_PATH_SEPARATOR; m_strOldPath = wxCONFIG_PATH_SEPARATOR;
} }
} }
wxConfigPathChanger::~wxConfigPathChanger() wxConfigPathChanger::~wxConfigPathChanger()
{ {
// only restore path if it was changed // only restore path if it was changed
if ( m_bChanged ) { if ( m_bChanged ) {
m_pContainer->SetPath(m_strOldPath); m_pContainer->SetPath(m_strOldPath);
} }
} }
// this is a wxConfig method but it's mainly used with wxConfigPathChanger // this is a wxConfig method but it's mainly used with wxConfigPathChanger
/* static */ /* static */
wxString wxConfigBase::RemoveTrailingSeparator(const wxString& key) wxString wxConfigBase::RemoveTrailingSeparator(const wxString& key)
{ {
wxString path(key); wxString path(key);
// don't remove the only separator from a root group path! // don't remove the only separator from a root group path!
while ( path.length() > 1 ) while ( path.length() > 1 )
{ {
if ( *path.rbegin() != wxCONFIG_PATH_SEPARATOR ) if ( *path.rbegin() != wxCONFIG_PATH_SEPARATOR )
break; break;
path.erase(path.end() - 1); path.erase(path.end() - 1);
} }
return path; return path;
} }
#endif // wxUSE_CONFIG #endif // wxUSE_CONFIG
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// static & global functions // static & global functions
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// understands both Unix and Windows (but only under Windows) environment // understands both Unix and Windows (but only under Windows) environment
// variables expansion: i.e. $var, $(var) and ${var} are always understood // variables expansion: i.e. $var, $(var) and ${var} are always understood
// and in addition under Windows %var% is also. // and in addition under Windows %var% is also.
// don't change the values the enum elements: they must be equal // don't change the values the enum elements: they must be equal
// to the matching [closing] delimiter. // to the matching [closing] delimiter.
enum Bracket enum Bracket
{ {
Bracket_None, Bracket_None,
Bracket_Normal = ')', Bracket_Normal = ')',
Bracket_Curly = '}', Bracket_Curly = '}',
#ifdef __WXMSW__ #ifdef __WXMSW__
Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-) Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
#endif #endif
Bracket_Max Bracket_Max
}; };
wxString wxExpandEnvVars(const wxString& str) wxString wxExpandEnvVars(const wxString& str)
{ {
wxString strResult; wxString strResult;
strResult.Alloc(str.length()); strResult.Alloc(str.length());
size_t m; size_t m;
for ( size_t n = 0; n < str.length(); n++ ) { for ( size_t n = 0; n < str.length(); n++ ) {
switch ( str[n] ) { switch ( str[n] ) {
#ifdef __WXMSW__ #ifdef __WXMSW__
case wxT('%'): case wxT('%'):
#endif //WINDOWS #endif //WINDOWS
case wxT('$'): case wxT('$'):
{ {
Bracket bracket; Bracket bracket;
#ifdef __WXMSW__ #ifdef __WXMSW__
if ( str[n] == wxT('%') ) if ( str[n] == wxT('%') )
bracket = Bracket_Windows; bracket = Bracket_Windows;
else else
#endif //WINDOWS #endif //WINDOWS
if ( n == str.length() - 1 ) { if ( n == str.length() - 1 ) {
bracket = Bracket_None; bracket = Bracket_None;
} }
else { else {
switch ( str[n + 1] ) { switch ( str[n + 1] ) {
case wxT('('): case wxT('('):
bracket = Bracket_Normal; bracket = Bracket_Normal;
n++; // skip the bracket n++; // skip the bracket
break; break;
case wxT('{'): case wxT('{'):
bracket = Bracket_Curly; bracket = Bracket_Curly;
n++; // skip the bracket n++; // skip the bracket
break; break;
default: default:
bracket = Bracket_None; bracket = Bracket_None;
} }
} }
m = n + 1; m = n + 1;
while ( m < str.length() && (wxIsalnum(str[m]) || str[m] == wxT('_')) ) while ( m < str.length() && (wxIsalnum(str[m]) || str[m] == wxT('_')) )
m++; m++;
wxString strVarName(str.c_str() + n + 1, m - n - 1); wxString strVarName(str.c_str() + n + 1, m - n - 1);
#ifdef __WXWINCE__ #ifdef __WXWINCE__
const wxChar *pszValue = NULL; const wxChar *pszValue = NULL;
#else #else
// NB: use wxGetEnv instead of wxGetenv as otherwise variables // NB: use wxGetEnv instead of wxGetenv as otherwise variables
// set through wxSetEnv may not be read correctly! // set through wxSetEnv may not be read correctly!
const wxChar *pszValue = NULL; const wxChar *pszValue = NULL;
wxString tmp; wxString tmp;
if (wxGetEnv(strVarName, &tmp)) if (wxGetEnv(strVarName, &tmp))
pszValue = tmp; pszValue = tmp;
#endif #endif
if ( pszValue != NULL ) { if ( pszValue != NULL ) {
strResult += pszValue; strResult += pszValue;
} }
else { else {
// variable doesn't exist => don't change anything // variable doesn't exist => don't change anything
#ifdef __WXMSW__ #ifdef __WXMSW__
if ( bracket != Bracket_Windows ) if ( bracket != Bracket_Windows )
#endif #endif
if ( bracket != Bracket_None ) if ( bracket != Bracket_None )
strResult << str[n - 1]; strResult << str[n - 1];
strResult << str[n] << strVarName; strResult << str[n] << strVarName;
} }
// check the closing bracket // check the closing bracket
if ( bracket != Bracket_None ) { if ( bracket != Bracket_None ) {
if ( m == str.length() || str[m] != (wxChar)bracket ) { if ( m == str.length() || str[m] != (wxChar)bracket ) {
// under MSW it's common to have '%' characters in the registry // under MSW it's common to have '%' characters in the registry
// and it's annoying to have warnings about them each time, so // and it's annoying to have warnings about them each time, so
// ignroe them silently if they are not used for env vars // ignroe them silently if they are not used for env vars
// //
// under Unix, OTOH, this warning could be useful for the user to // under Unix, OTOH, this warning could be useful for the user to
// understand why isn't the variable expanded as intended // understand why isn't the variable expanded as intended
#ifndef __WXMSW__ #ifndef __WXMSW__
wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."), wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."),
(char)bracket, (unsigned int) (m + 1), str.c_str()); (char)bracket, (unsigned int) (m + 1), str.c_str());
#endif // __WXMSW__ #endif // __WXMSW__
} }
else { else {
// skip closing bracket unless the variables wasn't expanded // skip closing bracket unless the variables wasn't expanded
if ( pszValue == NULL ) if ( pszValue == NULL )
strResult << (wxChar)bracket; strResult << (wxChar)bracket;
m++; m++;
} }
} }
n = m - 1; // skip variable name n = m - 1; // skip variable name
} }
break; break;
case '\\': case '\\':
// backslash can be used to suppress special meaning of % and $ // backslash can be used to suppress special meaning of % and $
if ( n != str.length() - 1 && if ( n != str.length() - 1 &&
(str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) { (str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) {
strResult += str[++n]; strResult += str[++n];
break; break;
} }
//else: fall through //else: fall through
default: default:
strResult += str[n]; strResult += str[n];
} }
} }
return strResult; return strResult;
} }
// this function is used to properly interpret '..' in path // this function is used to properly interpret '..' in path
void wxSplitPath(wxArrayString& aParts, const wxChar *sz) void wxSplitPath(wxArrayString& aParts, const wxChar *sz)
{ {
aParts.clear(); aParts.clear();
wxString strCurrent; wxString strCurrent;
const wxChar *pc = sz; const wxChar *pc = sz;
for ( ;; ) { for ( ;; ) {
if ( *pc == wxT('\0') || *pc == wxCONFIG_PATH_SEPARATOR ) { if ( *pc == wxT('\0') || *pc == wxCONFIG_PATH_SEPARATOR ) {
if ( strCurrent == wxT(".") ) { if ( strCurrent == wxT(".") ) {
// ignore // ignore
} }
else if ( strCurrent == wxT("..") ) { else if ( strCurrent == wxT("..") ) {
// go up one level // go up one level
if ( aParts.size() == 0 ) if ( aParts.size() == 0 )
wxLogWarning(_("'%s' has extra '..', ignored."), sz); wxLogWarning(_("'%s' has extra '..', ignored."), sz);
else else
aParts.erase(aParts.end() - 1); aParts.erase(aParts.end() - 1);
strCurrent.Empty(); strCurrent.Empty();
} }
else if ( !strCurrent.empty() ) { else if ( !strCurrent.empty() ) {
aParts.push_back(strCurrent); aParts.push_back(strCurrent);
strCurrent.Empty(); strCurrent.Empty();
} }
//else: //else:
// could log an error here, but we prefer to ignore extra '/' // could log an error here, but we prefer to ignore extra '/'
if ( *pc == wxT('\0') ) if ( *pc == wxT('\0') )
break; break;
} }
else else
strCurrent += *pc; strCurrent += *pc;
pc++; pc++;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,214 +1,214 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/convauto.cpp // Name: src/common/convauto.cpp
// Purpose: implementation of wxConvAuto // Purpose: implementation of wxConvAuto
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Created: 2006-04-04 // Created: 2006-04-04
// RCS-ID: $Id: convauto.cpp 38570 2006-04-05 14:37:47Z VZ $ // RCS-ID: $Id: convauto.cpp 38570 2006-04-05 14:37:47Z VZ $
// Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h". // for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_WCHAR_T #if wxUSE_WCHAR_T
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif //WX_PRECOMP #endif //WX_PRECOMP
#include "wx/convauto.h" #include "wx/convauto.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
/* static */ /* static */
wxConvAuto::BOMType wxConvAuto::DetectBOM(const char *src, size_t srcLen) wxConvAuto::BOMType wxConvAuto::DetectBOM(const char *src, size_t srcLen)
{ {
if ( srcLen < 2 ) if ( srcLen < 2 )
{ {
// minimal BOM is 2 bytes so bail out immediately and simplify the code // minimal BOM is 2 bytes so bail out immediately and simplify the code
// below which wouldn't need to check for length for UTF-16 cases // below which wouldn't need to check for length for UTF-16 cases
return BOM_None; return BOM_None;
} }
// examine the buffer for BOM presence // examine the buffer for BOM presence
// //
// see http://www.unicode.org/faq/utf_bom.html#BOM // see http://www.unicode.org/faq/utf_bom.html#BOM
switch ( *src++ ) switch ( *src++ )
{ {
case '\0': case '\0':
// could only be big endian UTF-32 (00 00 FE FF) // could only be big endian UTF-32 (00 00 FE FF)
if ( srcLen >= 4 && if ( srcLen >= 4 &&
src[0] == '\0' && src[0] == '\0' &&
src[1] == '\xfe' && src[1] == '\xfe' &&
src[2] == '\xff' ) src[2] == '\xff' )
{ {
return BOM_UTF32BE; return BOM_UTF32BE;
} }
break; break;
case '\xfe': case '\xfe':
// could only be big endian UTF-16 (FE FF) // could only be big endian UTF-16 (FE FF)
if ( *src++ == '\xff' ) if ( *src++ == '\xff' )
{ {
return BOM_UTF16BE; return BOM_UTF16BE;
} }
break; break;
case '\xff': case '\xff':
// could be either little endian UTF-16 or UTF-32, both start // could be either little endian UTF-16 or UTF-32, both start
// with FF FE // with FF FE
if ( *src++ == '\xfe' ) if ( *src++ == '\xfe' )
{ {
return srcLen >= 4 && src[0] == '\0' && src[1] == '\0' return srcLen >= 4 && src[0] == '\0' && src[1] == '\0'
? BOM_UTF32LE ? BOM_UTF32LE
: BOM_UTF16LE; : BOM_UTF16LE;
} }
break; break;
case '\xef': case '\xef':
// is this UTF-8 BOM (EF BB BF)? // is this UTF-8 BOM (EF BB BF)?
if ( srcLen >= 3 && src[0] == '\xbb' && src[1] == '\xbf' ) if ( srcLen >= 3 && src[0] == '\xbb' && src[1] == '\xbf' )
{ {
return BOM_UTF8; return BOM_UTF8;
} }
break; break;
} }
return BOM_None; return BOM_None;
} }
void wxConvAuto::InitFromBOM(BOMType bomType) void wxConvAuto::InitFromBOM(BOMType bomType)
{ {
m_consumedBOM = false; m_consumedBOM = false;
switch ( bomType ) switch ( bomType )
{ {
case BOM_UTF32BE: case BOM_UTF32BE:
m_conv = new wxMBConvUTF32BE; m_conv = new wxMBConvUTF32BE;
m_ownsConv = true; m_ownsConv = true;
break; break;
case BOM_UTF32LE: case BOM_UTF32LE:
m_conv = new wxMBConvUTF32LE; m_conv = new wxMBConvUTF32LE;
m_ownsConv = true; m_ownsConv = true;
break; break;
case BOM_UTF16BE: case BOM_UTF16BE:
m_conv = new wxMBConvUTF16BE; m_conv = new wxMBConvUTF16BE;
m_ownsConv = true; m_ownsConv = true;
break; break;
case BOM_UTF16LE: case BOM_UTF16LE:
m_conv = new wxMBConvUTF16LE; m_conv = new wxMBConvUTF16LE;
m_ownsConv = true; m_ownsConv = true;
break; break;
case BOM_UTF8: case BOM_UTF8:
m_conv = &wxConvUTF8; m_conv = &wxConvUTF8;
m_ownsConv = false; m_ownsConv = false;
break; break;
default: default:
wxFAIL_MSG( _T("unexpected BOM type") ); wxFAIL_MSG( _T("unexpected BOM type") );
// fall through: still need to create something // fall through: still need to create something
case BOM_None: case BOM_None:
InitWithDefault(); InitWithDefault();
m_consumedBOM = true; // as there is nothing to consume m_consumedBOM = true; // as there is nothing to consume
} }
} }
void wxConvAuto::SkipBOM(const char **src, size_t *len) const void wxConvAuto::SkipBOM(const char **src, size_t *len) const
{ {
int ofs; int ofs;
switch ( m_bomType ) switch ( m_bomType )
{ {
case BOM_UTF32BE: case BOM_UTF32BE:
case BOM_UTF32LE: case BOM_UTF32LE:
ofs = 4; ofs = 4;
break; break;
case BOM_UTF16BE: case BOM_UTF16BE:
case BOM_UTF16LE: case BOM_UTF16LE:
ofs = 2; ofs = 2;
break; break;
case BOM_UTF8: case BOM_UTF8:
ofs = 3; ofs = 3;
break; break;
default: default:
wxFAIL_MSG( _T("unexpected BOM type") ); wxFAIL_MSG( _T("unexpected BOM type") );
// fall through: still need to create something // fall through: still need to create something
case BOM_None: case BOM_None:
ofs = 0; ofs = 0;
} }
*src += ofs; *src += ofs;
if ( *len != (size_t)-1 ) if ( *len != (size_t)-1 )
*len -= ofs; *len -= ofs;
} }
void wxConvAuto::InitFromInput(const char **src, size_t *len) void wxConvAuto::InitFromInput(const char **src, size_t *len)
{ {
m_bomType = DetectBOM(*src, *len); m_bomType = DetectBOM(*src, *len);
InitFromBOM(m_bomType); InitFromBOM(m_bomType);
SkipBOM(src, len); SkipBOM(src, len);
} }
size_t size_t
wxConvAuto::ToWChar(wchar_t *dst, size_t dstLen, wxConvAuto::ToWChar(wchar_t *dst, size_t dstLen,
const char *src, size_t srcLen) const const char *src, size_t srcLen) const
{ {
// we check BOM and create the appropriate conversion the first time we're // we check BOM and create the appropriate conversion the first time we're
// called but we also need to ensure that the BOM is skipped not only // called but we also need to ensure that the BOM is skipped not only
// during this initial call but also during the first call with non-NULL // during this initial call but also during the first call with non-NULL
// dst as typically we're first called with NULL dst to calculate the // dst as typically we're first called with NULL dst to calculate the
// needed buffer size // needed buffer size
wxConvAuto *self = wx_const_cast(wxConvAuto *, this); wxConvAuto *self = wx_const_cast(wxConvAuto *, this);
if ( !m_conv ) if ( !m_conv )
{ {
self->InitFromInput(&src, &srcLen); self->InitFromInput(&src, &srcLen);
if ( dst ) if ( dst )
self->m_consumedBOM = true; self->m_consumedBOM = true;
} }
if ( !m_consumedBOM && dst ) if ( !m_consumedBOM && dst )
{ {
self->m_consumedBOM = true; self->m_consumedBOM = true;
SkipBOM(&src, &srcLen); SkipBOM(&src, &srcLen);
} }
return m_conv->ToWChar(dst, dstLen, src, srcLen); return m_conv->ToWChar(dst, dstLen, src, srcLen);
} }
size_t size_t
wxConvAuto::FromWChar(char *dst, size_t dstLen, wxConvAuto::FromWChar(char *dst, size_t dstLen,
const wchar_t *src, size_t srcLen) const const wchar_t *src, size_t srcLen) const
{ {
if ( !m_conv ) if ( !m_conv )
{ {
// default to UTF-8 for the multibyte output // default to UTF-8 for the multibyte output
wx_const_cast(wxConvAuto *, this)->InitWithDefault(); wx_const_cast(wxConvAuto *, this)->InitWithDefault();
} }
return m_conv->FromWChar(dst, dstLen, src, srcLen); return m_conv->FromWChar(dst, dstLen, src, srcLen);
} }
#endif // wxUSE_WCHAR_T #endif // wxUSE_WCHAR_T

File diff suppressed because it is too large Load Diff

View File

@ -1,188 +1,188 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/ctrlcmn.cpp // Name: src/common/ctrlcmn.cpp
// Purpose: wxControl common interface // Purpose: wxControl common interface
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 26.07.99 // Created: 26.07.99
// RCS-ID: $Id: ctrlcmn.cpp 40329 2006-07-25 18:40:04Z VZ $ // RCS-ID: $Id: ctrlcmn.cpp 40329 2006-07-25 18:40:04Z VZ $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_CONTROLS #if wxUSE_CONTROLS
#include "wx/control.h" #include "wx/control.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/log.h" #include "wx/log.h"
#include "wx/radiobut.h" #include "wx/radiobut.h"
#include "wx/statbmp.h" #include "wx/statbmp.h"
#include "wx/bitmap.h" #include "wx/bitmap.h"
#include "wx/utils.h" // for wxStripMenuCodes() #include "wx/utils.h" // for wxStripMenuCodes()
#endif #endif
const wxChar wxControlNameStr[] = wxT("control"); const wxChar wxControlNameStr[] = wxT("control");
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
wxControlBase::~wxControlBase() wxControlBase::~wxControlBase()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
bool wxControlBase::Create(wxWindow *parent, bool wxControlBase::Create(wxWindow *parent,
wxWindowID id, wxWindowID id,
const wxPoint &pos, const wxPoint &pos,
const wxSize &size, const wxSize &size,
long style, long style,
const wxValidator& wxVALIDATOR_PARAM(validator), const wxValidator& wxVALIDATOR_PARAM(validator),
const wxString &name) const wxString &name)
{ {
bool ret = wxWindow::Create(parent, id, pos, size, style, name); bool ret = wxWindow::Create(parent, id, pos, size, style, name);
#if wxUSE_VALIDATORS #if wxUSE_VALIDATORS
if ( ret ) if ( ret )
SetValidator(validator); SetValidator(validator);
#endif // wxUSE_VALIDATORS #endif // wxUSE_VALIDATORS
return ret; return ret;
} }
bool wxControlBase::CreateControl(wxWindowBase *parent, bool wxControlBase::CreateControl(wxWindowBase *parent,
wxWindowID id, wxWindowID id,
const wxPoint& pos, const wxPoint& pos,
const wxSize& size, const wxSize& size,
long style, long style,
const wxValidator& validator, const wxValidator& validator,
const wxString& name) const wxString& name)
{ {
// even if it's possible to create controls without parents in some port, // even if it's possible to create controls without parents in some port,
// it should surely be discouraged because it doesn't work at all under // it should surely be discouraged because it doesn't work at all under
// Windows // Windows
wxCHECK_MSG( parent, false, wxT("all controls must have parents") ); wxCHECK_MSG( parent, false, wxT("all controls must have parents") );
if ( !CreateBase(parent, id, pos, size, style, validator, name) ) if ( !CreateBase(parent, id, pos, size, style, validator, name) )
return false; return false;
parent->AddChild(this); parent->AddChild(this);
return true; return true;
} }
/* static */ /* static */
wxString wxControlBase::GetLabelText(const wxString& label) wxString wxControlBase::GetLabelText(const wxString& label)
{ {
// we don't want strip the TABs here, just the mnemonics // we don't want strip the TABs here, just the mnemonics
return wxStripMenuCodes(label, wxStrip_Mnemonics); return wxStripMenuCodes(label, wxStrip_Mnemonics);
} }
void wxControlBase::Command(wxCommandEvent& event) void wxControlBase::Command(wxCommandEvent& event)
{ {
(void)GetEventHandler()->ProcessEvent(event); (void)GetEventHandler()->ProcessEvent(event);
} }
void wxControlBase::InitCommandEvent(wxCommandEvent& event) const void wxControlBase::InitCommandEvent(wxCommandEvent& event) const
{ {
event.SetEventObject((wxControlBase *)this); // const_cast event.SetEventObject((wxControlBase *)this); // const_cast
// event.SetId(GetId()); -- this is usuall done in the event ctor // event.SetId(GetId()); -- this is usuall done in the event ctor
switch ( m_clientDataType ) switch ( m_clientDataType )
{ {
case wxClientData_Void: case wxClientData_Void:
event.SetClientData(GetClientData()); event.SetClientData(GetClientData());
break; break;
case wxClientData_Object: case wxClientData_Object:
event.SetClientObject(GetClientObject()); event.SetClientObject(GetClientObject());
break; break;
case wxClientData_None: case wxClientData_None:
// nothing to do // nothing to do
; ;
} }
} }
void wxControlBase::SetLabel( const wxString &label ) void wxControlBase::SetLabel( const wxString &label )
{ {
InvalidateBestSize(); InvalidateBestSize();
wxWindow::SetLabel(label); wxWindow::SetLabel(label);
} }
bool wxControlBase::SetFont(const wxFont& font) bool wxControlBase::SetFont(const wxFont& font)
{ {
InvalidateBestSize(); InvalidateBestSize();
return wxWindow::SetFont(font); return wxWindow::SetFont(font);
} }
// wxControl-specific processing after processing the update event // wxControl-specific processing after processing the update event
void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent& event) void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent& event)
{ {
// call inherited // call inherited
wxWindowBase::DoUpdateWindowUI(event); wxWindowBase::DoUpdateWindowUI(event);
// update label // update label
if ( event.GetSetText() ) if ( event.GetSetText() )
{ {
if ( event.GetText() != GetLabel() ) if ( event.GetText() != GetLabel() )
SetLabel(event.GetText()); SetLabel(event.GetText());
} }
// Unfortunately we don't yet have common base class for // Unfortunately we don't yet have common base class for
// wxRadioButton, so we handle updates of radiobuttons here. // wxRadioButton, so we handle updates of radiobuttons here.
// TODO: If once wxRadioButtonBase will exist, move this code there. // TODO: If once wxRadioButtonBase will exist, move this code there.
#if wxUSE_RADIOBTN #if wxUSE_RADIOBTN
if ( event.GetSetChecked() ) if ( event.GetSetChecked() )
{ {
wxRadioButton *radiobtn = wxDynamicCastThis(wxRadioButton); wxRadioButton *radiobtn = wxDynamicCastThis(wxRadioButton);
if ( radiobtn ) if ( radiobtn )
radiobtn->SetValue(event.GetChecked()); radiobtn->SetValue(event.GetChecked());
} }
#endif // wxUSE_RADIOBTN #endif // wxUSE_RADIOBTN
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxStaticBitmap // wxStaticBitmap
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_STATBMP #if wxUSE_STATBMP
wxStaticBitmapBase::~wxStaticBitmapBase() wxStaticBitmapBase::~wxStaticBitmapBase()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
wxSize wxStaticBitmapBase::DoGetBestSize() const wxSize wxStaticBitmapBase::DoGetBestSize() const
{ {
wxSize best; wxSize best;
wxBitmap bmp = GetBitmap(); wxBitmap bmp = GetBitmap();
if ( bmp.Ok() ) if ( bmp.Ok() )
best = wxSize(bmp.GetWidth(), bmp.GetHeight()); best = wxSize(bmp.GetWidth(), bmp.GetHeight());
else else
// this is completely arbitrary // this is completely arbitrary
best = wxSize(16, 16); best = wxSize(16, 16);
CacheBestSize(best); CacheBestSize(best);
return best; return best;
} }
#endif // wxUSE_STATBMP #endif // wxUSE_STATBMP
#endif // wxUSE_CONTROLS #endif // wxUSE_CONTROLS

View File

@ -1,197 +1,197 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/ctrlsub.cpp // Name: src/common/ctrlsub.cpp
// Purpose: wxItemContainer implementation // Purpose: wxItemContainer implementation
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 22.10.99 // Created: 22.10.99
// RCS-ID: $Id: ctrlsub.cpp 39077 2006-05-06 19:05:50Z VZ $ // RCS-ID: $Id: ctrlsub.cpp 39077 2006-05-06 19:05:50Z VZ $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_CONTROLS #if wxUSE_CONTROLS
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/ctrlsub.h" #include "wx/ctrlsub.h"
#include "wx/arrstr.h" #include "wx/arrstr.h"
#endif #endif
IMPLEMENT_ABSTRACT_CLASS(wxControlWithItems, wxControl) IMPLEMENT_ABSTRACT_CLASS(wxControlWithItems, wxControl)
// ============================================================================ // ============================================================================
// wxItemContainerImmutable implementation // wxItemContainerImmutable implementation
// ============================================================================ // ============================================================================
wxItemContainerImmutable::~wxItemContainerImmutable() wxItemContainerImmutable::~wxItemContainerImmutable()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// selection // selection
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxString wxItemContainerImmutable::GetStringSelection() const wxString wxItemContainerImmutable::GetStringSelection() const
{ {
wxString s; wxString s;
int sel = GetSelection(); int sel = GetSelection();
if ( sel != wxNOT_FOUND ) if ( sel != wxNOT_FOUND )
s = GetString((unsigned int)sel); s = GetString((unsigned int)sel);
return s; return s;
} }
bool wxItemContainerImmutable::SetStringSelection(const wxString& s) bool wxItemContainerImmutable::SetStringSelection(const wxString& s)
{ {
const int sel = FindString(s); const int sel = FindString(s);
if ( sel == wxNOT_FOUND ) if ( sel == wxNOT_FOUND )
return false; return false;
SetSelection(sel); SetSelection(sel);
return true; return true;
} }
wxArrayString wxItemContainerImmutable::GetStrings() const wxArrayString wxItemContainerImmutable::GetStrings() const
{ {
wxArrayString result; wxArrayString result;
const unsigned int count = GetCount(); const unsigned int count = GetCount();
result.Alloc(count); result.Alloc(count);
for ( unsigned int n = 0; n < count; n++ ) for ( unsigned int n = 0; n < count; n++ )
result.Add(GetString(n)); result.Add(GetString(n));
return result; return result;
} }
// ============================================================================ // ============================================================================
// wxItemContainer implementation // wxItemContainer implementation
// ============================================================================ // ============================================================================
wxItemContainer::~wxItemContainer() wxItemContainer::~wxItemContainer()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// appending items // appending items
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxItemContainer::Append(const wxArrayString& strings) void wxItemContainer::Append(const wxArrayString& strings)
{ {
const size_t count = strings.GetCount(); const size_t count = strings.GetCount();
for ( size_t n = 0; n < count; n++ ) for ( size_t n = 0; n < count; n++ )
{ {
Append(strings[n]); Append(strings[n]);
} }
} }
int wxItemContainer::Insert(const wxString& item, unsigned int pos, void *clientData) int wxItemContainer::Insert(const wxString& item, unsigned int pos, void *clientData)
{ {
int n = DoInsert(item, pos); int n = DoInsert(item, pos);
if ( n != wxNOT_FOUND ) if ( n != wxNOT_FOUND )
SetClientData(n, clientData); SetClientData(n, clientData);
return n; return n;
} }
int wxItemContainer::Insert(const wxString& item, unsigned int pos, wxClientData *clientData) int wxItemContainer::Insert(const wxString& item, unsigned int pos, wxClientData *clientData)
{ {
int n = DoInsert(item, pos); int n = DoInsert(item, pos);
if ( n != wxNOT_FOUND ) if ( n != wxNOT_FOUND )
SetClientObject(n, clientData); SetClientObject(n, clientData);
return n; return n;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// client data // client data
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxItemContainer::SetClientObject(unsigned int n, wxClientData *data) void wxItemContainer::SetClientObject(unsigned int n, wxClientData *data)
{ {
wxASSERT_MSG( m_clientDataItemsType != wxClientData_Void, wxASSERT_MSG( m_clientDataItemsType != wxClientData_Void,
wxT("can't have both object and void client data") ); wxT("can't have both object and void client data") );
// when we call SetClientObject() for the first time, m_clientDataItemsType // when we call SetClientObject() for the first time, m_clientDataItemsType
// is still wxClientData_None and so calling DoGetItemClientObject() would // is still wxClientData_None and so calling DoGetItemClientObject() would
// fail (in addition to being useless) - don't do it // fail (in addition to being useless) - don't do it
if ( m_clientDataItemsType == wxClientData_Object ) if ( m_clientDataItemsType == wxClientData_Object )
{ {
wxClientData *clientDataOld = DoGetItemClientObject(n); wxClientData *clientDataOld = DoGetItemClientObject(n);
if ( clientDataOld ) if ( clientDataOld )
delete clientDataOld; delete clientDataOld;
} }
else // m_clientDataItemsType == wxClientData_None else // m_clientDataItemsType == wxClientData_None
{ {
// now we have object client data // now we have object client data
m_clientDataItemsType = wxClientData_Object; m_clientDataItemsType = wxClientData_Object;
} }
DoSetItemClientObject(n, data); DoSetItemClientObject(n, data);
} }
wxClientData *wxItemContainer::GetClientObject(unsigned int n) const wxClientData *wxItemContainer::GetClientObject(unsigned int n) const
{ {
wxASSERT_MSG( m_clientDataItemsType == wxClientData_Object, wxASSERT_MSG( m_clientDataItemsType == wxClientData_Object,
wxT("this window doesn't have object client data") ); wxT("this window doesn't have object client data") );
return DoGetItemClientObject(n); return DoGetItemClientObject(n);
} }
void wxItemContainer::SetClientData(unsigned int n, void *data) void wxItemContainer::SetClientData(unsigned int n, void *data)
{ {
wxASSERT_MSG( m_clientDataItemsType != wxClientData_Object, wxASSERT_MSG( m_clientDataItemsType != wxClientData_Object,
wxT("can't have both object and void client data") ); wxT("can't have both object and void client data") );
DoSetItemClientData(n, data); DoSetItemClientData(n, data);
m_clientDataItemsType = wxClientData_Void; m_clientDataItemsType = wxClientData_Void;
} }
void *wxItemContainer::GetClientData(unsigned int n) const void *wxItemContainer::GetClientData(unsigned int n) const
{ {
wxASSERT_MSG( m_clientDataItemsType == wxClientData_Void, wxASSERT_MSG( m_clientDataItemsType == wxClientData_Void,
wxT("this window doesn't have void client data") ); wxT("this window doesn't have void client data") );
return DoGetItemClientData(n); return DoGetItemClientData(n);
} }
// ============================================================================ // ============================================================================
// wxControlWithItems implementation // wxControlWithItems implementation
// ============================================================================ // ============================================================================
void wxControlWithItems::InitCommandEventWithItems(wxCommandEvent& event, int n) void wxControlWithItems::InitCommandEventWithItems(wxCommandEvent& event, int n)
{ {
InitCommandEvent(event); InitCommandEvent(event);
if ( n != wxNOT_FOUND ) if ( n != wxNOT_FOUND )
{ {
if ( HasClientObjectData() ) if ( HasClientObjectData() )
event.SetClientObject(GetClientObject(n)); event.SetClientObject(GetClientObject(n));
else if ( HasClientUntypedData() ) else if ( HasClientUntypedData() )
event.SetClientData(GetClientData(n)); event.SetClientData(GetClientData(n));
} }
} }
wxControlWithItems::~wxControlWithItems() wxControlWithItems::~wxControlWithItems()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
#endif // wxUSE_CONTROLS #endif // wxUSE_CONTROLS

View File

@ -1,83 +1,83 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: common/datacmn.cpp // Name: common/datacmn.cpp
// Purpose: contains definitions of various global wxWidgets variables // Purpose: contains definitions of various global wxWidgets variables
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 10.04.03 (from src/*/data.cpp files) // Created: 10.04.03 (from src/*/data.cpp files)
// RCS-ID: $Id: datacmn.cpp 43874 2006-12-09 14:52:59Z VZ $ // RCS-ID: $Id: datacmn.cpp 43874 2006-12-09 14:52:59Z VZ $
// Copyright: (c) 1997-2002 wxWidgets development team // Copyright: (c) 1997-2002 wxWidgets development team
// License: wxWindows license // License: wxWindows license
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif // WX_PRECOMP #endif // WX_PRECOMP
#include "wx/accel.h" #include "wx/accel.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// 'Null' objects // 'Null' objects
#if wxUSE_ACCEL #if wxUSE_ACCEL
wxAcceleratorTable wxNullAcceleratorTable; wxAcceleratorTable wxNullAcceleratorTable;
#endif // wxUSE_ACCEL #endif // wxUSE_ACCEL
// Default window names // Default window names
extern WXDLLEXPORT_DATA(const wxChar) wxButtonNameStr[] = wxT("button"); extern WXDLLEXPORT_DATA(const wxChar) wxButtonNameStr[] = wxT("button");
extern WXDLLEXPORT_DATA(const wxChar) wxCheckBoxNameStr[] = wxT("check"); extern WXDLLEXPORT_DATA(const wxChar) wxCheckBoxNameStr[] = wxT("check");
extern WXDLLEXPORT_DATA(const wxChar) wxComboBoxNameStr[] = wxT("comboBox"); extern WXDLLEXPORT_DATA(const wxChar) wxComboBoxNameStr[] = wxT("comboBox");
extern WXDLLEXPORT_DATA(const wxChar) wxDialogNameStr[] = wxT("dialog"); extern WXDLLEXPORT_DATA(const wxChar) wxDialogNameStr[] = wxT("dialog");
extern WXDLLEXPORT_DATA(const wxChar) wxFrameNameStr[] = wxT("frame"); extern WXDLLEXPORT_DATA(const wxChar) wxFrameNameStr[] = wxT("frame");
extern WXDLLEXPORT_DATA(const wxChar) wxStaticBoxNameStr[] = wxT("groupBox"); extern WXDLLEXPORT_DATA(const wxChar) wxStaticBoxNameStr[] = wxT("groupBox");
extern WXDLLEXPORT_DATA(const wxChar) wxListBoxNameStr[] = wxT("listBox"); extern WXDLLEXPORT_DATA(const wxChar) wxListBoxNameStr[] = wxT("listBox");
extern WXDLLEXPORT_DATA(const wxChar) wxStaticLineNameStr[] = wxT("staticLine"); extern WXDLLEXPORT_DATA(const wxChar) wxStaticLineNameStr[] = wxT("staticLine");
extern WXDLLEXPORT_DATA(const wxChar) wxStaticTextNameStr[] = wxT("staticText"); extern WXDLLEXPORT_DATA(const wxChar) wxStaticTextNameStr[] = wxT("staticText");
extern WXDLLEXPORT_DATA(const wxChar) wxStaticBitmapNameStr[] = wxT("staticBitmap"); extern WXDLLEXPORT_DATA(const wxChar) wxStaticBitmapNameStr[] = wxT("staticBitmap");
extern WXDLLEXPORT_DATA(const wxChar) wxNotebookNameStr[] = wxT("notebook"); extern WXDLLEXPORT_DATA(const wxChar) wxNotebookNameStr[] = wxT("notebook");
extern WXDLLEXPORT_DATA(const wxChar) wxPanelNameStr[] = wxT("panel"); extern WXDLLEXPORT_DATA(const wxChar) wxPanelNameStr[] = wxT("panel");
extern WXDLLEXPORT_DATA(const wxChar) wxRadioBoxNameStr[] = wxT("radioBox"); extern WXDLLEXPORT_DATA(const wxChar) wxRadioBoxNameStr[] = wxT("radioBox");
extern WXDLLEXPORT_DATA(const wxChar) wxRadioButtonNameStr[] = wxT("radioButton"); extern WXDLLEXPORT_DATA(const wxChar) wxRadioButtonNameStr[] = wxT("radioButton");
extern WXDLLEXPORT_DATA(const wxChar) wxBitmapRadioButtonNameStr[] = wxT("radioButton"); extern WXDLLEXPORT_DATA(const wxChar) wxBitmapRadioButtonNameStr[] = wxT("radioButton");
extern WXDLLEXPORT_DATA(const wxChar) wxScrollBarNameStr[] = wxT("scrollBar"); extern WXDLLEXPORT_DATA(const wxChar) wxScrollBarNameStr[] = wxT("scrollBar");
extern WXDLLEXPORT_DATA(const wxChar) wxSliderNameStr[] = wxT("slider"); extern WXDLLEXPORT_DATA(const wxChar) wxSliderNameStr[] = wxT("slider");
extern WXDLLEXPORT_DATA(const wxChar) wxStatusLineNameStr[] = wxT("status_line"); extern WXDLLEXPORT_DATA(const wxChar) wxStatusLineNameStr[] = wxT("status_line");
extern WXDLLEXPORT_DATA(const wxChar) wxTextCtrlNameStr[] = wxT("text"); extern WXDLLEXPORT_DATA(const wxChar) wxTextCtrlNameStr[] = wxT("text");
extern WXDLLEXPORT_DATA(const wxChar) wxTreeCtrlNameStr[] = wxT("treeCtrl"); extern WXDLLEXPORT_DATA(const wxChar) wxTreeCtrlNameStr[] = wxT("treeCtrl");
extern WXDLLEXPORT_DATA(const wxChar) wxToolBarNameStr[] = wxT("toolbar"); extern WXDLLEXPORT_DATA(const wxChar) wxToolBarNameStr[] = wxT("toolbar");
// Default messages // Default messages
extern WXDLLEXPORT_DATA(const wxChar) wxMessageBoxCaptionStr[] = wxT("Message"); extern WXDLLEXPORT_DATA(const wxChar) wxMessageBoxCaptionStr[] = wxT("Message");
extern WXDLLEXPORT_DATA(const wxChar) wxFileSelectorPromptStr[] = wxT("Select a file"); extern WXDLLEXPORT_DATA(const wxChar) wxFileSelectorPromptStr[] = wxT("Select a file");
extern WXDLLEXPORT_DATA(const wxChar) wxDirSelectorPromptStr[] = wxT("Select a directory"); extern WXDLLEXPORT_DATA(const wxChar) wxDirSelectorPromptStr[] = wxT("Select a directory");
// Other default strings // Other default strings
extern WXDLLEXPORT_DATA(const wxChar) wxFileSelectorDefaultWildcardStr[] = extern WXDLLEXPORT_DATA(const wxChar) wxFileSelectorDefaultWildcardStr[] =
#if defined(__WXMSW__) || defined(__OS2__) #if defined(__WXMSW__) || defined(__OS2__)
wxT("*.*") wxT("*.*")
#else // Unix/Mac #else // Unix/Mac
wxT("*") wxT("*")
#endif #endif
; ;
extern WXDLLEXPORT_DATA(const wxChar) wxDirDialogNameStr[] = wxT("wxDirCtrl"); extern WXDLLEXPORT_DATA(const wxChar) wxDirDialogNameStr[] = wxT("wxDirCtrl");
extern WXDLLEXPORT_DATA(const wxChar) wxDirDialogDefaultFolderStr[] = wxT("/"); extern WXDLLEXPORT_DATA(const wxChar) wxDirDialogDefaultFolderStr[] = wxT("/");
extern WXDLLEXPORT_DATA(const wxChar) wxFileDialogNameStr[] = wxT("filedlg"); extern WXDLLEXPORT_DATA(const wxChar) wxFileDialogNameStr[] = wxT("filedlg");
#if defined(__WXMSW__) || defined(__OS2__) #if defined(__WXMSW__) || defined(__OS2__)
WXDLLEXPORT_DATA(const wxChar *) wxUserResourceStr = wxT("TEXT"); WXDLLEXPORT_DATA(const wxChar *) wxUserResourceStr = wxT("TEXT");
#endif #endif

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,95 +1,95 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/dcbufcmn.cpp // Name: src/common/dcbufcmn.cpp
// Purpose: Buffered DC implementation // Purpose: Buffered DC implementation
// Author: Ron Lee, Jaakko Salli // Author: Ron Lee, Jaakko Salli
// Modified by: // Modified by:
// Created: Sep-20-2006 // Created: Sep-20-2006
// RCS-ID: $Id: dcbufcmn.cpp 52152 2008-02-27 18:03:12Z VZ $ // RCS-ID: $Id: dcbufcmn.cpp 52152 2008-02-27 18:03:12Z VZ $
// Copyright: (c) wxWidgets team // Copyright: (c) wxWidgets team
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/dcbuffer.h" #include "wx/dcbuffer.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/module.h" #include "wx/module.h"
#endif #endif
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxSharedDCBufferManager: helper class maintaining backing store bitmap // wxSharedDCBufferManager: helper class maintaining backing store bitmap
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxSharedDCBufferManager : public wxModule class wxSharedDCBufferManager : public wxModule
{ {
public: public:
wxSharedDCBufferManager() { } wxSharedDCBufferManager() { }
virtual bool OnInit() { return true; } virtual bool OnInit() { return true; }
virtual void OnExit() { wxDELETE(ms_buffer); } virtual void OnExit() { wxDELETE(ms_buffer); }
static wxBitmap* GetBuffer(int w, int h) static wxBitmap* GetBuffer(int w, int h)
{ {
if ( !ms_buffer || if ( !ms_buffer ||
w > ms_buffer->GetWidth() || w > ms_buffer->GetWidth() ||
h > ms_buffer->GetHeight() ) h > ms_buffer->GetHeight() )
{ {
delete ms_buffer; delete ms_buffer;
// we must always return a valid bitmap but creating a bitmap of // we must always return a valid bitmap but creating a bitmap of
// size 0 would fail, so create a 1*1 bitmap in this case // size 0 would fail, so create a 1*1 bitmap in this case
if ( !w ) if ( !w )
w = 1; w = 1;
if ( !h ) if ( !h )
h = 1; h = 1;
ms_buffer = new wxBitmap(w, h); ms_buffer = new wxBitmap(w, h);
} }
return ms_buffer; return ms_buffer;
} }
private: private:
static wxBitmap *ms_buffer; static wxBitmap *ms_buffer;
DECLARE_DYNAMIC_CLASS(wxSharedDCBufferManager) DECLARE_DYNAMIC_CLASS(wxSharedDCBufferManager)
}; };
wxBitmap* wxSharedDCBufferManager::ms_buffer = NULL; wxBitmap* wxSharedDCBufferManager::ms_buffer = NULL;
IMPLEMENT_DYNAMIC_CLASS(wxSharedDCBufferManager, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxSharedDCBufferManager, wxModule)
// ============================================================================ // ============================================================================
// wxBufferedDC // wxBufferedDC
// ============================================================================ // ============================================================================
void wxBufferedDC::UseBuffer(wxCoord w, wxCoord h) void wxBufferedDC::UseBuffer(wxCoord w, wxCoord h)
{ {
if ( !m_buffer || !m_buffer->IsOk() ) if ( !m_buffer || !m_buffer->IsOk() )
{ {
if ( w == -1 || h == -1 ) if ( w == -1 || h == -1 )
m_dc->GetSize(&w, &h); m_dc->GetSize(&w, &h);
m_buffer = wxSharedDCBufferManager::GetBuffer(w, h); m_buffer = wxSharedDCBufferManager::GetBuffer(w, h);
} }
SelectObject(*m_buffer); SelectObject(*m_buffer);
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,357 +1,357 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/dircmn.cpp // Name: src/common/dircmn.cpp
// Purpose: wxDir methods common to all implementations // Purpose: wxDir methods common to all implementations
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 19.05.01 // Created: 19.05.01
// RCS-ID: $Id: dircmn.cpp 40665 2006-08-19 08:45:31Z JS $ // RCS-ID: $Id: dircmn.cpp 40665 2006-08-19 08:45:31Z JS $
// Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// License: wxWindows licence // License: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/string.h" #include "wx/string.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/filefn.h" #include "wx/filefn.h"
#include "wx/arrstr.h" #include "wx/arrstr.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
#include "wx/dir.h" #include "wx/dir.h"
#include "wx/filename.h" #include "wx/filename.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDirTraverser // wxDirTraverser
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDirTraverseResult wxDirTraverseResult
wxDirTraverser::OnOpenError(const wxString& WXUNUSED(dirname)) wxDirTraverser::OnOpenError(const wxString& WXUNUSED(dirname))
{ {
return wxDIR_IGNORE; return wxDIR_IGNORE;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDir::HasFiles() and HasSubDirs() // wxDir::HasFiles() and HasSubDirs()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// dumb generic implementation // dumb generic implementation
bool wxDir::HasFiles(const wxString& spec) bool wxDir::HasFiles(const wxString& spec)
{ {
wxString s; wxString s;
return GetFirst(&s, spec, wxDIR_FILES | wxDIR_HIDDEN); return GetFirst(&s, spec, wxDIR_FILES | wxDIR_HIDDEN);
} }
// we have a (much) faster version for Unix // we have a (much) faster version for Unix
#if (defined(__CYGWIN__) && defined(__WINDOWS__)) || !defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__EMX__) || defined(__WINE__) #if (defined(__CYGWIN__) && defined(__WINDOWS__)) || !defined(__UNIX_LIKE__) || defined(__WXMAC__) || defined(__EMX__) || defined(__WINE__)
bool wxDir::HasSubDirs(const wxString& spec) bool wxDir::HasSubDirs(const wxString& spec)
{ {
wxString s; wxString s;
return GetFirst(&s, spec, wxDIR_DIRS | wxDIR_HIDDEN); return GetFirst(&s, spec, wxDIR_DIRS | wxDIR_HIDDEN);
} }
#endif // !Unix #endif // !Unix
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDir::Traverse() // wxDir::Traverse()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
size_t wxDir::Traverse(wxDirTraverser& sink, size_t wxDir::Traverse(wxDirTraverser& sink,
const wxString& filespec, const wxString& filespec,
int flags) const int flags) const
{ {
wxCHECK_MSG( IsOpened(), (size_t)-1, wxCHECK_MSG( IsOpened(), (size_t)-1,
_T("dir must be opened before traversing it") ); _T("dir must be opened before traversing it") );
// the total number of files found // the total number of files found
size_t nFiles = 0; size_t nFiles = 0;
// the name of this dir with path delimiter at the end // the name of this dir with path delimiter at the end
wxString prefix = GetName(); wxString prefix = GetName();
prefix += wxFILE_SEP_PATH; prefix += wxFILE_SEP_PATH;
// first, recurse into subdirs // first, recurse into subdirs
if ( flags & wxDIR_DIRS ) if ( flags & wxDIR_DIRS )
{ {
wxString dirname; wxString dirname;
for ( bool cont = GetFirst(&dirname, wxEmptyString, wxDIR_DIRS | (flags & wxDIR_HIDDEN) ); for ( bool cont = GetFirst(&dirname, wxEmptyString, wxDIR_DIRS | (flags & wxDIR_HIDDEN) );
cont; cont;
cont = cont && GetNext(&dirname) ) cont = cont && GetNext(&dirname) )
{ {
const wxString fulldirname = prefix + dirname; const wxString fulldirname = prefix + dirname;
switch ( sink.OnDir(fulldirname) ) switch ( sink.OnDir(fulldirname) )
{ {
default: default:
wxFAIL_MSG(_T("unexpected OnDir() return value") ); wxFAIL_MSG(_T("unexpected OnDir() return value") );
// fall through // fall through
case wxDIR_STOP: case wxDIR_STOP:
cont = false; cont = false;
break; break;
case wxDIR_CONTINUE: case wxDIR_CONTINUE:
{ {
wxDir subdir; wxDir subdir;
// don't give the error messages for the directories // don't give the error messages for the directories
// which we can't open: there can be all sorts of good // which we can't open: there can be all sorts of good
// reason for this (e.g. insufficient privileges) and // reason for this (e.g. insufficient privileges) and
// this shouldn't be treated as an error -- instead // this shouldn't be treated as an error -- instead
// let the user code decide what to do // let the user code decide what to do
bool ok; bool ok;
do do
{ {
wxLogNull noLog; wxLogNull noLog;
ok = subdir.Open(fulldirname); ok = subdir.Open(fulldirname);
if ( !ok ) if ( !ok )
{ {
// ask the user code what to do // ask the user code what to do
bool tryagain; bool tryagain;
switch ( sink.OnOpenError(fulldirname) ) switch ( sink.OnOpenError(fulldirname) )
{ {
default: default:
wxFAIL_MSG(_T("unexpected OnOpenError() return value") ); wxFAIL_MSG(_T("unexpected OnOpenError() return value") );
// fall through // fall through
case wxDIR_STOP: case wxDIR_STOP:
cont = false; cont = false;
// fall through // fall through
case wxDIR_IGNORE: case wxDIR_IGNORE:
tryagain = false; tryagain = false;
break; break;
case wxDIR_CONTINUE: case wxDIR_CONTINUE:
tryagain = true; tryagain = true;
} }
if ( !tryagain ) if ( !tryagain )
break; break;
} }
} }
while ( !ok ); while ( !ok );
if ( ok ) if ( ok )
{ {
nFiles += subdir.Traverse(sink, filespec, flags); nFiles += subdir.Traverse(sink, filespec, flags);
} }
} }
break; break;
case wxDIR_IGNORE: case wxDIR_IGNORE:
// nothing to do // nothing to do
; ;
} }
} }
} }
// now enum our own files // now enum our own files
if ( flags & wxDIR_FILES ) if ( flags & wxDIR_FILES )
{ {
flags &= ~wxDIR_DIRS; flags &= ~wxDIR_DIRS;
wxString filename; wxString filename;
bool cont = GetFirst(&filename, filespec, flags); bool cont = GetFirst(&filename, filespec, flags);
while ( cont ) while ( cont )
{ {
wxDirTraverseResult res = sink.OnFile(prefix + filename); wxDirTraverseResult res = sink.OnFile(prefix + filename);
if ( res == wxDIR_STOP ) if ( res == wxDIR_STOP )
break; break;
wxASSERT_MSG( res == wxDIR_CONTINUE, wxASSERT_MSG( res == wxDIR_CONTINUE,
_T("unexpected OnFile() return value") ); _T("unexpected OnFile() return value") );
nFiles++; nFiles++;
cont = GetNext(&filename); cont = GetNext(&filename);
} }
} }
return nFiles; return nFiles;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDir::GetAllFiles() // wxDir::GetAllFiles()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxDirTraverserSimple : public wxDirTraverser class wxDirTraverserSimple : public wxDirTraverser
{ {
public: public:
wxDirTraverserSimple(wxArrayString& files) : m_files(files) { } wxDirTraverserSimple(wxArrayString& files) : m_files(files) { }
virtual wxDirTraverseResult OnFile(const wxString& filename) virtual wxDirTraverseResult OnFile(const wxString& filename)
{ {
m_files.push_back(filename); m_files.push_back(filename);
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname)) virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{ {
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
private: private:
wxArrayString& m_files; wxArrayString& m_files;
DECLARE_NO_COPY_CLASS(wxDirTraverserSimple) DECLARE_NO_COPY_CLASS(wxDirTraverserSimple)
}; };
/* static */ /* static */
size_t wxDir::GetAllFiles(const wxString& dirname, size_t wxDir::GetAllFiles(const wxString& dirname,
wxArrayString *files, wxArrayString *files,
const wxString& filespec, const wxString& filespec,
int flags) int flags)
{ {
wxCHECK_MSG( files, (size_t)-1, _T("NULL pointer in wxDir::GetAllFiles") ); wxCHECK_MSG( files, (size_t)-1, _T("NULL pointer in wxDir::GetAllFiles") );
size_t nFiles = 0; size_t nFiles = 0;
wxDir dir(dirname); wxDir dir(dirname);
if ( dir.IsOpened() ) if ( dir.IsOpened() )
{ {
wxDirTraverserSimple traverser(*files); wxDirTraverserSimple traverser(*files);
nFiles += dir.Traverse(traverser, filespec, flags); nFiles += dir.Traverse(traverser, filespec, flags);
} }
return nFiles; return nFiles;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDir::FindFirst() // wxDir::FindFirst()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxDirTraverserFindFirst : public wxDirTraverser class wxDirTraverserFindFirst : public wxDirTraverser
{ {
public: public:
wxDirTraverserFindFirst() { } wxDirTraverserFindFirst() { }
virtual wxDirTraverseResult OnFile(const wxString& filename) virtual wxDirTraverseResult OnFile(const wxString& filename)
{ {
m_file = filename; m_file = filename;
return wxDIR_STOP; return wxDIR_STOP;
} }
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname)) virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{ {
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
const wxString& GetFile() const const wxString& GetFile() const
{ {
return m_file; return m_file;
} }
private: private:
wxString m_file; wxString m_file;
DECLARE_NO_COPY_CLASS(wxDirTraverserFindFirst) DECLARE_NO_COPY_CLASS(wxDirTraverserFindFirst)
}; };
/* static */ /* static */
wxString wxDir::FindFirst(const wxString& dirname, wxString wxDir::FindFirst(const wxString& dirname,
const wxString& filespec, const wxString& filespec,
int flags) int flags)
{ {
wxDir dir(dirname); wxDir dir(dirname);
if ( dir.IsOpened() ) if ( dir.IsOpened() )
{ {
wxDirTraverserFindFirst traverser; wxDirTraverserFindFirst traverser;
dir.Traverse(traverser, filespec, flags | wxDIR_FILES); dir.Traverse(traverser, filespec, flags | wxDIR_FILES);
return traverser.GetFile(); return traverser.GetFile();
} }
return wxEmptyString; return wxEmptyString;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDir::GetTotalSize() // wxDir::GetTotalSize()
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxDirTraverserSumSize : public wxDirTraverser class wxDirTraverserSumSize : public wxDirTraverser
{ {
public: public:
wxDirTraverserSumSize() { } wxDirTraverserSumSize() { }
virtual wxDirTraverseResult OnFile(const wxString& filename) virtual wxDirTraverseResult OnFile(const wxString& filename)
{ {
wxULongLong sz = wxFileName::GetSize(filename); wxULongLong sz = wxFileName::GetSize(filename);
// wxFileName::GetSize won't use this class again as // wxFileName::GetSize won't use this class again as
// we're passing it a file and not a directory; // we're passing it a file and not a directory;
// thus we are sure to avoid an endless loop // thus we are sure to avoid an endless loop
if (sz == wxInvalidSize) if (sz == wxInvalidSize)
{ {
// if the GetSize() failed (this can happen because e.g. a // if the GetSize() failed (this can happen because e.g. a
// file is locked by another process), we can proceed but // file is locked by another process), we can proceed but
// we need to at least warn the user that the resulting // we need to at least warn the user that the resulting
// final size could be not reliable (if e.g. the locked // final size could be not reliable (if e.g. the locked
// file is very big). // file is very big).
m_skippedFiles.Add(filename); m_skippedFiles.Add(filename);
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
m_sz += sz; m_sz += sz;
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname)) virtual wxDirTraverseResult OnDir(const wxString& WXUNUSED(dirname))
{ {
return wxDIR_CONTINUE; return wxDIR_CONTINUE;
} }
wxULongLong GetTotalSize() const wxULongLong GetTotalSize() const
{ return m_sz; } { return m_sz; }
wxArrayString &FilesSkipped() wxArrayString &FilesSkipped()
{ return m_skippedFiles; } { return m_skippedFiles; }
protected: protected:
wxULongLong m_sz; wxULongLong m_sz;
wxArrayString m_skippedFiles; wxArrayString m_skippedFiles;
}; };
wxULongLong wxDir::GetTotalSize(const wxString &dirname, wxArrayString *filesSkipped) wxULongLong wxDir::GetTotalSize(const wxString &dirname, wxArrayString *filesSkipped)
{ {
if (!wxDirExists(dirname)) if (!wxDirExists(dirname))
return wxInvalidSize; return wxInvalidSize;
// to get the size of this directory and its contents we need // to get the size of this directory and its contents we need
// to recursively walk it... // to recursively walk it...
wxDir dir(dirname); wxDir dir(dirname);
if ( !dir.IsOpened() ) if ( !dir.IsOpened() )
return wxInvalidSize; return wxInvalidSize;
wxDirTraverserSumSize traverser; wxDirTraverserSumSize traverser;
if (dir.Traverse(traverser) == (size_t)-1 || if (dir.Traverse(traverser) == (size_t)-1 ||
traverser.GetTotalSize() == 0) traverser.GetTotalSize() == 0)
return wxInvalidSize; return wxInvalidSize;
if (filesSkipped) if (filesSkipped)
*filesSkipped = traverser.FilesSkipped(); *filesSkipped = traverser.FilesSkipped();
return traverser.GetTotalSize(); return traverser.GetTotalSize();
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +1,31 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: common/dndcmn.cpp // Name: common/dndcmn.cpp
// Author: Robert Roebling // Author: Robert Roebling
// Modified by: // Modified by:
// Created: 19.10.99 // Created: 19.10.99
// RCS-ID: $Id: dndcmn.cpp 43664 2006-11-26 21:50:51Z JS $ // RCS-ID: $Id: dndcmn.cpp 43664 2006-11-26 21:50:51Z JS $
// Copyright: (c) wxWidgets Team // Copyright: (c) wxWidgets Team
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/dnd.h" #include "wx/dnd.h"
#if wxUSE_DRAG_AND_DROP #if wxUSE_DRAG_AND_DROP
bool wxIsDragResultOk(wxDragResult res) bool wxIsDragResultOk(wxDragResult res)
{ {
return res == wxDragCopy || res == wxDragMove || res == wxDragLink; return res == wxDragCopy || res == wxDragMove || res == wxDragLink;
} }
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -1,204 +1,204 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: docmdi.cpp // Name: docmdi.cpp
// Purpose: Frame classes for MDI document/view applications // Purpose: Frame classes for MDI document/view applications
// Author: Julian Smart // Author: Julian Smart
// Modified by: // Modified by:
// Created: 01/02/97 // Created: 01/02/97
// RCS-ID: $Id: docmdi.cpp 35650 2005-09-23 12:56:45Z MR $ // RCS-ID: $Id: docmdi.cpp 35650 2005-09-23 12:56:45Z MR $
// Copyright: (c) Julian Smart // Copyright: (c) Julian Smart
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_MDI_ARCHITECTURE #if wxUSE_MDI_ARCHITECTURE
#include "wx/docmdi.h" #include "wx/docmdi.h"
/* /*
* Docview MDI parent frame * Docview MDI parent frame
*/ */
IMPLEMENT_CLASS(wxDocMDIParentFrame, wxMDIParentFrame) IMPLEMENT_CLASS(wxDocMDIParentFrame, wxMDIParentFrame)
BEGIN_EVENT_TABLE(wxDocMDIParentFrame, wxMDIParentFrame) BEGIN_EVENT_TABLE(wxDocMDIParentFrame, wxMDIParentFrame)
EVT_MENU(wxID_EXIT, wxDocMDIParentFrame::OnExit) EVT_MENU(wxID_EXIT, wxDocMDIParentFrame::OnExit)
EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocMDIParentFrame::OnMRUFile) EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, wxDocMDIParentFrame::OnMRUFile)
EVT_CLOSE(wxDocMDIParentFrame::OnCloseWindow) EVT_CLOSE(wxDocMDIParentFrame::OnCloseWindow)
END_EVENT_TABLE() END_EVENT_TABLE()
wxDocMDIParentFrame::wxDocMDIParentFrame() wxDocMDIParentFrame::wxDocMDIParentFrame()
{ {
Init(); Init();
} }
wxDocMDIParentFrame::wxDocMDIParentFrame(wxDocManager *manager, wxFrame *frame, wxWindowID id, const wxString& title, wxDocMDIParentFrame::wxDocMDIParentFrame(wxDocManager *manager, wxFrame *frame, wxWindowID id, const wxString& title,
const wxPoint& pos, const wxSize& size, long style, const wxString& name) const wxPoint& pos, const wxSize& size, long style, const wxString& name)
{ {
Init(); Init();
Create(manager, frame, id, title, pos, size, style, name); Create(manager, frame, id, title, pos, size, style, name);
} }
bool wxDocMDIParentFrame::Create(wxDocManager *manager, wxFrame *frame, wxWindowID id, const wxString& title, bool wxDocMDIParentFrame::Create(wxDocManager *manager, wxFrame *frame, wxWindowID id, const wxString& title,
const wxPoint& pos, const wxSize& size, long style, const wxString& name) const wxPoint& pos, const wxSize& size, long style, const wxString& name)
{ {
m_docManager = manager; m_docManager = manager;
return wxMDIParentFrame::Create(frame, id, title, pos, size, style, name); return wxMDIParentFrame::Create(frame, id, title, pos, size, style, name);
} }
void wxDocMDIParentFrame::OnExit(wxCommandEvent& WXUNUSED(event)) void wxDocMDIParentFrame::OnExit(wxCommandEvent& WXUNUSED(event))
{ {
Close(); Close();
} }
void wxDocMDIParentFrame::Init() void wxDocMDIParentFrame::Init()
{ {
m_docManager = NULL; m_docManager = NULL;
} }
void wxDocMDIParentFrame::OnMRUFile(wxCommandEvent& event) void wxDocMDIParentFrame::OnMRUFile(wxCommandEvent& event)
{ {
wxString f(m_docManager->GetHistoryFile(event.GetId() - wxID_FILE1)); wxString f(m_docManager->GetHistoryFile(event.GetId() - wxID_FILE1));
if (!f.empty()) if (!f.empty())
(void)m_docManager->CreateDocument(f, wxDOC_SILENT); (void)m_docManager->CreateDocument(f, wxDOC_SILENT);
} }
// Extend event processing to search the view's event table // Extend event processing to search the view's event table
bool wxDocMDIParentFrame::ProcessEvent(wxEvent& event) bool wxDocMDIParentFrame::ProcessEvent(wxEvent& event)
{ {
// Try the document manager, then do default processing // Try the document manager, then do default processing
if (!m_docManager || !m_docManager->ProcessEvent(event)) if (!m_docManager || !m_docManager->ProcessEvent(event))
return wxEvtHandler::ProcessEvent(event); return wxEvtHandler::ProcessEvent(event);
else else
return true; return true;
} }
void wxDocMDIParentFrame::OnCloseWindow(wxCloseEvent& event) void wxDocMDIParentFrame::OnCloseWindow(wxCloseEvent& event)
{ {
if (m_docManager->Clear(!event.CanVeto())) if (m_docManager->Clear(!event.CanVeto()))
{ {
this->Destroy(); this->Destroy();
} }
else else
event.Veto(); event.Veto();
} }
/* /*
* Default document child frame for MDI children * Default document child frame for MDI children
*/ */
IMPLEMENT_CLASS(wxDocMDIChildFrame, wxMDIChildFrame) IMPLEMENT_CLASS(wxDocMDIChildFrame, wxMDIChildFrame)
BEGIN_EVENT_TABLE(wxDocMDIChildFrame, wxMDIChildFrame) BEGIN_EVENT_TABLE(wxDocMDIChildFrame, wxMDIChildFrame)
EVT_ACTIVATE(wxDocMDIChildFrame::OnActivate) EVT_ACTIVATE(wxDocMDIChildFrame::OnActivate)
EVT_CLOSE(wxDocMDIChildFrame::OnCloseWindow) EVT_CLOSE(wxDocMDIChildFrame::OnCloseWindow)
END_EVENT_TABLE() END_EVENT_TABLE()
void wxDocMDIChildFrame::Init() void wxDocMDIChildFrame::Init()
{ {
m_childDocument = (wxDocument*) NULL; m_childDocument = (wxDocument*) NULL;
m_childView = (wxView*) NULL; m_childView = (wxView*) NULL;
} }
wxDocMDIChildFrame::wxDocMDIChildFrame() wxDocMDIChildFrame::wxDocMDIChildFrame()
{ {
Init(); Init();
} }
wxDocMDIChildFrame::wxDocMDIChildFrame(wxDocument *doc, wxView *view, wxMDIParentFrame *frame, wxWindowID id, wxDocMDIChildFrame::wxDocMDIChildFrame(wxDocument *doc, wxView *view, wxMDIParentFrame *frame, wxWindowID id,
const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name)
{ {
Init(); Init();
Create(doc, view, frame, id, title, pos, size, style, name); Create(doc, view, frame, id, title, pos, size, style, name);
} }
bool wxDocMDIChildFrame::Create(wxDocument *doc, wxView *view, wxMDIParentFrame *frame, wxWindowID id, bool wxDocMDIChildFrame::Create(wxDocument *doc, wxView *view, wxMDIParentFrame *frame, wxWindowID id,
const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name) const wxString& title, const wxPoint& pos, const wxSize& size, long style, const wxString& name)
{ {
m_childDocument = doc; m_childDocument = doc;
m_childView = view; m_childView = view;
if (wxMDIChildFrame::Create(frame, id, title, pos, size, style, name)) if (wxMDIChildFrame::Create(frame, id, title, pos, size, style, name))
{ {
if (view) if (view)
view->SetFrame(this); view->SetFrame(this);
return true; return true;
} }
return false; return false;
} }
wxDocMDIChildFrame::~wxDocMDIChildFrame(void) wxDocMDIChildFrame::~wxDocMDIChildFrame(void)
{ {
m_childView = (wxView *) NULL; m_childView = (wxView *) NULL;
} }
// Extend event processing to search the view's event table // Extend event processing to search the view's event table
bool wxDocMDIChildFrame::ProcessEvent(wxEvent& event) bool wxDocMDIChildFrame::ProcessEvent(wxEvent& event)
{ {
static wxEvent *ActiveEvent = NULL; static wxEvent *ActiveEvent = NULL;
// Break recursion loops // Break recursion loops
if (ActiveEvent == &event) if (ActiveEvent == &event)
return false; return false;
ActiveEvent = &event; ActiveEvent = &event;
bool ret; bool ret;
if ( !m_childView || ! m_childView->ProcessEvent(event) ) if ( !m_childView || ! m_childView->ProcessEvent(event) )
{ {
// Only hand up to the parent if it's a menu command // Only hand up to the parent if it's a menu command
if (!event.IsKindOf(CLASSINFO(wxCommandEvent)) || !GetParent() || !GetParent()->ProcessEvent(event)) if (!event.IsKindOf(CLASSINFO(wxCommandEvent)) || !GetParent() || !GetParent()->ProcessEvent(event))
ret = wxEvtHandler::ProcessEvent(event); ret = wxEvtHandler::ProcessEvent(event);
else else
ret = true; ret = true;
} }
else else
ret = true; ret = true;
ActiveEvent = NULL; ActiveEvent = NULL;
return ret; return ret;
} }
void wxDocMDIChildFrame::OnActivate(wxActivateEvent& event) void wxDocMDIChildFrame::OnActivate(wxActivateEvent& event)
{ {
wxMDIChildFrame::OnActivate(event); wxMDIChildFrame::OnActivate(event);
if (event.GetActive() && m_childView) if (event.GetActive() && m_childView)
m_childView->Activate(event.GetActive()); m_childView->Activate(event.GetActive());
} }
void wxDocMDIChildFrame::OnCloseWindow(wxCloseEvent& event) void wxDocMDIChildFrame::OnCloseWindow(wxCloseEvent& event)
{ {
// Close view but don't delete the frame while doing so! // Close view but don't delete the frame while doing so!
// ...since it will be deleted by wxWidgets if we return true. // ...since it will be deleted by wxWidgets if we return true.
if (m_childView) if (m_childView)
{ {
bool ans = event.CanVeto() bool ans = event.CanVeto()
? m_childView->Close(false) // false means don't delete associated window ? m_childView->Close(false) // false means don't delete associated window
: true; // Must delete. : true; // Must delete.
if (ans) if (ans)
{ {
m_childView->Activate(false); m_childView->Activate(false);
delete m_childView; delete m_childView;
m_childView = (wxView *) NULL; m_childView = (wxView *) NULL;
m_childDocument = (wxDocument *) NULL; m_childDocument = (wxDocument *) NULL;
this->Destroy(); this->Destroy();
} }
else else
event.Veto(); event.Veto();
} }
else else
event.Veto(); event.Veto();
} }
#endif #endif
// wxUSE_DOC_VIEW_ARCHITECTURE // wxUSE_DOC_VIEW_ARCHITECTURE

File diff suppressed because it is too large Load Diff

View File

@ -1,269 +1,269 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/dpycmn.cpp // Name: src/common/dpycmn.cpp
// Purpose: wxDisplay and wxDisplayImplSingle implementation // Purpose: wxDisplay and wxDisplayImplSingle implementation
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 01.03.03 // Created: 01.03.03
// RCS-ID: $Id: dpycmn.cpp 41548 2006-10-02 05:38:05Z PC $ // RCS-ID: $Id: dpycmn.cpp 41548 2006-10-02 05:38:05Z PC $
// Copyright: (c) 2003-2006 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 2003-2006 Vadim Zeitlin <vadim@wxwindows.org>
// License: wxWindows licence // License: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/gdicmn.h" #include "wx/gdicmn.h"
#include "wx/window.h" #include "wx/window.h"
#include "wx/module.h" #include "wx/module.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
#include "wx/display.h" #include "wx/display.h"
#include "wx/display_impl.h" #include "wx/display_impl.h"
#if wxUSE_DISPLAY #if wxUSE_DISPLAY
#include "wx/arrimpl.cpp" #include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(wxArrayVideoModes) WX_DEFINE_OBJARRAY(wxArrayVideoModes)
const wxVideoMode wxDefaultVideoMode; const wxVideoMode wxDefaultVideoMode;
#endif // wxUSE_DISPLAY #endif // wxUSE_DISPLAY
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// globals // globals
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// the factory object used by wxDisplay // the factory object used by wxDisplay
// //
// created on demand and destroyed by wxDisplayModule // created on demand and destroyed by wxDisplayModule
static wxDisplayFactory *gs_factory = NULL; static wxDisplayFactory *gs_factory = NULL;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDisplayImplSingle: trivial implementation working for main display only // wxDisplayImplSingle: trivial implementation working for main display only
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class WXDLLEXPORT wxDisplayImplSingle : public wxDisplayImpl class WXDLLEXPORT wxDisplayImplSingle : public wxDisplayImpl
{ {
public: public:
wxDisplayImplSingle() : wxDisplayImpl(0) { } wxDisplayImplSingle() : wxDisplayImpl(0) { }
virtual wxRect GetGeometry() const virtual wxRect GetGeometry() const
{ {
wxRect r; wxRect r;
wxDisplaySize(&r.width, &r.height); wxDisplaySize(&r.width, &r.height);
return r; return r;
} }
virtual wxRect GetClientArea() const { return wxGetClientDisplayRect(); } virtual wxRect GetClientArea() const { return wxGetClientDisplayRect(); }
virtual wxString GetName() const { return wxString(); } virtual wxString GetName() const { return wxString(); }
#if wxUSE_DISPLAY #if wxUSE_DISPLAY
// no video modes support for us, provide just the stubs // no video modes support for us, provide just the stubs
virtual wxArrayVideoModes GetModes(const wxVideoMode& WXUNUSED(mode)) const virtual wxArrayVideoModes GetModes(const wxVideoMode& WXUNUSED(mode)) const
{ {
return wxArrayVideoModes(); return wxArrayVideoModes();
} }
virtual wxVideoMode GetCurrentMode() const { return wxVideoMode(); } virtual wxVideoMode GetCurrentMode() const { return wxVideoMode(); }
virtual bool ChangeMode(const wxVideoMode& WXUNUSED(mode)) { return false; } virtual bool ChangeMode(const wxVideoMode& WXUNUSED(mode)) { return false; }
#endif // wxUSE_DISPLAY #endif // wxUSE_DISPLAY
DECLARE_NO_COPY_CLASS(wxDisplayImplSingle) DECLARE_NO_COPY_CLASS(wxDisplayImplSingle)
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDisplayModule is used to cleanup gs_factory // wxDisplayModule is used to cleanup gs_factory
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class wxDisplayModule : public wxModule class wxDisplayModule : public wxModule
{ {
public: public:
virtual bool OnInit() { return true; } virtual bool OnInit() { return true; }
virtual void OnExit() virtual void OnExit()
{ {
if ( gs_factory ) if ( gs_factory )
{ {
delete gs_factory; delete gs_factory;
gs_factory = NULL; gs_factory = NULL;
} }
} }
DECLARE_DYNAMIC_CLASS(wxDisplayModule) DECLARE_DYNAMIC_CLASS(wxDisplayModule)
}; };
IMPLEMENT_DYNAMIC_CLASS(wxDisplayModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxDisplayModule, wxModule)
// ============================================================================ // ============================================================================
// wxDisplay implementation // wxDisplay implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// ctor/dtor // ctor/dtor
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxDisplay::wxDisplay(unsigned n) wxDisplay::wxDisplay(unsigned n)
{ {
wxASSERT_MSG( n < GetCount(), wxASSERT_MSG( n < GetCount(),
wxT("An invalid index was passed to wxDisplay") ); wxT("An invalid index was passed to wxDisplay") );
m_impl = Factory().CreateDisplay(n); m_impl = Factory().CreateDisplay(n);
} }
wxDisplay::~wxDisplay() wxDisplay::~wxDisplay()
{ {
delete m_impl; delete m_impl;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// static functions forwarded to wxDisplayFactory // static functions forwarded to wxDisplayFactory
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/* static */ unsigned wxDisplay::GetCount() /* static */ unsigned wxDisplay::GetCount()
{ {
return Factory().GetCount(); return Factory().GetCount();
} }
/* static */ int wxDisplay::GetFromPoint(const wxPoint& pt) /* static */ int wxDisplay::GetFromPoint(const wxPoint& pt)
{ {
return Factory().GetFromPoint(pt); return Factory().GetFromPoint(pt);
} }
/* static */ int wxDisplay::GetFromWindow(wxWindow *window) /* static */ int wxDisplay::GetFromWindow(wxWindow *window)
{ {
wxCHECK_MSG( window, wxNOT_FOUND, _T("invalid window") ); wxCHECK_MSG( window, wxNOT_FOUND, _T("invalid window") );
return Factory().GetFromWindow(window); return Factory().GetFromWindow(window);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// functions forwarded to wxDisplayImpl // functions forwarded to wxDisplayImpl
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxRect wxDisplay::GetGeometry() const wxRect wxDisplay::GetGeometry() const
{ {
wxCHECK_MSG( IsOk(), wxRect(), _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), wxRect(), _T("invalid wxDisplay object") );
return m_impl->GetGeometry(); return m_impl->GetGeometry();
} }
wxRect wxDisplay::GetClientArea() const wxRect wxDisplay::GetClientArea() const
{ {
wxCHECK_MSG( IsOk(), wxRect(), _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), wxRect(), _T("invalid wxDisplay object") );
return m_impl->GetClientArea(); return m_impl->GetClientArea();
} }
wxString wxDisplay::GetName() const wxString wxDisplay::GetName() const
{ {
wxCHECK_MSG( IsOk(), wxString(), _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), wxString(), _T("invalid wxDisplay object") );
return m_impl->GetName(); return m_impl->GetName();
} }
bool wxDisplay::IsPrimary() const bool wxDisplay::IsPrimary() const
{ {
return m_impl && m_impl->GetIndex() == 0; return m_impl && m_impl->GetIndex() == 0;
} }
#if wxUSE_DISPLAY #if wxUSE_DISPLAY
wxArrayVideoModes wxDisplay::GetModes(const wxVideoMode& mode) const wxArrayVideoModes wxDisplay::GetModes(const wxVideoMode& mode) const
{ {
wxCHECK_MSG( IsOk(), wxArrayVideoModes(), _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), wxArrayVideoModes(), _T("invalid wxDisplay object") );
return m_impl->GetModes(mode); return m_impl->GetModes(mode);
} }
wxVideoMode wxDisplay::GetCurrentMode() const wxVideoMode wxDisplay::GetCurrentMode() const
{ {
wxCHECK_MSG( IsOk(), wxVideoMode(), _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), wxVideoMode(), _T("invalid wxDisplay object") );
return m_impl->GetCurrentMode(); return m_impl->GetCurrentMode();
} }
bool wxDisplay::ChangeMode(const wxVideoMode& mode) bool wxDisplay::ChangeMode(const wxVideoMode& mode)
{ {
wxCHECK_MSG( IsOk(), false, _T("invalid wxDisplay object") ); wxCHECK_MSG( IsOk(), false, _T("invalid wxDisplay object") );
return m_impl->ChangeMode(mode); return m_impl->ChangeMode(mode);
} }
#endif // wxUSE_DIRECTDRAW #endif // wxUSE_DIRECTDRAW
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// static functions implementation // static functions implementation
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// if wxUSE_DISPLAY == 1 this is implemented in port-specific code // if wxUSE_DISPLAY == 1 this is implemented in port-specific code
#if !wxUSE_DISPLAY #if !wxUSE_DISPLAY
/* static */ wxDisplayFactory *wxDisplay::CreateFactory() /* static */ wxDisplayFactory *wxDisplay::CreateFactory()
{ {
return new wxDisplayFactorySingle; return new wxDisplayFactorySingle;
} }
#endif // !wxUSE_DISPLAY #endif // !wxUSE_DISPLAY
/* static */ wxDisplayFactory& wxDisplay::Factory() /* static */ wxDisplayFactory& wxDisplay::Factory()
{ {
if ( !gs_factory ) if ( !gs_factory )
{ {
gs_factory = CreateFactory(); gs_factory = CreateFactory();
} }
return *gs_factory; return *gs_factory;
} }
// ============================================================================ // ============================================================================
// wxDisplayFactory implementation // wxDisplayFactory implementation
// ============================================================================ // ============================================================================
int wxDisplayFactory::GetFromWindow(wxWindow *window) int wxDisplayFactory::GetFromWindow(wxWindow *window)
{ {
// consider that the window belongs to the display containing its centre // consider that the window belongs to the display containing its centre
const wxRect r(window->GetRect()); const wxRect r(window->GetRect());
return GetFromPoint(wxPoint(r.x + r.width/2, r.y + r.height/2)); return GetFromPoint(wxPoint(r.x + r.width/2, r.y + r.height/2));
} }
// ============================================================================ // ============================================================================
// wxDisplayFactorySingle implementation // wxDisplayFactorySingle implementation
// ============================================================================ // ============================================================================
/* static */ /* static */
wxDisplayImpl *wxDisplayFactorySingle::CreateDisplay(unsigned n) wxDisplayImpl *wxDisplayFactorySingle::CreateDisplay(unsigned n)
{ {
// we recognize the main display only // we recognize the main display only
return n != 0 ? NULL : new wxDisplayImplSingle; return n != 0 ? NULL : new wxDisplayImplSingle;
} }
int wxDisplayFactorySingle::GetFromPoint(const wxPoint& pt) int wxDisplayFactorySingle::GetFromPoint(const wxPoint& pt)
{ {
if ( pt.x >= 0 && pt.y >= 0 ) if ( pt.x >= 0 && pt.y >= 0 )
{ {
int w, h; int w, h;
wxDisplaySize(&w, &h); wxDisplaySize(&w, &h);
if ( pt.x < w && pt.y < h ) if ( pt.x < w && pt.y < h )
return 0; return 0;
} }
// the point is outside of the screen // the point is outside of the screen
return wxNOT_FOUND; return wxNOT_FOUND;
} }

View File

@ -1,55 +1,55 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/dseldlg.cpp // Name: src/common/dseldlg.cpp
// Purpose: implementation of ::wxDirSelector() // Purpose: implementation of ::wxDirSelector()
// Author: Paul Thiessen // Author: Paul Thiessen
// Modified by: // Modified by:
// Created: 20.02.01 // Created: 20.02.01
// RCS-ID: $Id: dseldlg.cpp 39613 2006-06-07 11:44:19Z ABX $ // RCS-ID: $Id: dseldlg.cpp 39613 2006-06-07 11:44:19Z ABX $
// Copyright: (c) 2001 wxWidgets team // Copyright: (c) 2001 wxWidgets team
// License: wxWindows licence // License: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_DIRDLG #if wxUSE_DIRDLG
#include "wx/dirdlg.h" #include "wx/dirdlg.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif //WX_PRECOMP #endif //WX_PRECOMP
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
wxString wxDirSelector(const wxString& message, wxString wxDirSelector(const wxString& message,
const wxString& defaultPath, const wxString& defaultPath,
long style, long style,
const wxPoint& pos, const wxPoint& pos,
wxWindow *parent) wxWindow *parent)
{ {
wxString path; wxString path;
wxDirDialog dirDialog(parent, message, defaultPath, style, pos); wxDirDialog dirDialog(parent, message, defaultPath, style, pos);
if ( dirDialog.ShowModal() == wxID_OK ) if ( dirDialog.ShowModal() == wxID_OK )
{ {
path = dirDialog.GetPath(); path = dirDialog.GetPath();
} }
return path; return path;
} }
#endif // wxUSE_DIRDLG #endif // wxUSE_DIRDLG

View File

@ -1,32 +1,32 @@
/* /*
* File: src/common/dummy.cpp * File: src/common/dummy.cpp
* Purpose: See below * Purpose: See below
* Author: Julian Smart * Author: Julian Smart
* Created: 1993 * Created: 1993
* Updated: * Updated:
* Copyright: (c) 1993, AIAI, University of Edinburgh * Copyright: (c) 1993, AIAI, University of Edinburgh
*/ */
/* A dummy file to include wx.h. If precompiling wx.h, /* A dummy file to include wx.h. If precompiling wx.h,
* always start by compiling this and producing the PCH file. * always start by compiling this and producing the PCH file.
* Then subsequent source files use the PCH file. * Then subsequent source files use the PCH file.
* *
* If precompiling wx.h for wxWidgets and derived apps, * If precompiling wx.h for wxWidgets and derived apps,
* link dummy.obj with your program. * link dummy.obj with your program.
* *
* This will produce a big PCH file. * This will produce a big PCH file.
*/ */
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifdef __WXMSW__ #ifdef __WXMSW__
#include "wx/msw/msvcrt.h" #include "wx/msw/msvcrt.h"
#endif #endif
#ifdef __VISAGECPP__ #ifdef __VISAGECPP__
char wxDummyChar = 0; char wxDummyChar = 0;
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -1,323 +1,323 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/dynlib.cpp // Name: src/common/dynlib.cpp
// Purpose: Dynamic library management // Purpose: Dynamic library management
// Author: Guilhem Lavaux // Author: Guilhem Lavaux
// Modified by: // Modified by:
// Created: 20/07/98 // Created: 20/07/98
// RCS-ID: $Id: dynlib.cpp 41807 2006-10-09 15:58:56Z VZ $ // RCS-ID: $Id: dynlib.cpp 41807 2006-10-09 15:58:56Z VZ $
// Copyright: (c) 1998 Guilhem Lavaux // Copyright: (c) 1998 Guilhem Lavaux
// 2000-2005 Vadim Zeitlin // 2000-2005 Vadim Zeitlin
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
//FIXME: This class isn't really common at all, it should be moved into //FIXME: This class isn't really common at all, it should be moved into
// platform dependent files (already done for Windows and Unix) // platform dependent files (already done for Windows and Unix)
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_DYNLIB_CLASS #if wxUSE_DYNLIB_CLASS
#include "wx/dynlib.h" #include "wx/dynlib.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/app.h" #include "wx/app.h"
#include "wx/utils.h" #include "wx/utils.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
#include "wx/filefn.h" #include "wx/filefn.h"
#include "wx/filename.h" // for SplitPath() #include "wx/filename.h" // for SplitPath()
#include "wx/platinfo.h" #include "wx/platinfo.h"
#include "wx/arrimpl.cpp" #include "wx/arrimpl.cpp"
#if defined(__WXMAC__) #if defined(__WXMAC__)
#include "wx/mac/private.h" #include "wx/mac/private.h"
#endif #endif
WX_DEFINE_USER_EXPORTED_OBJARRAY(wxDynamicLibraryDetailsArray) WX_DEFINE_USER_EXPORTED_OBJARRAY(wxDynamicLibraryDetailsArray)
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// wxDynamicLibrary // wxDynamicLibrary
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
#if defined(__WXPM__) || defined(__EMX__) #if defined(__WXPM__) || defined(__EMX__)
const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll"); const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll");
#elif defined(__WXMAC__) && !defined(__DARWIN__) #elif defined(__WXMAC__) && !defined(__DARWIN__)
const wxChar *wxDynamicLibrary::ms_dllext = wxEmptyString; const wxChar *wxDynamicLibrary::ms_dllext = wxEmptyString;
#endif #endif
// for MSW/Unix it is defined in platform-specific file // for MSW/Unix it is defined in platform-specific file
#if !(defined(__WXMSW__) || defined(__UNIX__)) || defined(__EMX__) #if !(defined(__WXMSW__) || defined(__UNIX__)) || defined(__EMX__)
wxDllType wxDynamicLibrary::GetProgramHandle() wxDllType wxDynamicLibrary::GetProgramHandle()
{ {
wxFAIL_MSG( wxT("GetProgramHandle() is not implemented under this platform")); wxFAIL_MSG( wxT("GetProgramHandle() is not implemented under this platform"));
return 0; return 0;
} }
#endif // __WXMSW__ || __UNIX__ #endif // __WXMSW__ || __UNIX__
bool wxDynamicLibrary::Load(const wxString& libnameOrig, int flags) bool wxDynamicLibrary::Load(const wxString& libnameOrig, int flags)
{ {
wxASSERT_MSG(m_handle == 0, _T("Library already loaded.")); wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
// add the proper extension for the DLL ourselves unless told not to // add the proper extension for the DLL ourselves unless told not to
wxString libname = libnameOrig; wxString libname = libnameOrig;
if ( !(flags & wxDL_VERBATIM) ) if ( !(flags & wxDL_VERBATIM) )
{ {
// and also check that the libname doesn't already have it // and also check that the libname doesn't already have it
wxString ext; wxString ext;
wxFileName::SplitPath(libname, NULL, NULL, &ext); wxFileName::SplitPath(libname, NULL, NULL, &ext);
if ( ext.empty() ) if ( ext.empty() )
{ {
libname += GetDllExt(); libname += GetDllExt();
} }
} }
// different ways to load a shared library // different ways to load a shared library
// //
// FIXME: should go to the platform-specific files! // FIXME: should go to the platform-specific files!
#if defined(__WXMAC__) && !defined(__DARWIN__) #if defined(__WXMAC__) && !defined(__DARWIN__)
FSSpec myFSSpec; FSSpec myFSSpec;
Ptr myMainAddr; Ptr myMainAddr;
Str255 myErrName; Str255 myErrName;
wxMacFilename2FSSpec( libname , &myFSSpec ); wxMacFilename2FSSpec( libname , &myFSSpec );
if( GetDiskFragment( &myFSSpec, if( GetDiskFragment( &myFSSpec,
0, 0,
kCFragGoesToEOF, kCFragGoesToEOF,
"\p", "\p",
kPrivateCFragCopy, kPrivateCFragCopy,
&m_handle, &m_handle,
&myMainAddr, &myMainAddr,
myErrName ) != noErr ) myErrName ) != noErr )
{ {
wxLogSysError( _("Failed to load shared library '%s' Error '%s'"), wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
libname.c_str(), libname.c_str(),
wxMacMakeStringFromPascal( myErrName ).c_str() ); wxMacMakeStringFromPascal( myErrName ).c_str() );
m_handle = 0; m_handle = 0;
} }
#elif defined(__WXPM__) || defined(__EMX__) #elif defined(__WXPM__) || defined(__EMX__)
char err[256] = ""; char err[256] = "";
DosLoadModule(err, sizeof(err), (PSZ)libname.c_str(), &m_handle); DosLoadModule(err, sizeof(err), (PSZ)libname.c_str(), &m_handle);
#else // this should be the only remaining branch eventually #else // this should be the only remaining branch eventually
m_handle = RawLoad(libname, flags); m_handle = RawLoad(libname, flags);
#endif #endif
if ( m_handle == 0 ) if ( m_handle == 0 )
{ {
#ifdef wxHAVE_DYNLIB_ERROR #ifdef wxHAVE_DYNLIB_ERROR
Error(); Error();
#else #else
wxLogSysError(_("Failed to load shared library '%s'"), libname.c_str()); wxLogSysError(_("Failed to load shared library '%s'"), libname.c_str());
#endif #endif
} }
return IsLoaded(); return IsLoaded();
} }
// for MSW and Unix this is implemented in the platform-specific file // for MSW and Unix this is implemented in the platform-specific file
// //
// TODO: move the rest to os2/dlpm.cpp and mac/dlmac.cpp! // TODO: move the rest to os2/dlpm.cpp and mac/dlmac.cpp!
#if (!defined(__WXMSW__) && !defined(__UNIX__)) || defined(__EMX__) #if (!defined(__WXMSW__) && !defined(__UNIX__)) || defined(__EMX__)
/* static */ /* static */
void wxDynamicLibrary::Unload(wxDllType handle) void wxDynamicLibrary::Unload(wxDllType handle)
{ {
#if defined(__OS2__) || defined(__EMX__) #if defined(__OS2__) || defined(__EMX__)
DosFreeModule( handle ); DosFreeModule( handle );
#elif defined(__WXMAC__) && !defined(__DARWIN__) #elif defined(__WXMAC__) && !defined(__DARWIN__)
CloseConnection( (CFragConnectionID*) &handle ); CloseConnection( (CFragConnectionID*) &handle );
#else #else
#error "runtime shared lib support not implemented" #error "runtime shared lib support not implemented"
#endif #endif
} }
#endif // !(__WXMSW__ || __UNIX__) #endif // !(__WXMSW__ || __UNIX__)
void *wxDynamicLibrary::DoGetSymbol(const wxString &name, bool *success) const void *wxDynamicLibrary::DoGetSymbol(const wxString &name, bool *success) const
{ {
wxCHECK_MSG( IsLoaded(), NULL, wxCHECK_MSG( IsLoaded(), NULL,
_T("Can't load symbol from unloaded library") ); _T("Can't load symbol from unloaded library") );
void *symbol = 0; void *symbol = 0;
wxUnusedVar(symbol); wxUnusedVar(symbol);
#if defined(__WXMAC__) && !defined(__DARWIN__) #if defined(__WXMAC__) && !defined(__DARWIN__)
Ptr symAddress; Ptr symAddress;
CFragSymbolClass symClass; CFragSymbolClass symClass;
Str255 symName; Str255 symName;
#if TARGET_CARBON #if TARGET_CARBON
c2pstrcpy( (StringPtr) symName, name.fn_str() ); c2pstrcpy( (StringPtr) symName, name.fn_str() );
#else #else
strcpy( (char *)symName, name.fn_str() ); strcpy( (char *)symName, name.fn_str() );
c2pstr( (char *)symName ); c2pstr( (char *)symName );
#endif #endif
if( FindSymbol( m_handle, symName, &symAddress, &symClass ) == noErr ) if( FindSymbol( m_handle, symName, &symAddress, &symClass ) == noErr )
symbol = (void *)symAddress; symbol = (void *)symAddress;
#elif defined(__WXPM__) || defined(__EMX__) #elif defined(__WXPM__) || defined(__EMX__)
DosQueryProcAddr( m_handle, 1L, (PSZ)name.c_str(), (PFN*)symbol ); DosQueryProcAddr( m_handle, 1L, (PSZ)name.c_str(), (PFN*)symbol );
#else #else
symbol = RawGetSymbol(m_handle, name); symbol = RawGetSymbol(m_handle, name);
#endif #endif
if ( success ) if ( success )
*success = symbol != NULL; *success = symbol != NULL;
return symbol; return symbol;
} }
void *wxDynamicLibrary::GetSymbol(const wxString& name, bool *success) const void *wxDynamicLibrary::GetSymbol(const wxString& name, bool *success) const
{ {
void *symbol = DoGetSymbol(name, success); void *symbol = DoGetSymbol(name, success);
if ( !symbol ) if ( !symbol )
{ {
#ifdef wxHAVE_DYNLIB_ERROR #ifdef wxHAVE_DYNLIB_ERROR
Error(); Error();
#else #else
wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"), wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
name.c_str()); name.c_str());
#endif #endif
} }
return symbol; return symbol;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// informational methods // informational methods
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/*static*/ /*static*/
wxString wxString
wxDynamicLibrary::CanonicalizeName(const wxString& name, wxDynamicLibrary::CanonicalizeName(const wxString& name,
wxDynamicLibraryCategory cat) wxDynamicLibraryCategory cat)
{ {
wxString nameCanonic; wxString nameCanonic;
// under Unix the library names usually start with "lib" prefix, add it // under Unix the library names usually start with "lib" prefix, add it
#if defined(__UNIX__) && !defined(__EMX__) #if defined(__UNIX__) && !defined(__EMX__)
switch ( cat ) switch ( cat )
{ {
default: default:
wxFAIL_MSG( _T("unknown wxDynamicLibraryCategory value") ); wxFAIL_MSG( _T("unknown wxDynamicLibraryCategory value") );
// fall through // fall through
case wxDL_MODULE: case wxDL_MODULE:
// don't do anything for modules, their names are arbitrary // don't do anything for modules, their names are arbitrary
break; break;
case wxDL_LIBRARY: case wxDL_LIBRARY:
// library names should start with "lib" under Unix // library names should start with "lib" under Unix
nameCanonic = _T("lib"); nameCanonic = _T("lib");
break; break;
} }
#else // !__UNIX__ #else // !__UNIX__
wxUnusedVar(cat); wxUnusedVar(cat);
#endif // __UNIX__/!__UNIX__ #endif // __UNIX__/!__UNIX__
nameCanonic << name << GetDllExt(); nameCanonic << name << GetDllExt();
return nameCanonic; return nameCanonic;
} }
/*static*/ /*static*/
wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name, wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name,
wxPluginCategory cat) wxPluginCategory cat)
{ {
wxString suffix; wxString suffix;
if ( cat == wxDL_PLUGIN_GUI ) if ( cat == wxDL_PLUGIN_GUI )
{ {
suffix = wxPlatformInfo::Get().GetPortIdShortName(); suffix = wxPlatformInfo::Get().GetPortIdShortName();
} }
#if wxUSE_UNICODE #if wxUSE_UNICODE
suffix << _T('u'); suffix << _T('u');
#endif #endif
#ifdef __WXDEBUG__ #ifdef __WXDEBUG__
suffix << _T('d'); suffix << _T('d');
#endif #endif
if ( !suffix.empty() ) if ( !suffix.empty() )
suffix = wxString(_T("_")) + suffix; suffix = wxString(_T("_")) + suffix;
#define WXSTRINGIZE(x) #x #define WXSTRINGIZE(x) #x
#if defined(__UNIX__) && !defined(__EMX__) #if defined(__UNIX__) && !defined(__EMX__)
#if (wxMINOR_VERSION % 2) == 0 #if (wxMINOR_VERSION % 2) == 0
#define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y)
#else #else
#define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) "." WXSTRINGIZE(z) #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) "." WXSTRINGIZE(z)
#endif #endif
#else #else
#if (wxMINOR_VERSION % 2) == 0 #if (wxMINOR_VERSION % 2) == 0
#define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y)
#else #else
#define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z) #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z)
#endif #endif
#endif #endif
suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION, suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION,
wxRELEASE_NUMBER)); wxRELEASE_NUMBER));
#undef wxDLLVER #undef wxDLLVER
#undef WXSTRINGIZE #undef WXSTRINGIZE
#ifdef __WINDOWS__ #ifdef __WINDOWS__
// Add compiler identification: // Add compiler identification:
#if defined(__GNUG__) #if defined(__GNUG__)
suffix << _T("_gcc"); suffix << _T("_gcc");
#elif defined(__VISUALC__) #elif defined(__VISUALC__)
suffix << _T("_vc"); suffix << _T("_vc");
#elif defined(__WATCOMC__) #elif defined(__WATCOMC__)
suffix << _T("_wat"); suffix << _T("_wat");
#elif defined(__BORLANDC__) #elif defined(__BORLANDC__)
suffix << _T("_bcc"); suffix << _T("_bcc");
#endif #endif
#endif #endif
return CanonicalizeName(name + suffix, wxDL_MODULE); return CanonicalizeName(name + suffix, wxDL_MODULE);
} }
/*static*/ /*static*/
wxString wxDynamicLibrary::GetPluginsDirectory() wxString wxDynamicLibrary::GetPluginsDirectory()
{ {
#ifdef __UNIX__ #ifdef __UNIX__
wxString format = wxGetInstallPrefix(); wxString format = wxGetInstallPrefix();
wxString dir; wxString dir;
format << wxFILE_SEP_PATH format << wxFILE_SEP_PATH
<< wxT("lib") << wxFILE_SEP_PATH << wxT("lib") << wxFILE_SEP_PATH
<< wxT("wx") << wxFILE_SEP_PATH << wxT("wx") << wxFILE_SEP_PATH
#if (wxMINOR_VERSION % 2) == 0 #if (wxMINOR_VERSION % 2) == 0
<< wxT("%i.%i"); << wxT("%i.%i");
dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION); dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION);
#else #else
<< wxT("%i.%i.%i"); << wxT("%i.%i.%i");
dir.Printf(format.c_str(), dir.Printf(format.c_str(),
wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER); wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
#endif #endif
return dir; return dir;
#else // ! __UNIX__ #else // ! __UNIX__
return wxEmptyString; return wxEmptyString;
#endif #endif
} }
#endif // wxUSE_DYNLIB_CLASS #endif // wxUSE_DYNLIB_CLASS

View File

@ -1,362 +1,362 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/dynload.cpp // Name: src/common/dynload.cpp
// Purpose: Dynamic loading framework // Purpose: Dynamic loading framework
// Author: Ron Lee, David Falkinder, Vadim Zeitlin and a cast of 1000's // Author: Ron Lee, David Falkinder, Vadim Zeitlin and a cast of 1000's
// (derived in part from dynlib.cpp (c) 1998 Guilhem Lavaux) // (derived in part from dynlib.cpp (c) 1998 Guilhem Lavaux)
// Modified by: // Modified by:
// Created: 03/12/01 // Created: 03/12/01
// RCS-ID: $Id: dynload.cpp 40943 2006-08-31 19:31:43Z ABX $ // RCS-ID: $Id: dynload.cpp 40943 2006-08-31 19:31:43Z ABX $
// Copyright: (c) 2001 Ron Lee <ron@debian.org> // Copyright: (c) 2001 Ron Lee <ron@debian.org>
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_DYNAMIC_LOADER #if wxUSE_DYNAMIC_LOADER
#ifdef __WINDOWS__ #ifdef __WINDOWS__
#include "wx/msw/private.h" #include "wx/msw/private.h"
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/log.h" #include "wx/log.h"
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/hash.h" #include "wx/hash.h"
#include "wx/utils.h" #include "wx/utils.h"
#include "wx/module.h" #include "wx/module.h"
#endif #endif
#include "wx/strconv.h" #include "wx/strconv.h"
#include "wx/dynload.h" #include "wx/dynload.h"
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// wxPluginLibrary // wxPluginLibrary
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
wxDLImports* wxPluginLibrary::ms_classes = NULL; wxDLImports* wxPluginLibrary::ms_classes = NULL;
class wxPluginLibraryModule : public wxModule class wxPluginLibraryModule : public wxModule
{ {
public: public:
wxPluginLibraryModule() { } wxPluginLibraryModule() { }
// TODO: create ms_classes on demand, why always preallocate it? // TODO: create ms_classes on demand, why always preallocate it?
virtual bool OnInit() virtual bool OnInit()
{ {
wxPluginLibrary::ms_classes = new wxDLImports; wxPluginLibrary::ms_classes = new wxDLImports;
wxPluginManager::CreateManifest(); wxPluginManager::CreateManifest();
return true; return true;
} }
virtual void OnExit() virtual void OnExit()
{ {
delete wxPluginLibrary::ms_classes; delete wxPluginLibrary::ms_classes;
wxPluginLibrary::ms_classes = NULL; wxPluginLibrary::ms_classes = NULL;
wxPluginManager::ClearManifest(); wxPluginManager::ClearManifest();
} }
private: private:
DECLARE_DYNAMIC_CLASS(wxPluginLibraryModule ) DECLARE_DYNAMIC_CLASS(wxPluginLibraryModule )
}; };
IMPLEMENT_DYNAMIC_CLASS(wxPluginLibraryModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxPluginLibraryModule, wxModule)
wxPluginLibrary::wxPluginLibrary(const wxString &libname, int flags) wxPluginLibrary::wxPluginLibrary(const wxString &libname, int flags)
: m_linkcount(1) : m_linkcount(1)
, m_objcount(0) , m_objcount(0)
{ {
m_before = wxClassInfo::sm_first; m_before = wxClassInfo::sm_first;
Load( libname, flags ); Load( libname, flags );
m_after = wxClassInfo::sm_first; m_after = wxClassInfo::sm_first;
if( m_handle != 0 ) if( m_handle != 0 )
{ {
UpdateClasses(); UpdateClasses();
RegisterModules(); RegisterModules();
} }
else else
{ {
// Flag us for deletion // Flag us for deletion
--m_linkcount; --m_linkcount;
} }
} }
wxPluginLibrary::~wxPluginLibrary() wxPluginLibrary::~wxPluginLibrary()
{ {
if( m_handle != 0 ) if( m_handle != 0 )
{ {
UnregisterModules(); UnregisterModules();
RestoreClasses(); RestoreClasses();
} }
} }
wxPluginLibrary *wxPluginLibrary::RefLib() wxPluginLibrary *wxPluginLibrary::RefLib()
{ {
wxCHECK_MSG( m_linkcount > 0, NULL, wxCHECK_MSG( m_linkcount > 0, NULL,
_T("Library had been already deleted!") ); _T("Library had been already deleted!") );
++m_linkcount; ++m_linkcount;
return this; return this;
} }
bool wxPluginLibrary::UnrefLib() bool wxPluginLibrary::UnrefLib()
{ {
wxASSERT_MSG( m_objcount == 0, wxASSERT_MSG( m_objcount == 0,
_T("Library unloaded before all objects were destroyed") ); _T("Library unloaded before all objects were destroyed") );
if ( m_linkcount == 0 || --m_linkcount == 0 ) if ( m_linkcount == 0 || --m_linkcount == 0 )
{ {
delete this; delete this;
return true; return true;
} }
return false; return false;
} }
// ------------------------ // ------------------------
// Private methods // Private methods
// ------------------------ // ------------------------
void wxPluginLibrary::UpdateClasses() void wxPluginLibrary::UpdateClasses()
{ {
for (wxClassInfo *info = m_after; info != m_before; info = info->m_next) for (wxClassInfo *info = m_after; info != m_before; info = info->m_next)
{ {
if( info->GetClassName() ) if( info->GetClassName() )
{ {
// Hash all the class names into a local table too so // Hash all the class names into a local table too so
// we can quickly find the entry they correspond to. // we can quickly find the entry they correspond to.
(*ms_classes)[info->GetClassName()] = this; (*ms_classes)[info->GetClassName()] = this;
} }
} }
} }
void wxPluginLibrary::RestoreClasses() void wxPluginLibrary::RestoreClasses()
{ {
// Check if there is a need to restore classes. // Check if there is a need to restore classes.
if (!ms_classes) if (!ms_classes)
return; return;
for(wxClassInfo *info = m_after; info != m_before; info = info->m_next) for(wxClassInfo *info = m_after; info != m_before; info = info->m_next)
{ {
ms_classes->erase(ms_classes->find(info->GetClassName())); ms_classes->erase(ms_classes->find(info->GetClassName()));
} }
} }
void wxPluginLibrary::RegisterModules() void wxPluginLibrary::RegisterModules()
{ {
// Plugin libraries might have wxModules, Register and initialise them if // Plugin libraries might have wxModules, Register and initialise them if
// they do. // they do.
// //
// Note that these classes are NOT included in the reference counting since // Note that these classes are NOT included in the reference counting since
// it's implicit that they will be unloaded if and when the last handle to // it's implicit that they will be unloaded if and when the last handle to
// the library is. We do have to keep a copy of the module's pointer // the library is. We do have to keep a copy of the module's pointer
// though, as there is currently no way to Unregister it without it. // though, as there is currently no way to Unregister it without it.
wxASSERT_MSG( m_linkcount == 1, wxASSERT_MSG( m_linkcount == 1,
_T("RegisterModules should only be called for the first load") ); _T("RegisterModules should only be called for the first load") );
for ( wxClassInfo *info = m_after; info != m_before; info = info->m_next) for ( wxClassInfo *info = m_after; info != m_before; info = info->m_next)
{ {
if( info->IsKindOf(CLASSINFO(wxModule)) ) if( info->IsKindOf(CLASSINFO(wxModule)) )
{ {
wxModule *m = wxDynamicCast(info->CreateObject(), wxModule); wxModule *m = wxDynamicCast(info->CreateObject(), wxModule);
wxASSERT_MSG( m, _T("wxDynamicCast of wxModule failed") ); wxASSERT_MSG( m, _T("wxDynamicCast of wxModule failed") );
m_wxmodules.push_back(m); m_wxmodules.push_back(m);
wxModule::RegisterModule(m); wxModule::RegisterModule(m);
} }
} }
// FIXME: Likewise this is (well was) very similar to InitializeModules() // FIXME: Likewise this is (well was) very similar to InitializeModules()
for ( wxModuleList::iterator it = m_wxmodules.begin(); for ( wxModuleList::iterator it = m_wxmodules.begin();
it != m_wxmodules.end(); it != m_wxmodules.end();
++it) ++it)
{ {
if( !(*it)->Init() ) if( !(*it)->Init() )
{ {
wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary")); wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
// XXX: Watch this, a different hash implementation might break it, // XXX: Watch this, a different hash implementation might break it,
// a good hash implementation would let us fix it though. // a good hash implementation would let us fix it though.
// The name of the game is to remove any uninitialised modules and // The name of the game is to remove any uninitialised modules and
// let the dtor Exit the rest on shutdown, (which we'll initiate // let the dtor Exit the rest on shutdown, (which we'll initiate
// shortly). // shortly).
wxModuleList::iterator oldNode = m_wxmodules.end(); wxModuleList::iterator oldNode = m_wxmodules.end();
do { do {
++it; ++it;
if( oldNode != m_wxmodules.end() ) if( oldNode != m_wxmodules.end() )
m_wxmodules.erase(oldNode); m_wxmodules.erase(oldNode);
wxModule::UnregisterModule( *it ); wxModule::UnregisterModule( *it );
oldNode = it; oldNode = it;
} while( it != m_wxmodules.end() ); } while( it != m_wxmodules.end() );
--m_linkcount; // Flag us for deletion --m_linkcount; // Flag us for deletion
break; break;
} }
} }
} }
void wxPluginLibrary::UnregisterModules() void wxPluginLibrary::UnregisterModules()
{ {
wxModuleList::iterator it; wxModuleList::iterator it;
for ( it = m_wxmodules.begin(); it != m_wxmodules.end(); ++it ) for ( it = m_wxmodules.begin(); it != m_wxmodules.end(); ++it )
(*it)->Exit(); (*it)->Exit();
for ( it = m_wxmodules.begin(); it != m_wxmodules.end(); ++it ) for ( it = m_wxmodules.begin(); it != m_wxmodules.end(); ++it )
wxModule::UnregisterModule( *it ); wxModule::UnregisterModule( *it );
// NB: content of the list was deleted by UnregisterModule calls above: // NB: content of the list was deleted by UnregisterModule calls above:
m_wxmodules.clear(); m_wxmodules.clear();
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// wxPluginManager // wxPluginManager
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
wxDLManifest* wxPluginManager::ms_manifest = NULL; wxDLManifest* wxPluginManager::ms_manifest = NULL;
// ------------------------ // ------------------------
// Static accessors // Static accessors
// ------------------------ // ------------------------
wxPluginLibrary * wxPluginLibrary *
wxPluginManager::LoadLibrary(const wxString &libname, int flags) wxPluginManager::LoadLibrary(const wxString &libname, int flags)
{ {
wxString realname(libname); wxString realname(libname);
if( !(flags & wxDL_VERBATIM) ) if( !(flags & wxDL_VERBATIM) )
realname += wxDynamicLibrary::GetDllExt(); realname += wxDynamicLibrary::GetDllExt();
wxPluginLibrary *entry; wxPluginLibrary *entry;
if ( flags & wxDL_NOSHARE ) if ( flags & wxDL_NOSHARE )
{ {
entry = NULL; entry = NULL;
} }
else else
{ {
entry = FindByName(realname); entry = FindByName(realname);
} }
if ( entry ) if ( entry )
{ {
wxLogTrace(_T("dll"), wxLogTrace(_T("dll"),
_T("LoadLibrary(%s): already loaded."), realname.c_str()); _T("LoadLibrary(%s): already loaded."), realname.c_str());
entry->RefLib(); entry->RefLib();
} }
else else
{ {
entry = new wxPluginLibrary( libname, flags ); entry = new wxPluginLibrary( libname, flags );
if ( entry->IsLoaded() ) if ( entry->IsLoaded() )
{ {
(*ms_manifest)[realname] = entry; (*ms_manifest)[realname] = entry;
wxLogTrace(_T("dll"), wxLogTrace(_T("dll"),
_T("LoadLibrary(%s): loaded ok."), realname.c_str()); _T("LoadLibrary(%s): loaded ok."), realname.c_str());
} }
else else
{ {
wxLogTrace(_T("dll"), wxLogTrace(_T("dll"),
_T("LoadLibrary(%s): failed to load."), realname.c_str()); _T("LoadLibrary(%s): failed to load."), realname.c_str());
// we have created entry just above // we have created entry just above
if ( !entry->UnrefLib() ) if ( !entry->UnrefLib() )
{ {
// ... so UnrefLib() is supposed to delete it // ... so UnrefLib() is supposed to delete it
wxFAIL_MSG( _T("Currently linked library is not loaded?") ); wxFAIL_MSG( _T("Currently linked library is not loaded?") );
} }
entry = NULL; entry = NULL;
} }
} }
return entry; return entry;
} }
bool wxPluginManager::UnloadLibrary(const wxString& libname) bool wxPluginManager::UnloadLibrary(const wxString& libname)
{ {
wxString realname = libname; wxString realname = libname;
wxPluginLibrary *entry = FindByName(realname); wxPluginLibrary *entry = FindByName(realname);
if ( !entry ) if ( !entry )
{ {
realname += wxDynamicLibrary::GetDllExt(); realname += wxDynamicLibrary::GetDllExt();
entry = FindByName(realname); entry = FindByName(realname);
} }
if ( !entry ) if ( !entry )
{ {
wxLogDebug(_T("Attempt to unload library '%s' which is not loaded."), wxLogDebug(_T("Attempt to unload library '%s' which is not loaded."),
libname.c_str()); libname.c_str());
return false; return false;
} }
wxLogTrace(_T("dll"), _T("UnloadLibrary(%s)"), realname.c_str()); wxLogTrace(_T("dll"), _T("UnloadLibrary(%s)"), realname.c_str());
if ( !entry->UnrefLib() ) if ( !entry->UnrefLib() )
{ {
// not really unloaded yet // not really unloaded yet
return false; return false;
} }
ms_manifest->erase(ms_manifest->find(realname)); ms_manifest->erase(ms_manifest->find(realname));
return true; return true;
} }
// ------------------------ // ------------------------
// Class implementation // Class implementation
// ------------------------ // ------------------------
bool wxPluginManager::Load(const wxString &libname, int flags) bool wxPluginManager::Load(const wxString &libname, int flags)
{ {
m_entry = wxPluginManager::LoadLibrary(libname, flags); m_entry = wxPluginManager::LoadLibrary(libname, flags);
return IsLoaded(); return IsLoaded();
} }
void wxPluginManager::Unload() void wxPluginManager::Unload()
{ {
wxCHECK_RET( m_entry, _T("unloading an invalid wxPluginManager?") ); wxCHECK_RET( m_entry, _T("unloading an invalid wxPluginManager?") );
for ( wxDLManifest::iterator i = ms_manifest->begin(); for ( wxDLManifest::iterator i = ms_manifest->begin();
i != ms_manifest->end(); i != ms_manifest->end();
++i ) ++i )
{ {
if ( i->second == m_entry ) if ( i->second == m_entry )
{ {
ms_manifest->erase(i); ms_manifest->erase(i);
break; break;
} }
} }
m_entry->UnrefLib(); m_entry->UnrefLib();
m_entry = NULL; m_entry = NULL;
} }
#endif // wxUSE_DYNAMIC_LOADER #endif // wxUSE_DYNAMIC_LOADER

View File

@ -1,124 +1,124 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/effects.cpp // Name: src/common/effects.cpp
// Purpose: wxEffects implementation // Purpose: wxEffects implementation
// Author: Julian Smart // Author: Julian Smart
// Modified by: // Modified by:
// Created: 25/4/2000 // Created: 25/4/2000
// RCS-ID: $Id: effects.cpp 42755 2006-10-30 19:41:46Z VZ $ // RCS-ID: $Id: effects.cpp 42755 2006-10-30 19:41:46Z VZ $
// Copyright: (c) Julian Smart // Copyright: (c) Julian Smart
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/effects.h" #include "wx/effects.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/dcmemory.h" #include "wx/dcmemory.h"
#include "wx/pen.h" #include "wx/pen.h"
#include "wx/settings.h" #include "wx/settings.h"
#include "wx/gdicmn.h" #include "wx/gdicmn.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
/* /*
* wxEffects: various 3D effects * wxEffects: various 3D effects
*/ */
IMPLEMENT_CLASS(wxEffects, wxObject) IMPLEMENT_CLASS(wxEffects, wxObject)
// Assume system colours // Assume system colours
wxEffects::wxEffects() wxEffects::wxEffects()
{ {
m_highlightColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DHILIGHT) ; m_highlightColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DHILIGHT) ;
m_lightShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT) ; m_lightShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DLIGHT) ;
m_faceColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE) ; m_faceColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE) ;
m_mediumShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW) ; m_mediumShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW) ;
m_darkShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DDKSHADOW) ; m_darkShadow = wxSystemSettings::GetColour(wxSYS_COLOUR_3DDKSHADOW) ;
} }
// Going from lightest to darkest // Going from lightest to darkest
wxEffects::wxEffects(const wxColour& highlightColour, const wxColour& lightShadow, wxEffects::wxEffects(const wxColour& highlightColour, const wxColour& lightShadow,
const wxColour& faceColour, const wxColour& mediumShadow, const wxColour& darkShadow) const wxColour& faceColour, const wxColour& mediumShadow, const wxColour& darkShadow)
{ {
m_highlightColour = highlightColour; m_highlightColour = highlightColour;
m_lightShadow = lightShadow; m_lightShadow = lightShadow;
m_faceColour = faceColour; m_faceColour = faceColour;
m_mediumShadow = mediumShadow; m_mediumShadow = mediumShadow;
m_darkShadow = darkShadow; m_darkShadow = darkShadow;
} }
// Draw a sunken edge // Draw a sunken edge
void wxEffects::DrawSunkenEdge(wxDC& dc, const wxRect& rect, int WXUNUSED(borderSize)) void wxEffects::DrawSunkenEdge(wxDC& dc, const wxRect& rect, int WXUNUSED(borderSize))
{ {
wxPen highlightPen(m_highlightColour, 1, wxSOLID); wxPen highlightPen(m_highlightColour, 1, wxSOLID);
wxPen lightShadowPen(m_lightShadow, 1, wxSOLID); wxPen lightShadowPen(m_lightShadow, 1, wxSOLID);
wxPen facePen(m_faceColour, 1, wxSOLID); wxPen facePen(m_faceColour, 1, wxSOLID);
wxPen mediumShadowPen(m_mediumShadow, 1, wxSOLID); wxPen mediumShadowPen(m_mediumShadow, 1, wxSOLID);
wxPen darkShadowPen(m_darkShadow, 1, wxSOLID); wxPen darkShadowPen(m_darkShadow, 1, wxSOLID);
//// LEFT AND TOP //// LEFT AND TOP
// Draw a medium shadow pen on left and top, followed by dark shadow line to // Draw a medium shadow pen on left and top, followed by dark shadow line to
// right and below of these lines // right and below of these lines
dc.SetPen(mediumShadowPen); dc.SetPen(mediumShadowPen);
dc.DrawLine(rect.x, rect.y, rect.x+rect.width-1, rect.y); // Top dc.DrawLine(rect.x, rect.y, rect.x+rect.width-1, rect.y); // Top
dc.DrawLine(rect.x, rect.y, rect.x, rect.y+rect.height-1); // Left dc.DrawLine(rect.x, rect.y, rect.x, rect.y+rect.height-1); // Left
dc.SetPen(darkShadowPen); dc.SetPen(darkShadowPen);
dc.DrawLine(rect.x+1, rect.y+1, rect.x+rect.width-2, rect.y+1); // Top dc.DrawLine(rect.x+1, rect.y+1, rect.x+rect.width-2, rect.y+1); // Top
dc.DrawLine(rect.x+1, rect.y+1, rect.x+1, rect.y+rect.height-1); // Left dc.DrawLine(rect.x+1, rect.y+1, rect.x+1, rect.y+rect.height-1); // Left
//// RIGHT AND BOTTOM //// RIGHT AND BOTTOM
dc.SetPen(highlightPen); dc.SetPen(highlightPen);
dc.DrawLine(rect.x+rect.width-1, rect.y, rect.x+rect.width-1, rect.y+rect.height-1); // Right dc.DrawLine(rect.x+rect.width-1, rect.y, rect.x+rect.width-1, rect.y+rect.height-1); // Right
dc.DrawLine(rect.x, rect.y+rect.height-1, rect.x+rect.width, rect.y+rect.height-1); // Bottom dc.DrawLine(rect.x, rect.y+rect.height-1, rect.x+rect.width, rect.y+rect.height-1); // Bottom
dc.SetPen(lightShadowPen); dc.SetPen(lightShadowPen);
dc.DrawLine(rect.x+rect.width-2, rect.y+1, rect.x+rect.width-2, rect.y+rect.height-2); // Right dc.DrawLine(rect.x+rect.width-2, rect.y+1, rect.x+rect.width-2, rect.y+rect.height-2); // Right
dc.DrawLine(rect.x+1, rect.y+rect.height-2, rect.x+rect.width-1, rect.y+rect.height-2); // Bottom dc.DrawLine(rect.x+1, rect.y+rect.height-2, rect.x+rect.width-1, rect.y+rect.height-2); // Bottom
dc.SetPen(wxNullPen); dc.SetPen(wxNullPen);
} }
bool wxEffects::TileBitmap(const wxRect& rect, wxDC& dc, const wxBitmap& bitmap) bool wxEffects::TileBitmap(const wxRect& rect, wxDC& dc, const wxBitmap& bitmap)
{ {
int w = bitmap.GetWidth(); int w = bitmap.GetWidth();
int h = bitmap.GetHeight(); int h = bitmap.GetHeight();
wxMemoryDC dcMem; wxMemoryDC dcMem;
#if wxUSE_PALETTE #if wxUSE_PALETTE
static bool hiColour = (wxDisplayDepth() >= 16) ; static bool hiColour = (wxDisplayDepth() >= 16) ;
if (bitmap.GetPalette() && !hiColour) if (bitmap.GetPalette() && !hiColour)
{ {
dc.SetPalette(* bitmap.GetPalette()); dc.SetPalette(* bitmap.GetPalette());
dcMem.SetPalette(* bitmap.GetPalette()); dcMem.SetPalette(* bitmap.GetPalette());
} }
#endif // wxUSE_PALETTE #endif // wxUSE_PALETTE
dcMem.SelectObjectAsSource(bitmap); dcMem.SelectObjectAsSource(bitmap);
int i, j; int i, j;
for (i = rect.x; i < rect.x + rect.width; i += w) for (i = rect.x; i < rect.x + rect.width; i += w)
{ {
for (j = rect.y; j < rect.y + rect.height; j+= h) for (j = rect.y; j < rect.y + rect.height; j+= h)
dc.Blit(i, j, bitmap.GetWidth(), bitmap.GetHeight(), & dcMem, 0, 0); dc.Blit(i, j, bitmap.GetWidth(), bitmap.GetHeight(), & dcMem, 0, 0);
} }
dcMem.SelectObject(wxNullBitmap); dcMem.SelectObject(wxNullBitmap);
#if wxUSE_PALETTE #if wxUSE_PALETTE
if (bitmap.GetPalette() && !hiColour) if (bitmap.GetPalette() && !hiColour)
{ {
dc.SetPalette(wxNullPalette); dc.SetPalette(wxNullPalette);
dcMem.SetPalette(wxNullPalette); dcMem.SetPalette(wxNullPalette);
} }
#endif // wxUSE_PALETTE #endif // wxUSE_PALETTE
return true; return true;
} }

View File

@ -1,3 +1,3 @@
// This file exists so that it can be compiled into an object so the linker // This file exists so that it can be compiled into an object so the linker
// will have something to chew on so that builds don't break when a platform // will have something to chew on so that builds don't break when a platform
// lacks any objects in a particular multilib. // lacks any objects in a particular multilib.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,172 +1,172 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/evtloopcmn.cpp // Name: src/common/evtloopcmn.cpp
// Purpose: common wxEventLoop-related stuff // Purpose: common wxEventLoop-related stuff
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 2006-01-12 // Created: 2006-01-12
// RCS-ID: $Id: evtloopcmn.cpp 45938 2007-05-10 02:07:41Z VZ $ // RCS-ID: $Id: evtloopcmn.cpp 45938 2007-05-10 02:07:41Z VZ $
// Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h". // for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/evtloop.h" #include "wx/evtloop.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/app.h" #include "wx/app.h"
#endif //WX_PRECOMP #endif //WX_PRECOMP
// see the comment near the declaration of wxRunningEventLoopCount in // see the comment near the declaration of wxRunningEventLoopCount in
// src/msw/thread.cpp for the explanation of this hack // src/msw/thread.cpp for the explanation of this hack
#if defined(__WXMSW__) && wxUSE_THREADS #if defined(__WXMSW__) && wxUSE_THREADS
extern WXDLLIMPEXP_DATA_BASE(int) wxRunningEventLoopCount; extern WXDLLIMPEXP_DATA_BASE(int) wxRunningEventLoopCount;
struct wxRunningEventLoopCounter struct wxRunningEventLoopCounter
{ {
wxRunningEventLoopCounter() { wxRunningEventLoopCount++; } wxRunningEventLoopCounter() { wxRunningEventLoopCount++; }
~wxRunningEventLoopCounter() { wxRunningEventLoopCount--; } ~wxRunningEventLoopCounter() { wxRunningEventLoopCount--; }
}; };
#endif // __WXMSW__ #endif // __WXMSW__
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// globals // globals
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxEventLoop *wxEventLoopBase::ms_activeLoop = NULL; wxEventLoop *wxEventLoopBase::ms_activeLoop = NULL;
// wxEventLoopManual is unused in the other ports // wxEventLoopManual is unused in the other ports
#if defined(__WXMSW__) || defined(__WXMAC__) || defined(__WXDFB__) #if defined(__WXMSW__) || defined(__WXMAC__) || defined(__WXDFB__)
// ============================================================================ // ============================================================================
// wxEventLoopManual implementation // wxEventLoopManual implementation
// ============================================================================ // ============================================================================
wxEventLoopManual::wxEventLoopManual() wxEventLoopManual::wxEventLoopManual()
{ {
m_exitcode = 0; m_exitcode = 0;
m_shouldExit = false; m_shouldExit = false;
} }
int wxEventLoopManual::Run() int wxEventLoopManual::Run()
{ {
// event loops are not recursive, you need to create another loop! // event loops are not recursive, you need to create another loop!
wxCHECK_MSG( !IsRunning(), -1, _T("can't reenter a message loop") ); wxCHECK_MSG( !IsRunning(), -1, _T("can't reenter a message loop") );
// ProcessIdle() and Dispatch() below may throw so the code here should // ProcessIdle() and Dispatch() below may throw so the code here should
// be exception-safe, hence we must use local objects for all actions we // be exception-safe, hence we must use local objects for all actions we
// should undo // should undo
wxEventLoopActivator activate(wx_static_cast(wxEventLoop *, this)); wxEventLoopActivator activate(wx_static_cast(wxEventLoop *, this));
#if defined(__WXMSW__) && wxUSE_THREADS #if defined(__WXMSW__) && wxUSE_THREADS
wxRunningEventLoopCounter evtLoopCounter; wxRunningEventLoopCounter evtLoopCounter;
#endif // __WXMSW__ #endif // __WXMSW__
// we must ensure that OnExit() is called even if an exception is thrown // we must ensure that OnExit() is called even if an exception is thrown
// from inside Dispatch() but we must call it from Exit() in normal // from inside Dispatch() but we must call it from Exit() in normal
// situations because it is supposed to be called synchronously, // situations because it is supposed to be called synchronously,
// wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
// something similar here) // something similar here)
#if wxUSE_EXCEPTIONS #if wxUSE_EXCEPTIONS
for ( ;; ) for ( ;; )
{ {
try try
{ {
#endif // wxUSE_EXCEPTIONS #endif // wxUSE_EXCEPTIONS
// this is the event loop itself // this is the event loop itself
for ( ;; ) for ( ;; )
{ {
// give them the possibility to do whatever they want // give them the possibility to do whatever they want
OnNextIteration(); OnNextIteration();
// generate and process idle events for as long as we don't // generate and process idle events for as long as we don't
// have anything else to do // have anything else to do
while ( !Pending() && (wxTheApp && wxTheApp->ProcessIdle()) ) while ( !Pending() && (wxTheApp && wxTheApp->ProcessIdle()) )
; ;
// if the "should exit" flag is set, the loop should terminate // if the "should exit" flag is set, the loop should terminate
// but not before processing any remaining messages so while // but not before processing any remaining messages so while
// Pending() returns true, do process them // Pending() returns true, do process them
if ( m_shouldExit ) if ( m_shouldExit )
{ {
while ( Pending() ) while ( Pending() )
Dispatch(); Dispatch();
break; break;
} }
// a message came or no more idle processing to do, sit in // a message came or no more idle processing to do, sit in
// Dispatch() waiting for the next message // Dispatch() waiting for the next message
if ( !Dispatch() ) if ( !Dispatch() )
{ {
// we got WM_QUIT // we got WM_QUIT
break; break;
} }
} }
#if wxUSE_EXCEPTIONS #if wxUSE_EXCEPTIONS
// exit the outer loop as well // exit the outer loop as well
break; break;
} }
catch ( ... ) catch ( ... )
{ {
try try
{ {
if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() ) if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
{ {
OnExit(); OnExit();
break; break;
} }
//else: continue running the event loop //else: continue running the event loop
} }
catch ( ... ) catch ( ... )
{ {
// OnException() throwed, possibly rethrowing the same // OnException() throwed, possibly rethrowing the same
// exception again: very good, but we still need OnExit() to // exception again: very good, but we still need OnExit() to
// be called // be called
OnExit(); OnExit();
throw; throw;
} }
} }
} }
#endif // wxUSE_EXCEPTIONS #endif // wxUSE_EXCEPTIONS
return m_exitcode; return m_exitcode;
} }
void wxEventLoopManual::Exit(int rc) void wxEventLoopManual::Exit(int rc)
{ {
wxCHECK_RET( IsRunning(), _T("can't call Exit() if not running") ); wxCHECK_RET( IsRunning(), _T("can't call Exit() if not running") );
m_exitcode = rc; m_exitcode = rc;
m_shouldExit = true; m_shouldExit = true;
OnExit(); OnExit();
// all we have to do to exit from the loop is to (maybe) wake it up so that // all we have to do to exit from the loop is to (maybe) wake it up so that
// it can notice that Exit() had been called // it can notice that Exit() had been called
// //
// in particular, do *not* use here calls such as PostQuitMessage() (under // in particular, do *not* use here calls such as PostQuitMessage() (under
// MSW) which terminate the current event loop here because we're not sure // MSW) which terminate the current event loop here because we're not sure
// that it is going to be processed by the correct event loop: it would be // that it is going to be processed by the correct event loop: it would be
// possible that another one is started and terminated by mistake if we do // possible that another one is started and terminated by mistake if we do
// this // this
WakeUp(); WakeUp();
} }
#endif // __WXMSW__ || __WXMAC__ || __WXDFB__ #endif // __WXMSW__ || __WXMAC__ || __WXDFB__

View File

@ -1,122 +1,122 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: common/wxexec.cpp // Name: common/wxexec.cpp
// Purpose: defines wxStreamTempInputBuffer which is used by Unix and MSW // Purpose: defines wxStreamTempInputBuffer which is used by Unix and MSW
// implementations of wxExecute; this file is only used by the // implementations of wxExecute; this file is only used by the
// library and never by the user code // library and never by the user code
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 20.08.02 // Created: 20.08.02
// RCS-ID: $Id: execcmn.cpp 35289 2005-08-23 23:12:48Z VZ $ // RCS-ID: $Id: execcmn.cpp 35289 2005-08-23 23:12:48Z VZ $
// Copyright: (c) 2002 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 2002 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_WXEXEC_CPP_ #ifndef _WX_WXEXEC_CPP_
#define _WX_WXEXEC_CPP_ #define _WX_WXEXEC_CPP_
// this file should never be compiled directly, just included by other code // this file should never be compiled directly, just included by other code
#ifndef _WX_USED_BY_WXEXECUTE_ #ifndef _WX_USED_BY_WXEXECUTE_
#error "You should never directly build this file!" #error "You should never directly build this file!"
#endif #endif
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxStreamTempInputBuffer // wxStreamTempInputBuffer
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
/* /*
wxStreamTempInputBuffer is a hack which we need to solve the problem of wxStreamTempInputBuffer is a hack which we need to solve the problem of
executing a child process synchronously with IO redirecting: when we do executing a child process synchronously with IO redirecting: when we do
this, the child writes to a pipe we open to it but when the pipe buffer this, the child writes to a pipe we open to it but when the pipe buffer
(which has finite capacity, e.g. commonly just 4Kb) becomes full we have to (which has finite capacity, e.g. commonly just 4Kb) becomes full we have to
read data from it because the child blocks in its write() until then and if read data from it because the child blocks in its write() until then and if
it blocks we are never going to return from wxExecute() so we dead lock. it blocks we are never going to return from wxExecute() so we dead lock.
So here is the fix: we now read the output as soon as it appears into a temp So here is the fix: we now read the output as soon as it appears into a temp
buffer (wxStreamTempInputBuffer object) and later just stuff it back into buffer (wxStreamTempInputBuffer object) and later just stuff it back into
the stream when the process terminates. See supporting code in wxExecute() the stream when the process terminates. See supporting code in wxExecute()
itself as well. itself as well.
Note that this is horribly inefficient for large amounts of output (count Note that this is horribly inefficient for large amounts of output (count
the number of times we copy the data around) and so a better API is badly the number of times we copy the data around) and so a better API is badly
needed! However it's not easy to devise a way to do this keeping backwards needed! However it's not easy to devise a way to do this keeping backwards
compatibility with the existing wxExecute(wxEXEC_SYNC)... compatibility with the existing wxExecute(wxEXEC_SYNC)...
*/ */
class wxStreamTempInputBuffer class wxStreamTempInputBuffer
{ {
public: public:
wxStreamTempInputBuffer(); wxStreamTempInputBuffer();
// call to associate a stream with this buffer, otherwise nothing happens // call to associate a stream with this buffer, otherwise nothing happens
// at all // at all
void Init(wxPipeInputStream *stream); void Init(wxPipeInputStream *stream);
// check for input on our stream and cache it in our buffer if any // check for input on our stream and cache it in our buffer if any
void Update(); void Update();
~wxStreamTempInputBuffer(); ~wxStreamTempInputBuffer();
private: private:
// the stream we're buffering, if NULL we don't do anything at all // the stream we're buffering, if NULL we don't do anything at all
wxPipeInputStream *m_stream; wxPipeInputStream *m_stream;
// the buffer of size m_size (NULL if m_size == 0) // the buffer of size m_size (NULL if m_size == 0)
void *m_buffer; void *m_buffer;
// the size of the buffer // the size of the buffer
size_t m_size; size_t m_size;
DECLARE_NO_COPY_CLASS(wxStreamTempInputBuffer) DECLARE_NO_COPY_CLASS(wxStreamTempInputBuffer)
}; };
inline wxStreamTempInputBuffer::wxStreamTempInputBuffer() inline wxStreamTempInputBuffer::wxStreamTempInputBuffer()
{ {
m_stream = NULL; m_stream = NULL;
m_buffer = NULL; m_buffer = NULL;
m_size = 0; m_size = 0;
} }
inline void wxStreamTempInputBuffer::Init(wxPipeInputStream *stream) inline void wxStreamTempInputBuffer::Init(wxPipeInputStream *stream)
{ {
m_stream = stream; m_stream = stream;
} }
inline inline
void wxStreamTempInputBuffer::Update() void wxStreamTempInputBuffer::Update()
{ {
if ( m_stream && m_stream->CanRead() ) if ( m_stream && m_stream->CanRead() )
{ {
// realloc in blocks of 4Kb: this is the default (and minimal) buffer // realloc in blocks of 4Kb: this is the default (and minimal) buffer
// size of the Unix pipes so it should be the optimal step // size of the Unix pipes so it should be the optimal step
// //
// NB: don't use "static int" in this inline function, some compilers // NB: don't use "static int" in this inline function, some compilers
// (e.g. IBM xlC) don't like it // (e.g. IBM xlC) don't like it
enum { incSize = 4096 }; enum { incSize = 4096 };
void *buf = realloc(m_buffer, m_size + incSize); void *buf = realloc(m_buffer, m_size + incSize);
if ( !buf ) if ( !buf )
{ {
// don't read any more, we don't have enough memory to do it // don't read any more, we don't have enough memory to do it
m_stream = NULL; m_stream = NULL;
} }
else // got memory for the buffer else // got memory for the buffer
{ {
m_buffer = buf; m_buffer = buf;
m_stream->Read((char *)m_buffer + m_size, incSize); m_stream->Read((char *)m_buffer + m_size, incSize);
m_size += m_stream->LastRead(); m_size += m_stream->LastRead();
} }
} }
} }
inline inline
wxStreamTempInputBuffer::~wxStreamTempInputBuffer() wxStreamTempInputBuffer::~wxStreamTempInputBuffer()
{ {
if ( m_buffer ) if ( m_buffer )
{ {
m_stream->Ungetch(m_buffer, m_size); m_stream->Ungetch(m_buffer, m_size);
free(m_buffer); free(m_buffer);
} }
} }
#endif // _WX_WXEXEC_CPP_ #endif // _WX_WXEXEC_CPP_

View File

@ -1,102 +1,102 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fdrepdlg.cpp // Name: src/common/fdrepdlg.cpp
// Purpose: common parts of wxFindReplaceDialog implementations // Purpose: common parts of wxFindReplaceDialog implementations
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 01.08.01 // Created: 01.08.01
// RCS-ID: // RCS-ID:
// Copyright: (c) 2001 Vadim Zeitlin // Copyright: (c) 2001 Vadim Zeitlin
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FINDREPLDLG #if wxUSE_FINDREPLDLG
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif #endif
#include "wx/fdrepdlg.h" #include "wx/fdrepdlg.h"
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxWin macros // wxWin macros
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxFindDialogEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxFindDialogEvent, wxCommandEvent)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_NEXT) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_NEXT)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_REPLACE) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_REPLACE)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_REPLACE_ALL) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_REPLACE_ALL)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_CLOSE) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FIND_CLOSE)
// ============================================================================ // ============================================================================
// implementations // implementations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFindReplaceData // wxFindReplaceData
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxFindReplaceData::Init() void wxFindReplaceData::Init()
{ {
m_Flags = 0; m_Flags = 0;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFindReplaceDialogBase // wxFindReplaceDialogBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFindReplaceDialogBase::~wxFindReplaceDialogBase() wxFindReplaceDialogBase::~wxFindReplaceDialogBase()
{ {
} }
void wxFindReplaceDialogBase::Send(wxFindDialogEvent& event) void wxFindReplaceDialogBase::Send(wxFindDialogEvent& event)
{ {
// we copy the data to dialog->GetData() as well // we copy the data to dialog->GetData() as well
m_FindReplaceData->m_Flags = event.GetFlags(); m_FindReplaceData->m_Flags = event.GetFlags();
m_FindReplaceData->m_FindWhat = event.GetFindString(); m_FindReplaceData->m_FindWhat = event.GetFindString();
if ( HasFlag(wxFR_REPLACEDIALOG) && if ( HasFlag(wxFR_REPLACEDIALOG) &&
(event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE || (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE ||
event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL) ) event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL) )
{ {
m_FindReplaceData->m_ReplaceWith = event.GetReplaceString(); m_FindReplaceData->m_ReplaceWith = event.GetReplaceString();
} }
// translate wxEVT_COMMAND_FIND_NEXT to wxEVT_COMMAND_FIND if needed // translate wxEVT_COMMAND_FIND_NEXT to wxEVT_COMMAND_FIND if needed
if ( event.GetEventType() == wxEVT_COMMAND_FIND_NEXT ) if ( event.GetEventType() == wxEVT_COMMAND_FIND_NEXT )
{ {
if ( m_FindReplaceData->m_FindWhat != m_lastSearch ) if ( m_FindReplaceData->m_FindWhat != m_lastSearch )
{ {
event.SetEventType(wxEVT_COMMAND_FIND); event.SetEventType(wxEVT_COMMAND_FIND);
m_lastSearch = m_FindReplaceData->m_FindWhat; m_lastSearch = m_FindReplaceData->m_FindWhat;
} }
} }
if ( !GetEventHandler()->ProcessEvent(event) ) if ( !GetEventHandler()->ProcessEvent(event) )
{ {
// the event is not propagated upwards to the parent automatically // the event is not propagated upwards to the parent automatically
// because the dialog is a top level window, so do it manually as // because the dialog is a top level window, so do it manually as
// in 9 cases of 10 the message must be processed by the dialog // in 9 cases of 10 the message must be processed by the dialog
// owner and not the dialog itself // owner and not the dialog itself
(void)GetParent()->GetEventHandler()->ProcessEvent(event); (void)GetParent()->GetEventHandler()->ProcessEvent(event);
} }
} }
#endif // wxUSE_FINDREPLDLG #endif // wxUSE_FINDREPLDLG

View File

@ -1,268 +1,268 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: ffile.cpp // Name: ffile.cpp
// Purpose: wxFFile encapsulates "FILE *" IO stream // Purpose: wxFFile encapsulates "FILE *" IO stream
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 14.07.99 // Created: 14.07.99
// RCS-ID: $Id: ffile.cpp 38570 2006-04-05 14:37:47Z VZ $ // RCS-ID: $Id: ffile.cpp 38570 2006-04-05 14:37:47Z VZ $
// Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FFILE #if wxUSE_FFILE
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/log.h" #include "wx/log.h"
#endif #endif
#ifdef __WINDOWS__ #ifdef __WINDOWS__
#include "wx/msw/mslu.h" #include "wx/msw/mslu.h"
#endif #endif
#include "wx/ffile.h" #include "wx/ffile.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// seek and tell with large file support if available // seek and tell with large file support if available
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#ifdef HAVE_FSEEKO #ifdef HAVE_FSEEKO
# define wxFseek fseeko # define wxFseek fseeko
# define wxFtell ftello # define wxFtell ftello
#else #else
# define wxFseek fseek # define wxFseek fseek
# define wxFtell ftell # define wxFtell ftell
#endif #endif
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// opening the file // opening the file
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFFile::wxFFile(const wxChar *filename, const wxChar *mode) wxFFile::wxFFile(const wxChar *filename, const wxChar *mode)
{ {
Detach(); Detach();
(void)Open(filename, mode); (void)Open(filename, mode);
} }
bool wxFFile::Open(const wxChar *filename, const wxChar *mode) bool wxFFile::Open(const wxChar *filename, const wxChar *mode)
{ {
wxASSERT_MSG( !m_fp, wxT("should close or detach the old file first") ); wxASSERT_MSG( !m_fp, wxT("should close or detach the old file first") );
m_fp = wxFopen(filename, mode); m_fp = wxFopen(filename, mode);
if ( !m_fp ) if ( !m_fp )
{ {
wxLogSysError(_("can't open file '%s'"), filename); wxLogSysError(_("can't open file '%s'"), filename);
return false; return false;
} }
m_name = filename; m_name = filename;
return true; return true;
} }
bool wxFFile::Close() bool wxFFile::Close()
{ {
if ( IsOpened() ) if ( IsOpened() )
{ {
if ( fclose(m_fp) != 0 ) if ( fclose(m_fp) != 0 )
{ {
wxLogSysError(_("can't close file '%s'"), m_name.c_str()); wxLogSysError(_("can't close file '%s'"), m_name.c_str());
return false; return false;
} }
Detach(); Detach();
} }
return true; return true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// read/write // read/write
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxFFile::ReadAll(wxString *str, const wxMBConv& conv) bool wxFFile::ReadAll(wxString *str, const wxMBConv& conv)
{ {
wxCHECK_MSG( str, false, wxT("invalid parameter") ); wxCHECK_MSG( str, false, wxT("invalid parameter") );
wxCHECK_MSG( IsOpened(), false, wxT("can't read from closed file") ); wxCHECK_MSG( IsOpened(), false, wxT("can't read from closed file") );
wxCHECK_MSG( Length() >= 0, false, wxT("invalid length") ); wxCHECK_MSG( Length() >= 0, false, wxT("invalid length") );
size_t length = wx_truncate_cast(size_t, Length()); size_t length = wx_truncate_cast(size_t, Length());
wxCHECK_MSG( (wxFileOffset)length == Length(), false, wxT("huge file not supported") ); wxCHECK_MSG( (wxFileOffset)length == Length(), false, wxT("huge file not supported") );
clearerr(m_fp); clearerr(m_fp);
wxCharBuffer buf(length + 1); wxCharBuffer buf(length + 1);
// note that real length may be less than file length for text files with DOS EOLs // note that real length may be less than file length for text files with DOS EOLs
// ('\r's get dropped by CRT when reading which means that we have // ('\r's get dropped by CRT when reading which means that we have
// realLen = fileLen - numOfLinesInTheFile) // realLen = fileLen - numOfLinesInTheFile)
length = fread(buf.data(), sizeof(char), length, m_fp); length = fread(buf.data(), sizeof(char), length, m_fp);
if ( Error() ) if ( Error() )
{ {
wxLogSysError(_("Read error on file '%s'"), m_name.c_str()); wxLogSysError(_("Read error on file '%s'"), m_name.c_str());
return false; return false;
} }
buf.data()[length] = 0; buf.data()[length] = 0;
*str = wxString(buf, conv); *str = wxString(buf, conv);
return true; return true;
} }
size_t wxFFile::Read(void *pBuf, size_t nCount) size_t wxFFile::Read(void *pBuf, size_t nCount)
{ {
wxCHECK_MSG( pBuf, 0, wxT("invalid parameter") ); wxCHECK_MSG( pBuf, 0, wxT("invalid parameter") );
wxCHECK_MSG( IsOpened(), 0, wxT("can't read from closed file") ); wxCHECK_MSG( IsOpened(), 0, wxT("can't read from closed file") );
size_t nRead = fread(pBuf, 1, nCount, m_fp); size_t nRead = fread(pBuf, 1, nCount, m_fp);
if ( (nRead < nCount) && Error() ) if ( (nRead < nCount) && Error() )
{ {
wxLogSysError(_("Read error on file '%s'"), m_name.c_str()); wxLogSysError(_("Read error on file '%s'"), m_name.c_str());
} }
return nRead; return nRead;
} }
size_t wxFFile::Write(const void *pBuf, size_t nCount) size_t wxFFile::Write(const void *pBuf, size_t nCount)
{ {
wxCHECK_MSG( pBuf, 0, wxT("invalid parameter") ); wxCHECK_MSG( pBuf, 0, wxT("invalid parameter") );
wxCHECK_MSG( IsOpened(), 0, wxT("can't write to closed file") ); wxCHECK_MSG( IsOpened(), 0, wxT("can't write to closed file") );
size_t nWritten = fwrite(pBuf, 1, nCount, m_fp); size_t nWritten = fwrite(pBuf, 1, nCount, m_fp);
if ( nWritten < nCount ) if ( nWritten < nCount )
{ {
wxLogSysError(_("Write error on file '%s'"), m_name.c_str()); wxLogSysError(_("Write error on file '%s'"), m_name.c_str());
} }
return nWritten; return nWritten;
} }
bool wxFFile::Flush() bool wxFFile::Flush()
{ {
if ( IsOpened() ) if ( IsOpened() )
{ {
// fflush returns non-zero on error // fflush returns non-zero on error
// //
if ( fflush(m_fp) ) if ( fflush(m_fp) )
{ {
wxLogSysError(_("failed to flush the file '%s'"), m_name.c_str()); wxLogSysError(_("failed to flush the file '%s'"), m_name.c_str());
return false; return false;
} }
} }
return true; return true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// seeking // seeking
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxFFile::Seek(wxFileOffset ofs, wxSeekMode mode) bool wxFFile::Seek(wxFileOffset ofs, wxSeekMode mode)
{ {
wxCHECK_MSG( IsOpened(), false, wxT("can't seek on closed file") ); wxCHECK_MSG( IsOpened(), false, wxT("can't seek on closed file") );
int origin; int origin;
switch ( mode ) switch ( mode )
{ {
default: default:
wxFAIL_MSG(wxT("unknown seek mode")); wxFAIL_MSG(wxT("unknown seek mode"));
// still fall through // still fall through
case wxFromStart: case wxFromStart:
origin = SEEK_SET; origin = SEEK_SET;
break; break;
case wxFromCurrent: case wxFromCurrent:
origin = SEEK_CUR; origin = SEEK_CUR;
break; break;
case wxFromEnd: case wxFromEnd:
origin = SEEK_END; origin = SEEK_END;
break; break;
} }
#ifndef HAVE_FSEEKO #ifndef HAVE_FSEEKO
if ((long)ofs != ofs) if ((long)ofs != ofs)
{ {
wxLogError(_("Seek error on file '%s' (large files not supported by stdio)"), m_name.c_str()); wxLogError(_("Seek error on file '%s' (large files not supported by stdio)"), m_name.c_str());
return false; return false;
} }
if ( wxFseek(m_fp, (long)ofs, origin) != 0 ) if ( wxFseek(m_fp, (long)ofs, origin) != 0 )
#else #else
if ( wxFseek(m_fp, ofs, origin) != 0 ) if ( wxFseek(m_fp, ofs, origin) != 0 )
#endif #endif
{ {
wxLogSysError(_("Seek error on file '%s'"), m_name.c_str()); wxLogSysError(_("Seek error on file '%s'"), m_name.c_str());
return false; return false;
} }
return true; return true;
} }
wxFileOffset wxFFile::Tell() const wxFileOffset wxFFile::Tell() const
{ {
wxCHECK_MSG( IsOpened(), wxInvalidOffset, wxCHECK_MSG( IsOpened(), wxInvalidOffset,
_T("wxFFile::Tell(): file is closed!") ); _T("wxFFile::Tell(): file is closed!") );
wxFileOffset rc = wxFtell(m_fp); wxFileOffset rc = wxFtell(m_fp);
if ( rc == wxInvalidOffset ) if ( rc == wxInvalidOffset )
{ {
wxLogSysError(_("Can't find current position in file '%s'"), wxLogSysError(_("Can't find current position in file '%s'"),
m_name.c_str()); m_name.c_str());
} }
return rc; return rc;
} }
wxFileOffset wxFFile::Length() const wxFileOffset wxFFile::Length() const
{ {
wxCHECK_MSG( IsOpened(), wxInvalidOffset, wxCHECK_MSG( IsOpened(), wxInvalidOffset,
_T("wxFFile::Length(): file is closed!") ); _T("wxFFile::Length(): file is closed!") );
wxFFile& self = *(wxFFile *)this; // const_cast wxFFile& self = *(wxFFile *)this; // const_cast
wxFileOffset posOld = Tell(); wxFileOffset posOld = Tell();
if ( posOld != wxInvalidOffset ) if ( posOld != wxInvalidOffset )
{ {
if ( self.SeekEnd() ) if ( self.SeekEnd() )
{ {
wxFileOffset len = Tell(); wxFileOffset len = Tell();
(void)self.Seek(posOld); (void)self.Seek(posOld);
return len; return len;
} }
} }
return wxInvalidOffset; return wxInvalidOffset;
} }
#endif // wxUSE_FFILE #endif // wxUSE_FFILE

File diff suppressed because it is too large Load Diff

View File

@ -1,338 +1,338 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fileback.cpp // Name: src/common/fileback.cpp
// Purpose: Back an input stream with memory or a file // Purpose: Back an input stream with memory or a file
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: fileback.cpp 42651 2006-10-29 20:06:45Z MW $ // RCS-ID: $Id: fileback.cpp 42651 2006-10-29 20:06:45Z MW $
// Copyright: (c) 2006 Mike Wetherell // Copyright: (c) 2006 Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FILESYSTEM #if wxUSE_FILESYSTEM
#include "wx/private/fileback.h" #include "wx/private/fileback.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/utils.h" #include "wx/utils.h"
#include "wx/log.h" #include "wx/log.h"
#endif #endif
#include "wx/private/filename.h" #include "wx/private/filename.h"
// Prefer wxFFile unless wxFile has large file support but wxFFile does not. // Prefer wxFFile unless wxFile has large file support but wxFFile does not.
// //
#if wxUSE_FFILE && (defined wxHAS_LARGE_FFILES || !defined wxHAS_LARGE_FILES) #if wxUSE_FFILE && (defined wxHAS_LARGE_FFILES || !defined wxHAS_LARGE_FILES)
typedef wxFFile wxBFFile; typedef wxFFile wxBFFile;
static const bool wxBadSeek = false; static const bool wxBadSeek = false;
#else #else
typedef wxFile wxBFFile; typedef wxFile wxBFFile;
static const wxFileOffset wxBadSeek = wxInvalidOffset; static const wxFileOffset wxBadSeek = wxInvalidOffset;
#endif #endif
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Backing file implementation // Backing file implementation
class wxBackingFileImpl class wxBackingFileImpl
{ {
public: public:
wxBackingFileImpl(wxInputStream *stream, wxBackingFileImpl(wxInputStream *stream,
size_t bufsize, size_t bufsize,
const wxString& prefix); const wxString& prefix);
~wxBackingFileImpl(); ~wxBackingFileImpl();
void Release() { if (--m_refcount == 0) delete this; } void Release() { if (--m_refcount == 0) delete this; }
wxBackingFileImpl *AddRef() { m_refcount++; return this; } wxBackingFileImpl *AddRef() { m_refcount++; return this; }
wxStreamError ReadAt(wxFileOffset pos, void *buffer, size_t *size); wxStreamError ReadAt(wxFileOffset pos, void *buffer, size_t *size);
wxFileOffset GetLength() const; wxFileOffset GetLength() const;
private: private:
int m_refcount; int m_refcount;
wxInputStream *m_stream; wxInputStream *m_stream;
wxStreamError m_parenterror; wxStreamError m_parenterror;
char *m_buf; char *m_buf;
size_t m_bufsize; size_t m_bufsize;
size_t m_buflen; size_t m_buflen;
wxString m_prefix; wxString m_prefix;
wxString m_filename; wxString m_filename;
wxBFFile m_file; wxBFFile m_file;
wxFileOffset m_filelen; wxFileOffset m_filelen;
}; };
wxBackingFileImpl::wxBackingFileImpl(wxInputStream *stream, wxBackingFileImpl::wxBackingFileImpl(wxInputStream *stream,
size_t bufsize, size_t bufsize,
const wxString& prefix) const wxString& prefix)
: m_refcount(1), : m_refcount(1),
m_stream(stream), m_stream(stream),
m_parenterror(wxSTREAM_NO_ERROR), m_parenterror(wxSTREAM_NO_ERROR),
m_buf(NULL), m_buf(NULL),
m_bufsize(bufsize), m_bufsize(bufsize),
m_buflen(0), m_buflen(0),
m_prefix(prefix), m_prefix(prefix),
m_filelen(0) m_filelen(0)
{ {
wxFileOffset len = m_stream->GetLength(); wxFileOffset len = m_stream->GetLength();
if (len >= 0 && len + size_t(1) < m_bufsize) if (len >= 0 && len + size_t(1) < m_bufsize)
m_bufsize = size_t(len + 1); m_bufsize = size_t(len + 1);
if (m_bufsize) if (m_bufsize)
m_buf = new char[m_bufsize]; m_buf = new char[m_bufsize];
} }
wxBackingFileImpl::~wxBackingFileImpl() wxBackingFileImpl::~wxBackingFileImpl()
{ {
delete m_stream; delete m_stream;
delete [] m_buf; delete [] m_buf;
if (!m_filename.empty()) if (!m_filename.empty())
wxRemoveFile(m_filename); wxRemoveFile(m_filename);
} }
wxStreamError wxBackingFileImpl::ReadAt(wxFileOffset pos, wxStreamError wxBackingFileImpl::ReadAt(wxFileOffset pos,
void *buffer, void *buffer,
size_t *size) size_t *size)
{ {
size_t reqestedSize = *size; size_t reqestedSize = *size;
*size = 0; *size = 0;
// size1 is the number of bytes it will read directly from the backing // size1 is the number of bytes it will read directly from the backing
// file. size2 is any remaining bytes not yet backed, these are returned // file. size2 is any remaining bytes not yet backed, these are returned
// from the buffer or read from the parent stream. // from the buffer or read from the parent stream.
size_t size1, size2; size_t size1, size2;
if (pos + reqestedSize <= m_filelen + size_t(0)) { if (pos + reqestedSize <= m_filelen + size_t(0)) {
size1 = reqestedSize; size1 = reqestedSize;
size2 = 0; size2 = 0;
} else if (pos < m_filelen) { } else if (pos < m_filelen) {
size1 = size_t(m_filelen - pos); size1 = size_t(m_filelen - pos);
size2 = reqestedSize - size1; size2 = reqestedSize - size1;
} else { } else {
size1 = 0; size1 = 0;
size2 = reqestedSize; size2 = reqestedSize;
} }
if (pos < 0) if (pos < 0)
return wxSTREAM_READ_ERROR; return wxSTREAM_READ_ERROR;
// read the backing file // read the backing file
if (size1) { if (size1) {
if (m_file.Seek(pos) == wxBadSeek) if (m_file.Seek(pos) == wxBadSeek)
return wxSTREAM_READ_ERROR; return wxSTREAM_READ_ERROR;
ssize_t n = m_file.Read(buffer, size1); ssize_t n = m_file.Read(buffer, size1);
if (n > 0) { if (n > 0) {
*size = n; *size = n;
pos += n; pos += n;
} }
if (*size < size1) if (*size < size1)
return wxSTREAM_READ_ERROR; return wxSTREAM_READ_ERROR;
} }
// read from the buffer or parent stream // read from the buffer or parent stream
if (size2) if (size2)
{ {
while (*size < reqestedSize) while (*size < reqestedSize)
{ {
// if pos is further ahead than the parent has been read so far, // if pos is further ahead than the parent has been read so far,
// then read forward in the parent stream // then read forward in the parent stream
while (pos - m_filelen + size_t(0) >= m_buflen) while (pos - m_filelen + size_t(0) >= m_buflen)
{ {
// if the parent is small enough, don't use a backing file // if the parent is small enough, don't use a backing file
// just the buffer memory // just the buffer memory
if (!m_stream && m_filelen == 0) if (!m_stream && m_filelen == 0)
return m_parenterror; return m_parenterror;
// before refilling the buffer write out the current buffer // before refilling the buffer write out the current buffer
// to the backing file if there is anything in it // to the backing file if there is anything in it
if (m_buflen) if (m_buflen)
{ {
if (!m_file.IsOpened()) if (!m_file.IsOpened())
if (!wxCreateTempFile(m_prefix, &m_file, &m_filename)) if (!wxCreateTempFile(m_prefix, &m_file, &m_filename))
return wxSTREAM_READ_ERROR; return wxSTREAM_READ_ERROR;
if (m_file.Seek(m_filelen) == wxBadSeek) if (m_file.Seek(m_filelen) == wxBadSeek)
return wxSTREAM_READ_ERROR; return wxSTREAM_READ_ERROR;
size_t count = m_file.Write(m_buf, m_buflen); size_t count = m_file.Write(m_buf, m_buflen);
m_filelen += count; m_filelen += count;
if (count < m_buflen) { if (count < m_buflen) {
delete m_stream; delete m_stream;
m_stream = NULL; m_stream = NULL;
if (count > 0) { if (count > 0) {
delete[] m_buf; delete[] m_buf;
m_buf = NULL; m_buf = NULL;
m_buflen = 0; m_buflen = 0;
} }
m_parenterror = wxSTREAM_READ_ERROR; m_parenterror = wxSTREAM_READ_ERROR;
return m_parenterror; return m_parenterror;
} }
m_buflen = 0; m_buflen = 0;
if (!m_stream) { if (!m_stream) {
delete[] m_buf; delete[] m_buf;
m_buf = NULL; m_buf = NULL;
} }
} }
if (!m_stream) if (!m_stream)
return m_parenterror; return m_parenterror;
// refill buffer // refill buffer
m_buflen = m_stream->Read(m_buf, m_bufsize).LastRead(); m_buflen = m_stream->Read(m_buf, m_bufsize).LastRead();
if (m_buflen < m_bufsize) { if (m_buflen < m_bufsize) {
m_parenterror = m_stream->GetLastError(); m_parenterror = m_stream->GetLastError();
if (m_parenterror == wxSTREAM_NO_ERROR) if (m_parenterror == wxSTREAM_NO_ERROR)
m_parenterror = wxSTREAM_EOF; m_parenterror = wxSTREAM_EOF;
delete m_stream; delete m_stream;
m_stream = NULL; m_stream = NULL;
} }
} }
// copy to the user's buffer // copy to the user's buffer
size_t start = size_t(pos - m_filelen); size_t start = size_t(pos - m_filelen);
size_t len = wxMin(m_buflen - start, reqestedSize - *size); size_t len = wxMin(m_buflen - start, reqestedSize - *size);
memcpy((char*)buffer + *size, m_buf + start, len); memcpy((char*)buffer + *size, m_buf + start, len);
*size += len; *size += len;
pos += len; pos += len;
} }
} }
return wxSTREAM_NO_ERROR; return wxSTREAM_NO_ERROR;
} }
wxFileOffset wxBackingFileImpl::GetLength() const wxFileOffset wxBackingFileImpl::GetLength() const
{ {
if (m_parenterror != wxSTREAM_EOF) { if (m_parenterror != wxSTREAM_EOF) {
wxLogNull nolog; wxLogNull nolog;
return m_stream->GetLength(); return m_stream->GetLength();
} }
return m_filelen + m_buflen; return m_filelen + m_buflen;
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Backing File, the handle part // Backing File, the handle part
wxBackingFile::wxBackingFile(wxInputStream *stream, wxBackingFile::wxBackingFile(wxInputStream *stream,
size_t bufsize, size_t bufsize,
const wxString& prefix) const wxString& prefix)
: m_impl(new wxBackingFileImpl(stream, bufsize, prefix)) : m_impl(new wxBackingFileImpl(stream, bufsize, prefix))
{ {
} }
wxBackingFile::wxBackingFile(const wxBackingFile& backer) wxBackingFile::wxBackingFile(const wxBackingFile& backer)
: m_impl(backer.m_impl ? backer.m_impl->AddRef() : NULL) : m_impl(backer.m_impl ? backer.m_impl->AddRef() : NULL)
{ {
} }
wxBackingFile& wxBackingFile::operator=(const wxBackingFile& backer) wxBackingFile& wxBackingFile::operator=(const wxBackingFile& backer)
{ {
if (backer.m_impl != m_impl) { if (backer.m_impl != m_impl) {
if (m_impl) if (m_impl)
m_impl->Release(); m_impl->Release();
m_impl = backer.m_impl; m_impl = backer.m_impl;
if (m_impl) if (m_impl)
m_impl->AddRef(); m_impl->AddRef();
} }
return *this; return *this;
} }
wxBackingFile::~wxBackingFile() wxBackingFile::~wxBackingFile()
{ {
if (m_impl) if (m_impl)
m_impl->Release(); m_impl->Release();
} }
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Input stream // Input stream
wxBackedInputStream::wxBackedInputStream(const wxBackingFile& backer) wxBackedInputStream::wxBackedInputStream(const wxBackingFile& backer)
: m_backer(backer), : m_backer(backer),
m_pos(0) m_pos(0)
{ {
} }
wxFileOffset wxBackedInputStream::GetLength() const wxFileOffset wxBackedInputStream::GetLength() const
{ {
return m_backer.m_impl->GetLength(); return m_backer.m_impl->GetLength();
} }
wxFileOffset wxBackedInputStream::FindLength() const wxFileOffset wxBackedInputStream::FindLength() const
{ {
wxFileOffset len = GetLength(); wxFileOffset len = GetLength();
if (len == wxInvalidOffset && IsOk()) { if (len == wxInvalidOffset && IsOk()) {
// read a byte at 7ff...ffe // read a byte at 7ff...ffe
wxFileOffset pos = 1; wxFileOffset pos = 1;
pos <<= sizeof(pos) * 8 - 1; pos <<= sizeof(pos) * 8 - 1;
pos = ~pos - 1; pos = ~pos - 1;
char ch; char ch;
size_t size = 1; size_t size = 1;
m_backer.m_impl->ReadAt(pos, &ch, &size); m_backer.m_impl->ReadAt(pos, &ch, &size);
len = GetLength(); len = GetLength();
} }
return len; return len;
} }
size_t wxBackedInputStream::OnSysRead(void *buffer, size_t size) size_t wxBackedInputStream::OnSysRead(void *buffer, size_t size)
{ {
if (!IsOk()) if (!IsOk())
return 0; return 0;
m_lasterror = m_backer.m_impl->ReadAt(m_pos, buffer, &size); m_lasterror = m_backer.m_impl->ReadAt(m_pos, buffer, &size);
m_pos += size; m_pos += size;
return size; return size;
} }
wxFileOffset wxBackedInputStream::OnSysSeek(wxFileOffset pos, wxSeekMode mode) wxFileOffset wxBackedInputStream::OnSysSeek(wxFileOffset pos, wxSeekMode mode)
{ {
switch (mode) { switch (mode) {
case wxFromCurrent: case wxFromCurrent:
{ {
m_pos += pos; m_pos += pos;
break; break;
} }
case wxFromEnd: case wxFromEnd:
{ {
wxFileOffset len = GetLength(); wxFileOffset len = GetLength();
if (len == wxInvalidOffset) if (len == wxInvalidOffset)
return wxInvalidOffset; return wxInvalidOffset;
m_pos = len + pos; m_pos = len + pos;
break; break;
} }
default: default:
{ {
m_pos = pos; m_pos = pos;
break; break;
} }
} }
return m_pos; return m_pos;
} }
wxFileOffset wxBackedInputStream::OnSysTell() const wxFileOffset wxBackedInputStream::OnSysTell() const
{ {
return m_pos; return m_pos;
} }
#endif // wxUSE_FILESYSTEM #endif // wxUSE_FILESYSTEM

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,224 +1,224 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/filepickercmn.cpp // Name: src/common/filepickercmn.cpp
// Purpose: wxFilePickerCtrl class implementation // Purpose: wxFilePickerCtrl class implementation
// Author: Francesco Montorsi (readapted code written by Vadim Zeitlin) // Author: Francesco Montorsi (readapted code written by Vadim Zeitlin)
// Modified by: // Modified by:
// Created: 15/04/2006 // Created: 15/04/2006
// RCS-ID: $Id: filepickercmn.cpp 42219 2006-10-21 19:53:05Z PC $ // RCS-ID: $Id: filepickercmn.cpp 42219 2006-10-21 19:53:05Z PC $
// Copyright: (c) Vadim Zeitlin, Francesco Montorsi // Copyright: (c) Vadim Zeitlin, Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FILEPICKERCTRL || wxUSE_DIRPICKERCTRL #if wxUSE_FILEPICKERCTRL || wxUSE_DIRPICKERCTRL
#include "wx/filepicker.h" #include "wx/filepicker.h"
#include "wx/filename.h" #include "wx/filename.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/textctrl.h" #include "wx/textctrl.h"
#endif #endif
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
const wxChar wxFilePickerCtrlNameStr[] = wxT("filepicker"); const wxChar wxFilePickerCtrlNameStr[] = wxT("filepicker");
const wxChar wxFilePickerWidgetNameStr[] = wxT("filepickerwidget"); const wxChar wxFilePickerWidgetNameStr[] = wxT("filepickerwidget");
const wxChar wxDirPickerCtrlNameStr[] = wxT("dirpicker"); const wxChar wxDirPickerCtrlNameStr[] = wxT("dirpicker");
const wxChar wxDirPickerWidgetNameStr[] = wxT("dirpickerwidget"); const wxChar wxDirPickerWidgetNameStr[] = wxT("dirpickerwidget");
const wxChar wxFilePickerWidgetLabel[] = wxT("Browse"); const wxChar wxFilePickerWidgetLabel[] = wxT("Browse");
const wxChar wxDirPickerWidgetLabel[] = wxT("Browse"); const wxChar wxDirPickerWidgetLabel[] = wxT("Browse");
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FILEPICKER_CHANGED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FILEPICKER_CHANGED)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_DIRPICKER_CHANGED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_DIRPICKER_CHANGED)
IMPLEMENT_DYNAMIC_CLASS(wxFileDirPickerEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxFileDirPickerEvent, wxCommandEvent)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFileDirPickerCtrlBase // wxFileDirPickerCtrlBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxFileDirPickerCtrlBase::CreateBase(wxWindow *parent, bool wxFileDirPickerCtrlBase::CreateBase(wxWindow *parent,
wxWindowID id, wxWindowID id,
const wxString &path, const wxString &path,
const wxString &message, const wxString &message,
const wxString &wildcard, const wxString &wildcard,
const wxPoint &pos, const wxPoint &pos,
const wxSize &size, const wxSize &size,
long style, long style,
const wxValidator& validator, const wxValidator& validator,
const wxString &name ) const wxString &name )
{ {
wxASSERT_MSG(path.empty() || CheckPath(path), wxT("Invalid initial path!")); wxASSERT_MSG(path.empty() || CheckPath(path), wxT("Invalid initial path!"));
if (!wxPickerBase::CreateBase(parent, id, path, pos, size, if (!wxPickerBase::CreateBase(parent, id, path, pos, size,
style, validator, name)) style, validator, name))
return false; return false;
if (!HasFlag(wxFLP_OPEN) && !HasFlag(wxFLP_SAVE)) if (!HasFlag(wxFLP_OPEN) && !HasFlag(wxFLP_SAVE))
m_windowStyle |= wxFLP_OPEN; // wxFD_OPEN is the default m_windowStyle |= wxFLP_OPEN; // wxFD_OPEN is the default
// check that the styles are not contradictory // check that the styles are not contradictory
wxASSERT_MSG( !(HasFlag(wxFLP_SAVE) && HasFlag(wxFLP_OPEN)), wxASSERT_MSG( !(HasFlag(wxFLP_SAVE) && HasFlag(wxFLP_OPEN)),
_T("can't specify both wxFLP_SAVE and wxFLP_OPEN at once") ); _T("can't specify both wxFLP_SAVE and wxFLP_OPEN at once") );
wxASSERT_MSG( !HasFlag(wxFLP_SAVE) || !HasFlag(wxFLP_FILE_MUST_EXIST), wxASSERT_MSG( !HasFlag(wxFLP_SAVE) || !HasFlag(wxFLP_FILE_MUST_EXIST),
_T("wxFLP_FILE_MUST_EXIST can't be used with wxFLP_SAVE" ) ); _T("wxFLP_FILE_MUST_EXIST can't be used with wxFLP_SAVE" ) );
wxASSERT_MSG( !HasFlag(wxFLP_OPEN) || !HasFlag(wxFLP_OVERWRITE_PROMPT), wxASSERT_MSG( !HasFlag(wxFLP_OPEN) || !HasFlag(wxFLP_OVERWRITE_PROMPT),
_T("wxFLP_OVERWRITE_PROMPT can't be used with wxFLP_OPEN") ); _T("wxFLP_OVERWRITE_PROMPT can't be used with wxFLP_OPEN") );
// create a wxFilePickerWidget or a wxDirPickerWidget... // create a wxFilePickerWidget or a wxDirPickerWidget...
m_pickerIface = CreatePicker(this, path, message, wildcard); m_pickerIface = CreatePicker(this, path, message, wildcard);
if ( !m_pickerIface ) if ( !m_pickerIface )
return false; return false;
m_picker = m_pickerIface->AsControl(); m_picker = m_pickerIface->AsControl();
// complete sizer creation // complete sizer creation
wxPickerBase::PostCreation(); wxPickerBase::PostCreation();
m_picker->Connect(GetEventType(), m_picker->Connect(GetEventType(),
wxFileDirPickerEventHandler(wxFileDirPickerCtrlBase::OnFileDirChange), wxFileDirPickerEventHandler(wxFileDirPickerCtrlBase::OnFileDirChange),
NULL, this); NULL, this);
// default's wxPickerBase textctrl limit is too small for this control: // default's wxPickerBase textctrl limit is too small for this control:
// make it bigger // make it bigger
if (m_text) m_text->SetMaxLength(512); if (m_text) m_text->SetMaxLength(512);
return true; return true;
} }
wxString wxFileDirPickerCtrlBase::GetPath() const wxString wxFileDirPickerCtrlBase::GetPath() const
{ {
return m_pickerIface->GetPath(); return m_pickerIface->GetPath();
} }
void wxFileDirPickerCtrlBase::SetPath(const wxString &path) void wxFileDirPickerCtrlBase::SetPath(const wxString &path)
{ {
m_pickerIface->SetPath(path); m_pickerIface->SetPath(path);
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
} }
void wxFileDirPickerCtrlBase::UpdatePickerFromTextCtrl() void wxFileDirPickerCtrlBase::UpdatePickerFromTextCtrl()
{ {
wxASSERT(m_text); wxASSERT(m_text);
if (m_bIgnoreNextTextCtrlUpdate) if (m_bIgnoreNextTextCtrlUpdate)
{ {
// ignore this update // ignore this update
m_bIgnoreNextTextCtrlUpdate = false; m_bIgnoreNextTextCtrlUpdate = false;
return; return;
} }
// remove the eventually present path-separator from the end of the textctrl // remove the eventually present path-separator from the end of the textctrl
// string otherwise we would generate a wxFileDirPickerEvent when changing // string otherwise we would generate a wxFileDirPickerEvent when changing
// from e.g. /home/user to /home/user/ and we want to avoid it ! // from e.g. /home/user to /home/user/ and we want to avoid it !
wxString newpath(GetTextCtrlValue()); wxString newpath(GetTextCtrlValue());
if (!CheckPath(newpath)) if (!CheckPath(newpath))
return; // invalid user input return; // invalid user input
if (m_pickerIface->GetPath() != newpath) if (m_pickerIface->GetPath() != newpath)
{ {
m_pickerIface->SetPath(newpath); m_pickerIface->SetPath(newpath);
// update current working directory, if necessary // update current working directory, if necessary
// NOTE: the path separator is required because if newpath is "C:" // NOTE: the path separator is required because if newpath is "C:"
// then no change would happen // then no change would happen
if (IsCwdToUpdate()) if (IsCwdToUpdate())
wxSetWorkingDirectory(newpath); wxSetWorkingDirectory(newpath);
// fire an event // fire an event
wxFileDirPickerEvent event(GetEventType(), this, GetId(), newpath); wxFileDirPickerEvent event(GetEventType(), this, GetId(), newpath);
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
} }
void wxFileDirPickerCtrlBase::UpdateTextCtrlFromPicker() void wxFileDirPickerCtrlBase::UpdateTextCtrlFromPicker()
{ {
if (!m_text) if (!m_text)
return; // no textctrl to update return; // no textctrl to update
// NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED // NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED
// which will trigger a unneeded UpdateFromTextCtrl(); thus before using // which will trigger a unneeded UpdateFromTextCtrl(); thus before using
// SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag... // SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag...
m_bIgnoreNextTextCtrlUpdate = true; m_bIgnoreNextTextCtrlUpdate = true;
m_text->SetValue(m_pickerIface->GetPath()); m_text->SetValue(m_pickerIface->GetPath());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFileDirPickerCtrlBase - event handlers // wxFileDirPickerCtrlBase - event handlers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxFileDirPickerCtrlBase::OnFileDirChange(wxFileDirPickerEvent &ev) void wxFileDirPickerCtrlBase::OnFileDirChange(wxFileDirPickerEvent &ev)
{ {
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
// the wxFilePickerWidget sent us a colour-change notification. // the wxFilePickerWidget sent us a colour-change notification.
// forward this event to our parent // forward this event to our parent
wxFileDirPickerEvent event(GetEventType(), this, GetId(), ev.GetPath()); wxFileDirPickerEvent event(GetEventType(), this, GetId(), ev.GetPath());
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
#endif // wxUSE_FILEPICKERCTRL || wxUSE_DIRPICKERCTRL #endif // wxUSE_FILEPICKERCTRL || wxUSE_DIRPICKERCTRL
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFileDirPickerCtrl // wxFileDirPickerCtrl
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_FILEPICKERCTRL #if wxUSE_FILEPICKERCTRL
IMPLEMENT_DYNAMIC_CLASS(wxFilePickerCtrl, wxPickerBase) IMPLEMENT_DYNAMIC_CLASS(wxFilePickerCtrl, wxPickerBase)
bool wxFilePickerCtrl::CheckPath(const wxString& path) const bool wxFilePickerCtrl::CheckPath(const wxString& path) const
{ {
// if wxFLP_SAVE was given or wxFLP_FILE_MUST_EXIST has NOT been given we // if wxFLP_SAVE was given or wxFLP_FILE_MUST_EXIST has NOT been given we
// must accept any path // must accept any path
return HasFlag(wxFLP_SAVE) || return HasFlag(wxFLP_SAVE) ||
!HasFlag(wxFLP_FILE_MUST_EXIST) || !HasFlag(wxFLP_FILE_MUST_EXIST) ||
wxFileName::FileExists(path); wxFileName::FileExists(path);
} }
wxString wxFilePickerCtrl::GetTextCtrlValue() const wxString wxFilePickerCtrl::GetTextCtrlValue() const
{ {
// filter it through wxFileName to remove any spurious path separator // filter it through wxFileName to remove any spurious path separator
return wxFileName(m_text->GetValue()).GetFullPath(); return wxFileName(m_text->GetValue()).GetFullPath();
} }
#endif // wxUSE_FILEPICKERCTRL #endif // wxUSE_FILEPICKERCTRL
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxDirPickerCtrl // wxDirPickerCtrl
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#if wxUSE_DIRPICKERCTRL #if wxUSE_DIRPICKERCTRL
IMPLEMENT_DYNAMIC_CLASS(wxDirPickerCtrl, wxPickerBase) IMPLEMENT_DYNAMIC_CLASS(wxDirPickerCtrl, wxPickerBase)
bool wxDirPickerCtrl::CheckPath(const wxString& path) const bool wxDirPickerCtrl::CheckPath(const wxString& path) const
{ {
// if wxDIRP_DIR_MUST_EXIST has NOT been given we must accept any path // if wxDIRP_DIR_MUST_EXIST has NOT been given we must accept any path
return !HasFlag(wxDIRP_DIR_MUST_EXIST) || wxFileName::DirExists(path); return !HasFlag(wxDIRP_DIR_MUST_EXIST) || wxFileName::DirExists(path);
} }
wxString wxDirPickerCtrl::GetTextCtrlValue() const wxString wxDirPickerCtrl::GetTextCtrlValue() const
{ {
// filter it through wxFileName to remove any spurious path separator // filter it through wxFileName to remove any spurious path separator
return wxFileName::DirName(m_text->GetValue()).GetPath(); return wxFileName::DirName(m_text->GetValue()).GetPath();
} }
#endif // wxUSE_DIRPICKERCTRL #endif // wxUSE_DIRPICKERCTRL

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,36 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/filtall.cpp // Name: src/common/filtall.cpp
// Purpose: Link all filter streams // Purpose: Link all filter streams
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: filtall.cpp 42412 2006-10-25 20:41:12Z MW $ // RCS-ID: $Id: filtall.cpp 42412 2006-10-25 20:41:12Z MW $
// Copyright: (c) 2006 Mike Wetherell // Copyright: (c) 2006 Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_STREAMS #if wxUSE_STREAMS
#if wxUSE_ZLIB #if wxUSE_ZLIB
#include "wx/zstream.h" #include "wx/zstream.h"
#endif #endif
// Reference filter classes to ensure they are linked into a statically // Reference filter classes to ensure they are linked into a statically
// linked program that uses Find or GetFirst to look for an filter handler. // linked program that uses Find or GetFirst to look for an filter handler.
// It is in its own file so that the user can override this behaviour by // It is in its own file so that the user can override this behaviour by
// providing their own implementation. // providing their own implementation.
void wxUseFilterClasses() void wxUseFilterClasses()
{ {
#if wxUSE_ZLIB #if wxUSE_ZLIB
wxZlibClassFactory(); wxZlibClassFactory();
wxGzipClassFactory(); wxGzipClassFactory();
#endif #endif
} }
#endif // wxUSE_STREAMS #endif // wxUSE_STREAMS

View File

@ -1,43 +1,43 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/filtfind.cpp // Name: src/common/filtfind.cpp
// Purpose: Streams for filter formats // Purpose: Streams for filter formats
// Author: Mike Wetherell // Author: Mike Wetherell
// RCS-ID: $Id: filtfind.cpp 42412 2006-10-25 20:41:12Z MW $ // RCS-ID: $Id: filtfind.cpp 42412 2006-10-25 20:41:12Z MW $
// Copyright: (c) Mike Wetherell // Copyright: (c) Mike Wetherell
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_STREAMS #if wxUSE_STREAMS
#include "wx/stream.h" #include "wx/stream.h"
// These functions are in a separate file so that statically linked apps // These functions are in a separate file so that statically linked apps
// that do not call them to search for filter handlers will only link in // that do not call them to search for filter handlers will only link in
// the filter classes they use. // the filter classes they use.
const wxFilterClassFactory * const wxFilterClassFactory *
wxFilterClassFactory::Find(const wxChar *protocol, wxStreamProtocolType type) wxFilterClassFactory::Find(const wxChar *protocol, wxStreamProtocolType type)
{ {
for (const wxFilterClassFactory *f = GetFirst(); f; f = f->GetNext()) for (const wxFilterClassFactory *f = GetFirst(); f; f = f->GetNext())
if (f->CanHandle(protocol, type)) if (f->CanHandle(protocol, type))
return f; return f;
return NULL; return NULL;
} }
// static // static
const wxFilterClassFactory *wxFilterClassFactory::GetFirst() const wxFilterClassFactory *wxFilterClassFactory::GetFirst()
{ {
if (!sm_first) if (!sm_first)
wxUseFilterClasses(); wxUseFilterClasses();
return sm_first; return sm_first;
} }
#endif // wxUSE_STREAMS #endif // wxUSE_STREAMS

View File

@ -1,348 +1,348 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fldlgcmn.cpp // Name: src/common/fldlgcmn.cpp
// Purpose: wxFileDialog common functions // Purpose: wxFileDialog common functions
// Author: John Labenski // Author: John Labenski
// Modified by: // Modified by:
// Created: 14.06.03 (extracted from src/*/filedlg.cpp) // Created: 14.06.03 (extracted from src/*/filedlg.cpp)
// RCS-ID: $Id: fldlgcmn.cpp 47482 2007-07-15 14:12:08Z VS $ // RCS-ID: $Id: fldlgcmn.cpp 47482 2007-07-15 14:12:08Z VS $
// Copyright: (c) Robert Roebling // Copyright: (c) Robert Roebling
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#if wxUSE_FILEDLG #if wxUSE_FILEDLG
#include "wx/filedlg.h" #include "wx/filedlg.h"
#include "wx/dirdlg.h" #include "wx/dirdlg.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/string.h" #include "wx/string.h"
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/window.h" #include "wx/window.h"
#endif // WX_PRECOMP #endif // WX_PRECOMP
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxFileDialogBase // wxFileDialogBase
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxFileDialogBase, wxDialog) IMPLEMENT_DYNAMIC_CLASS(wxFileDialogBase, wxDialog)
void wxFileDialogBase::Init() void wxFileDialogBase::Init()
{ {
m_filterIndex = m_filterIndex =
m_windowStyle = 0; m_windowStyle = 0;
} }
bool wxFileDialogBase::Create(wxWindow *parent, bool wxFileDialogBase::Create(wxWindow *parent,
const wxString& message, const wxString& message,
const wxString& defaultDir, const wxString& defaultDir,
const wxString& defaultFile, const wxString& defaultFile,
const wxString& wildCard, const wxString& wildCard,
long style, long style,
const wxPoint& WXUNUSED(pos), const wxPoint& WXUNUSED(pos),
const wxSize& WXUNUSED(sz), const wxSize& WXUNUSED(sz),
const wxString& WXUNUSED(name)) const wxString& WXUNUSED(name))
{ {
m_message = message; m_message = message;
m_dir = defaultDir; m_dir = defaultDir;
m_fileName = defaultFile; m_fileName = defaultFile;
m_wildCard = wildCard; m_wildCard = wildCard;
m_parent = parent; m_parent = parent;
m_windowStyle = style; m_windowStyle = style;
m_filterIndex = 0; m_filterIndex = 0;
if (!HasFdFlag(wxFD_OPEN) && !HasFdFlag(wxFD_SAVE)) if (!HasFdFlag(wxFD_OPEN) && !HasFdFlag(wxFD_SAVE))
m_windowStyle |= wxFD_OPEN; // wxFD_OPEN is the default m_windowStyle |= wxFD_OPEN; // wxFD_OPEN is the default
// check that the styles are not contradictory // check that the styles are not contradictory
wxASSERT_MSG( !(HasFdFlag(wxFD_SAVE) && HasFdFlag(wxFD_OPEN)), wxASSERT_MSG( !(HasFdFlag(wxFD_SAVE) && HasFdFlag(wxFD_OPEN)),
_T("can't specify both wxFD_SAVE and wxFD_OPEN at once") ); _T("can't specify both wxFD_SAVE and wxFD_OPEN at once") );
wxASSERT_MSG( !HasFdFlag(wxFD_SAVE) || wxASSERT_MSG( !HasFdFlag(wxFD_SAVE) ||
(!HasFdFlag(wxFD_MULTIPLE) && !HasFdFlag(wxFD_FILE_MUST_EXIST)), (!HasFdFlag(wxFD_MULTIPLE) && !HasFdFlag(wxFD_FILE_MUST_EXIST)),
_T("wxFD_MULTIPLE or wxFD_FILE_MUST_EXIST can't be used with wxFD_SAVE" ) ); _T("wxFD_MULTIPLE or wxFD_FILE_MUST_EXIST can't be used with wxFD_SAVE" ) );
wxASSERT_MSG( !HasFdFlag(wxFD_OPEN) || !HasFdFlag(wxFD_OVERWRITE_PROMPT), wxASSERT_MSG( !HasFdFlag(wxFD_OPEN) || !HasFdFlag(wxFD_OVERWRITE_PROMPT),
_T("wxFD_OVERWRITE_PROMPT can't be used with wxFD_OPEN") ); _T("wxFD_OVERWRITE_PROMPT can't be used with wxFD_OPEN") );
if ( wildCard.empty() || wildCard == wxFileSelectorDefaultWildcardStr ) if ( wildCard.empty() || wildCard == wxFileSelectorDefaultWildcardStr )
{ {
m_wildCard = wxString::Format(_("All files (%s)|%s"), m_wildCard = wxString::Format(_("All files (%s)|%s"),
wxFileSelectorDefaultWildcardStr, wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr); wxFileSelectorDefaultWildcardStr);
} }
else // have wild card else // have wild card
{ {
// convert m_wildCard from "*.bar" to "bar files (*.bar)|*.bar" // convert m_wildCard from "*.bar" to "bar files (*.bar)|*.bar"
if ( m_wildCard.Find(wxT('|')) == wxNOT_FOUND ) if ( m_wildCard.Find(wxT('|')) == wxNOT_FOUND )
{ {
wxString::size_type nDot = m_wildCard.find(_T("*.")); wxString::size_type nDot = m_wildCard.find(_T("*."));
if ( nDot != wxString::npos ) if ( nDot != wxString::npos )
nDot++; nDot++;
else else
nDot = 0; nDot = 0;
m_wildCard = wxString::Format m_wildCard = wxString::Format
( (
_("%s files (%s)|%s"), _("%s files (%s)|%s"),
wildCard.c_str() + nDot, wildCard.c_str() + nDot,
wildCard.c_str(), wildCard.c_str(),
wildCard.c_str() wildCard.c_str()
); );
} }
} }
return true; return true;
} }
#if WXWIN_COMPATIBILITY_2_4 #if WXWIN_COMPATIBILITY_2_4
// Parses the filterStr, returning the number of filters. // Parses the filterStr, returning the number of filters.
// Returns 0 if none or if there's a problem. // Returns 0 if none or if there's a problem.
// filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg" // filterStr is in the form: "All files (*.*)|*.*|JPEG Files (*.jpeg)|*.jpg"
int wxFileDialogBase::ParseWildcard(const wxString& filterStr, int wxFileDialogBase::ParseWildcard(const wxString& filterStr,
wxArrayString& descriptions, wxArrayString& descriptions,
wxArrayString& filters) wxArrayString& filters)
{ {
return ::wxParseCommonDialogsFilter(filterStr, descriptions, filters); return ::wxParseCommonDialogsFilter(filterStr, descriptions, filters);
} }
#endif // WXWIN_COMPATIBILITY_2_4 #endif // WXWIN_COMPATIBILITY_2_4
#if WXWIN_COMPATIBILITY_2_6 #if WXWIN_COMPATIBILITY_2_6
long wxFileDialogBase::GetStyle() const long wxFileDialogBase::GetStyle() const
{ {
return GetWindowStyle(); return GetWindowStyle();
} }
void wxFileDialogBase::SetStyle(long style) void wxFileDialogBase::SetStyle(long style)
{ {
SetWindowStyle(style); SetWindowStyle(style);
} }
#endif // WXWIN_COMPATIBILITY_2_6 #endif // WXWIN_COMPATIBILITY_2_6
wxString wxFileDialogBase::AppendExtension(const wxString &filePath, wxString wxFileDialogBase::AppendExtension(const wxString &filePath,
const wxString &extensionList) const wxString &extensionList)
{ {
// strip off path, to avoid problems with "path.bar/foo" // strip off path, to avoid problems with "path.bar/foo"
wxString fileName = filePath.AfterLast(wxFILE_SEP_PATH); wxString fileName = filePath.AfterLast(wxFILE_SEP_PATH);
// if fileName is of form "foo.bar" it's ok, return it // if fileName is of form "foo.bar" it's ok, return it
int idx_dot = fileName.Find(wxT('.'), true); int idx_dot = fileName.Find(wxT('.'), true);
if ((idx_dot != wxNOT_FOUND) && (idx_dot < (int)fileName.length() - 1)) if ((idx_dot != wxNOT_FOUND) && (idx_dot < (int)fileName.length() - 1))
return filePath; return filePath;
// get the first extension from extensionList, or all of it // get the first extension from extensionList, or all of it
wxString ext = extensionList.BeforeFirst(wxT(';')); wxString ext = extensionList.BeforeFirst(wxT(';'));
// if ext == "foo" or "foo." there's no extension // if ext == "foo" or "foo." there's no extension
int idx_ext_dot = ext.Find(wxT('.'), true); int idx_ext_dot = ext.Find(wxT('.'), true);
if ((idx_ext_dot == wxNOT_FOUND) || (idx_ext_dot == (int)ext.length() - 1)) if ((idx_ext_dot == wxNOT_FOUND) || (idx_ext_dot == (int)ext.length() - 1))
return filePath; return filePath;
else else
ext = ext.AfterLast(wxT('.')); ext = ext.AfterLast(wxT('.'));
// if ext == "*" or "bar*" or "b?r" or " " then its not valid // if ext == "*" or "bar*" or "b?r" or " " then its not valid
if ((ext.Find(wxT('*')) != wxNOT_FOUND) || if ((ext.Find(wxT('*')) != wxNOT_FOUND) ||
(ext.Find(wxT('?')) != wxNOT_FOUND) || (ext.Find(wxT('?')) != wxNOT_FOUND) ||
(ext.Strip(wxString::both).empty())) (ext.Strip(wxString::both).empty()))
return filePath; return filePath;
// if fileName doesn't have a '.' then add one // if fileName doesn't have a '.' then add one
if (filePath.Last() != wxT('.')) if (filePath.Last() != wxT('.'))
ext = wxT(".") + ext; ext = wxT(".") + ext;
return filePath + ext; return filePath + ext;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxFileDialog convenience functions // wxFileDialog convenience functions
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
wxString wxFileSelector(const wxChar *title, wxString wxFileSelector(const wxChar *title,
const wxChar *defaultDir, const wxChar *defaultDir,
const wxChar *defaultFileName, const wxChar *defaultFileName,
const wxChar *defaultExtension, const wxChar *defaultExtension,
const wxChar *filter, const wxChar *filter,
int flags, int flags,
wxWindow *parent, wxWindow *parent,
int x, int y) int x, int y)
{ {
// The defaultExtension, if non-NULL, is // The defaultExtension, if non-NULL, is
// appended to the filename if the user fails to type an extension. The new // appended to the filename if the user fails to type an extension. The new
// implementation (taken from wxFileSelectorEx) appends the extension // implementation (taken from wxFileSelectorEx) appends the extension
// automatically, by looking at the filter specification. In fact this // automatically, by looking at the filter specification. In fact this
// should be better than the native Microsoft implementation because // should be better than the native Microsoft implementation because
// Windows only allows *one* default extension, whereas here we do the // Windows only allows *one* default extension, whereas here we do the
// right thing depending on the filter the user has chosen. // right thing depending on the filter the user has chosen.
// If there's a default extension specified but no filter, we create a // If there's a default extension specified but no filter, we create a
// suitable filter. // suitable filter.
wxString filter2; wxString filter2;
if ( !wxIsEmpty(defaultExtension) && wxIsEmpty(filter) ) if ( !wxIsEmpty(defaultExtension) && wxIsEmpty(filter) )
filter2 = wxString(wxT("*.")) + defaultExtension; filter2 = wxString(wxT("*.")) + defaultExtension;
else if ( !wxIsEmpty(filter) ) else if ( !wxIsEmpty(filter) )
filter2 = filter; filter2 = filter;
wxString defaultDirString; wxString defaultDirString;
if (!wxIsEmpty(defaultDir)) if (!wxIsEmpty(defaultDir))
defaultDirString = defaultDir; defaultDirString = defaultDir;
wxString defaultFilenameString; wxString defaultFilenameString;
if (!wxIsEmpty(defaultFileName)) if (!wxIsEmpty(defaultFileName))
defaultFilenameString = defaultFileName; defaultFilenameString = defaultFileName;
wxFileDialog fileDialog(parent, title, defaultDirString, wxFileDialog fileDialog(parent, title, defaultDirString,
defaultFilenameString, filter2, defaultFilenameString, filter2,
flags, wxPoint(x, y)); flags, wxPoint(x, y));
// if filter is of form "All files (*)|*|..." set correct filter index // if filter is of form "All files (*)|*|..." set correct filter index
if((wxStrlen(defaultExtension) != 0) && (filter2.Find(wxT('|')) != wxNOT_FOUND)) if((wxStrlen(defaultExtension) != 0) && (filter2.Find(wxT('|')) != wxNOT_FOUND))
{ {
int filterIndex = 0; int filterIndex = 0;
wxArrayString descriptions, filters; wxArrayString descriptions, filters;
// don't care about errors, handled already by wxFileDialog // don't care about errors, handled already by wxFileDialog
(void)wxParseCommonDialogsFilter(filter2, descriptions, filters); (void)wxParseCommonDialogsFilter(filter2, descriptions, filters);
for (size_t n=0; n<filters.GetCount(); n++) for (size_t n=0; n<filters.GetCount(); n++)
{ {
if (filters[n].Contains(defaultExtension)) if (filters[n].Contains(defaultExtension))
{ {
filterIndex = n; filterIndex = n;
break; break;
} }
} }
if (filterIndex > 0) if (filterIndex > 0)
fileDialog.SetFilterIndex(filterIndex); fileDialog.SetFilterIndex(filterIndex);
} }
wxString filename; wxString filename;
if ( fileDialog.ShowModal() == wxID_OK ) if ( fileDialog.ShowModal() == wxID_OK )
{ {
filename = fileDialog.GetPath(); filename = fileDialog.GetPath();
} }
return filename; return filename;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxFileSelectorEx // wxFileSelectorEx
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
wxString wxFileSelectorEx(const wxChar *title, wxString wxFileSelectorEx(const wxChar *title,
const wxChar *defaultDir, const wxChar *defaultDir,
const wxChar *defaultFileName, const wxChar *defaultFileName,
int* defaultFilterIndex, int* defaultFilterIndex,
const wxChar *filter, const wxChar *filter,
int flags, int flags,
wxWindow* parent, wxWindow* parent,
int x, int x,
int y) int y)
{ {
wxFileDialog fileDialog(parent, wxFileDialog fileDialog(parent,
!wxIsEmpty(title) ? title : wxEmptyString, !wxIsEmpty(title) ? title : wxEmptyString,
!wxIsEmpty(defaultDir) ? defaultDir : wxEmptyString, !wxIsEmpty(defaultDir) ? defaultDir : wxEmptyString,
!wxIsEmpty(defaultFileName) ? defaultFileName : wxEmptyString, !wxIsEmpty(defaultFileName) ? defaultFileName : wxEmptyString,
!wxIsEmpty(filter) ? filter : wxEmptyString, !wxIsEmpty(filter) ? filter : wxEmptyString,
flags, wxPoint(x, y)); flags, wxPoint(x, y));
wxString filename; wxString filename;
if ( fileDialog.ShowModal() == wxID_OK ) if ( fileDialog.ShowModal() == wxID_OK )
{ {
if ( defaultFilterIndex ) if ( defaultFilterIndex )
*defaultFilterIndex = fileDialog.GetFilterIndex(); *defaultFilterIndex = fileDialog.GetFilterIndex();
filename = fileDialog.GetPath(); filename = fileDialog.GetPath();
} }
return filename; return filename;
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxDefaultFileSelector - Generic load/save dialog (for internal use only) // wxDefaultFileSelector - Generic load/save dialog (for internal use only)
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
static wxString wxDefaultFileSelector(bool load, static wxString wxDefaultFileSelector(bool load,
const wxChar *what, const wxChar *what,
const wxChar *extension, const wxChar *extension,
const wxChar *default_name, const wxChar *default_name,
wxWindow *parent) wxWindow *parent)
{ {
wxString prompt; wxString prompt;
wxString str; wxString str;
if (load) if (load)
str = _("Load %s file"); str = _("Load %s file");
else else
str = _("Save %s file"); str = _("Save %s file");
prompt.Printf(str, what); prompt.Printf(str, what);
wxString wild; wxString wild;
const wxChar *ext = extension; const wxChar *ext = extension;
if ( !wxIsEmpty(ext) ) if ( !wxIsEmpty(ext) )
{ {
if ( *ext == wxT('.') ) if ( *ext == wxT('.') )
ext++; ext++;
wild.Printf(wxT("*.%s"), ext); wild.Printf(wxT("*.%s"), ext);
} }
else // no extension specified else // no extension specified
{ {
wild = wxFileSelectorDefaultWildcardStr; wild = wxFileSelectorDefaultWildcardStr;
} }
return wxFileSelector(prompt, NULL, default_name, ext, wild, return wxFileSelector(prompt, NULL, default_name, ext, wild,
load ? wxFD_OPEN : wxFD_SAVE, parent); load ? wxFD_OPEN : wxFD_SAVE, parent);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxLoadFileSelector // wxLoadFileSelector
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
WXDLLEXPORT wxString wxLoadFileSelector(const wxChar *what, WXDLLEXPORT wxString wxLoadFileSelector(const wxChar *what,
const wxChar *extension, const wxChar *extension,
const wxChar *default_name, const wxChar *default_name,
wxWindow *parent) wxWindow *parent)
{ {
return wxDefaultFileSelector(true, what, extension, default_name, parent); return wxDefaultFileSelector(true, what, extension, default_name, parent);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxSaveFileSelector // wxSaveFileSelector
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
WXDLLEXPORT wxString wxSaveFileSelector(const wxChar *what, WXDLLEXPORT wxString wxSaveFileSelector(const wxChar *what,
const wxChar *extension, const wxChar *extension,
const wxChar *default_name, const wxChar *default_name,
wxWindow *parent) wxWindow *parent)
{ {
return wxDefaultFileSelector(false, what, extension, default_name, parent); return wxDefaultFileSelector(false, what, extension, default_name, parent);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxDirDialogBase // wxDirDialogBase
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
#if WXWIN_COMPATIBILITY_2_6 #if WXWIN_COMPATIBILITY_2_6
long wxDirDialogBase::GetStyle() const long wxDirDialogBase::GetStyle() const
{ {
return GetWindowStyle(); return GetWindowStyle();
} }
void wxDirDialogBase::SetStyle(long style) void wxDirDialogBase::SetStyle(long style)
{ {
SetWindowStyle(style); SetWindowStyle(style);
} }
#endif // WXWIN_COMPATIBILITY_2_6 #endif // WXWIN_COMPATIBILITY_2_6
#endif // wxUSE_FILEDLG #endif // wxUSE_FILEDLG

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,131 +1,131 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fontenumcmn.cpp // Name: src/common/fontenumcmn.cpp
// Purpose: wxFontEnumerator class // Purpose: wxFontEnumerator class
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 7/5/2006 // Created: 7/5/2006
// RCS-ID: $Id: fontenumcmn.cpp 43727 2006-12-01 10:14:28Z VS $ // RCS-ID: $Id: fontenumcmn.cpp 43727 2006-12-01 10:14:28Z VS $
// Copyright: (c) 1999-2003 Vadim Zeitlin <vadim@wxwindows.org> // Copyright: (c) 1999-2003 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/fontenum.h" #include "wx/fontenum.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// A simple wxFontEnumerator which doesn't perform any filtering and // A simple wxFontEnumerator which doesn't perform any filtering and
// just returns all facenames and encodings found in the system // just returns all facenames and encodings found in the system
class WXDLLEXPORT wxSimpleFontEnumerator : public wxFontEnumerator class WXDLLEXPORT wxSimpleFontEnumerator : public wxFontEnumerator
{ {
public: public:
wxSimpleFontEnumerator() { } wxSimpleFontEnumerator() { }
// called by EnumerateFacenames // called by EnumerateFacenames
virtual bool OnFacename(const wxString& facename) virtual bool OnFacename(const wxString& facename)
{ {
m_arrFacenames.Add(facename); m_arrFacenames.Add(facename);
return true; return true;
} }
// called by EnumerateEncodings // called by EnumerateEncodings
virtual bool OnFontEncoding(const wxString& WXUNUSED(facename), virtual bool OnFontEncoding(const wxString& WXUNUSED(facename),
const wxString& encoding) const wxString& encoding)
{ {
m_arrEncodings.Add(encoding); m_arrEncodings.Add(encoding);
return true; return true;
} }
public: public:
wxArrayString m_arrFacenames, m_arrEncodings; wxArrayString m_arrFacenames, m_arrEncodings;
}; };
/* static */ /* static */
wxArrayString wxFontEnumerator::GetFacenames(wxFontEncoding encoding, bool fixedWidthOnly) wxArrayString wxFontEnumerator::GetFacenames(wxFontEncoding encoding, bool fixedWidthOnly)
{ {
wxSimpleFontEnumerator temp; wxSimpleFontEnumerator temp;
temp.EnumerateFacenames(encoding, fixedWidthOnly); temp.EnumerateFacenames(encoding, fixedWidthOnly);
return temp.m_arrFacenames; return temp.m_arrFacenames;
} }
/* static */ /* static */
wxArrayString wxFontEnumerator::GetEncodings(const wxString& facename) wxArrayString wxFontEnumerator::GetEncodings(const wxString& facename)
{ {
wxSimpleFontEnumerator temp; wxSimpleFontEnumerator temp;
temp.EnumerateEncodings(facename); temp.EnumerateEncodings(facename);
return temp.m_arrEncodings; return temp.m_arrEncodings;
} }
/* static */ /* static */
bool wxFontEnumerator::IsValidFacename(const wxString &facename) bool wxFontEnumerator::IsValidFacename(const wxString &facename)
{ {
// we cache the result of wxFontEnumerator::GetFacenames supposing that // we cache the result of wxFontEnumerator::GetFacenames supposing that
// the array of face names won't change in the session of this program // the array of face names won't change in the session of this program
static wxArrayString s_arr = wxFontEnumerator::GetFacenames(); static wxArrayString s_arr = wxFontEnumerator::GetFacenames();
#ifdef __WXMSW__ #ifdef __WXMSW__
// Quoting the MSDN: // Quoting the MSDN:
// "MS Shell Dlg is a mapping mechanism that enables // "MS Shell Dlg is a mapping mechanism that enables
// U.S. English Microsoft Windows NT, and Microsoft Windows 2000 to // U.S. English Microsoft Windows NT, and Microsoft Windows 2000 to
// support locales that have characters that are not contained in code // support locales that have characters that are not contained in code
// page 1252. It is not a font but a face name for a nonexistent font." // page 1252. It is not a font but a face name for a nonexistent font."
// Thus we need to consider "Ms Shell Dlg" and "Ms Shell Dlg 2" as valid // Thus we need to consider "Ms Shell Dlg" and "Ms Shell Dlg 2" as valid
// font face names even if they are enumerated by wxFontEnumerator // font face names even if they are enumerated by wxFontEnumerator
if (facename.IsSameAs(wxT("Ms Shell Dlg"), false) || if (facename.IsSameAs(wxT("Ms Shell Dlg"), false) ||
facename.IsSameAs(wxT("Ms Shell Dlg 2"), false)) facename.IsSameAs(wxT("Ms Shell Dlg 2"), false))
return true; return true;
#endif #endif
// is given font face name a valid one ? // is given font face name a valid one ?
if (s_arr.Index(facename, false) == wxNOT_FOUND) if (s_arr.Index(facename, false) == wxNOT_FOUND)
return false; return false;
return true; return true;
} }
#ifdef wxHAS_UTF8_FONTS #ifdef wxHAS_UTF8_FONTS
bool wxFontEnumerator::EnumerateEncodingsUTF8(const wxString& facename) bool wxFontEnumerator::EnumerateEncodingsUTF8(const wxString& facename)
{ {
// name of UTF-8 encoding: no need to use wxFontMapper for it as it's // name of UTF-8 encoding: no need to use wxFontMapper for it as it's
// unlikely to change // unlikely to change
const wxString utf8(_T("UTF-8")); const wxString utf8(_T("UTF-8"));
// all fonts are in UTF-8 only if this code is used // all fonts are in UTF-8 only if this code is used
if ( !facename.empty() ) if ( !facename.empty() )
{ {
OnFontEncoding(facename, utf8); OnFontEncoding(facename, utf8);
return true; return true;
} }
// so enumerating all facenames supporting this encoding is the same as // so enumerating all facenames supporting this encoding is the same as
// enumerating all facenames // enumerating all facenames
const wxArrayString facenames(GetFacenames(wxFONTENCODING_UTF8)); const wxArrayString facenames(GetFacenames(wxFONTENCODING_UTF8));
const size_t count = facenames.size(); const size_t count = facenames.size();
if ( !count ) if ( !count )
return false; return false;
for ( size_t n = 0; n < count; n++ ) for ( size_t n = 0; n < count; n++ )
{ {
OnFontEncoding(facenames[n], utf8); OnFontEncoding(facenames[n], utf8);
} }
return true; return true;
} }
#endif // wxHAS_UTF8_FONTS #endif // wxHAS_UTF8_FONTS

File diff suppressed because it is too large Load Diff

View File

@ -1,345 +1,345 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fontmgrcmn.cpp // Name: src/common/fontmgrcmn.cpp
// Purpose: font management for ports that don't have their own // Purpose: font management for ports that don't have their own
// Author: Vaclav Slavik // Author: Vaclav Slavik
// Created: 2006-11-18 // Created: 2006-11-18
// RCS-ID: $Id: fontmgrcmn.cpp 43550 2006-11-20 20:45:57Z VS $ // RCS-ID: $Id: fontmgrcmn.cpp 43550 2006-11-20 20:45:57Z VS $
// Copyright: (c) 2001-2002 SciTech Software, Inc. (www.scitechsoft.com) // Copyright: (c) 2001-2002 SciTech Software, Inc. (www.scitechsoft.com)
// (c) 2006 REA Elektronik GmbH // (c) 2006 REA Elektronik GmbH
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/private/fontmgr.h" #include "wx/private/fontmgr.h"
#include "wx/listimpl.cpp" #include "wx/listimpl.cpp"
#include "wx/hashmap.h" #include "wx/hashmap.h"
WX_DECLARE_LIST(wxFontInstance, wxFontInstanceList); WX_DECLARE_LIST(wxFontInstance, wxFontInstanceList);
WX_DEFINE_LIST(wxFontInstanceList) WX_DEFINE_LIST(wxFontInstanceList)
WX_DEFINE_LIST(wxFontBundleList) WX_DEFINE_LIST(wxFontBundleList)
WX_DECLARE_HASH_MAP(wxString, wxFontBundle*, WX_DECLARE_HASH_MAP(wxString, wxFontBundle*,
wxStringHash, wxStringEqual, wxStringHash, wxStringEqual,
wxFontBundleHash); wxFontBundleHash);
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontFaceBase // wxFontFaceBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFontFaceBase::wxFontFaceBase() wxFontFaceBase::wxFontFaceBase()
: m_refCnt(0) : m_refCnt(0)
{ {
m_instances = new wxFontInstanceList; m_instances = new wxFontInstanceList;
m_instances->DeleteContents(true); m_instances->DeleteContents(true);
} }
wxFontFaceBase::~wxFontFaceBase() wxFontFaceBase::~wxFontFaceBase()
{ {
delete m_instances; delete m_instances;
} }
void wxFontFaceBase::Acquire() void wxFontFaceBase::Acquire()
{ {
m_refCnt++; m_refCnt++;
} }
void wxFontFaceBase::Release() void wxFontFaceBase::Release()
{ {
if ( --m_refCnt == 0 ) if ( --m_refCnt == 0 )
{ {
m_instances->Clear(); m_instances->Clear();
} }
} }
wxFontInstance *wxFontFaceBase::GetFontInstance(float ptSize, bool aa) wxFontInstance *wxFontFaceBase::GetFontInstance(float ptSize, bool aa)
{ {
wxASSERT_MSG( m_refCnt > 0, _T("font library not loaded!") ); wxASSERT_MSG( m_refCnt > 0, _T("font library not loaded!") );
wxFontInstance *i; wxFontInstance *i;
wxFontInstanceList::Node *node; wxFontInstanceList::Node *node;
for ( node = m_instances->GetFirst(); node; node = node->GetNext() ) for ( node = m_instances->GetFirst(); node; node = node->GetNext() )
{ {
i = node->GetData(); i = node->GetData();
if ( i->GetPointSize() == ptSize && i->IsAntiAliased() == aa ) if ( i->GetPointSize() == ptSize && i->IsAntiAliased() == aa )
return i; return i;
} }
i = CreateFontInstance(ptSize, aa); i = CreateFontInstance(ptSize, aa);
m_instances->Append(i); m_instances->Append(i);
return i; return i;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontBundleBase // wxFontBundleBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFontBundleBase::wxFontBundleBase() wxFontBundleBase::wxFontBundleBase()
{ {
for (int i = 0; i < FaceType_Max; i++) for (int i = 0; i < FaceType_Max; i++)
m_faces[i] = NULL; m_faces[i] = NULL;
} }
wxFontBundleBase::~wxFontBundleBase() wxFontBundleBase::~wxFontBundleBase()
{ {
for (int i = 0; i < FaceType_Max; i++) for (int i = 0; i < FaceType_Max; i++)
delete m_faces[i]; delete m_faces[i];
} }
wxFontFace *wxFontBundleBase::GetFace(FaceType type) const wxFontFace *wxFontBundleBase::GetFace(FaceType type) const
{ {
wxFontFace *f = m_faces[type]; wxFontFace *f = m_faces[type];
wxCHECK_MSG( f, NULL, _T("no such face in font bundle") ); wxCHECK_MSG( f, NULL, _T("no such face in font bundle") );
f->Acquire(); f->Acquire();
return f; return f;
} }
wxFontFace * wxFontFace *
wxFontBundleBase::GetFaceForFont(const wxFontMgrFontRefData& font) const wxFontBundleBase::GetFaceForFont(const wxFontMgrFontRefData& font) const
{ {
wxASSERT_MSG( font.GetFaceName().empty() || font.GetFaceName() == GetName(), wxASSERT_MSG( font.GetFaceName().empty() || font.GetFaceName() == GetName(),
_T("calling GetFaceForFont for incompatible font") ); _T("calling GetFaceForFont for incompatible font") );
int type = FaceType_Regular; int type = FaceType_Regular;
if ( font.GetWeight() == wxBOLD ) if ( font.GetWeight() == wxBOLD )
type |= FaceType_Bold; type |= FaceType_Bold;
// FIXME -- this should read "if ( font->GetStyle() == wxITALIC )", // FIXME -- this should read "if ( font->GetStyle() == wxITALIC )",
// but since MGL neither DFB supports slant, we try to display it with // but since MGL neither DFB supports slant, we try to display it with
// italic face (better than nothing...) // italic face (better than nothing...)
if ( font.GetStyle() == wxITALIC || font.GetStyle() == wxSLANT ) if ( font.GetStyle() == wxITALIC || font.GetStyle() == wxSLANT )
{ {
if ( HasFace((FaceType)(type | FaceType_Italic)) ) if ( HasFace((FaceType)(type | FaceType_Italic)) )
type |= FaceType_Italic; type |= FaceType_Italic;
} }
if ( !HasFace((FaceType)type) ) if ( !HasFace((FaceType)type) )
{ {
for (int i = 0; i < FaceType_Max; i++) for (int i = 0; i < FaceType_Max; i++)
{ {
if ( HasFace((FaceType)i) ) if ( HasFace((FaceType)i) )
return GetFace((FaceType)i); return GetFace((FaceType)i);
} }
wxFAIL_MSG( _T("no face") ); wxFAIL_MSG( _T("no face") );
return NULL; return NULL;
} }
return GetFace((FaceType)type); return GetFace((FaceType)type);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontsManagerBase // wxFontsManagerBase
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFontsManager *wxFontsManagerBase::ms_instance = NULL; wxFontsManager *wxFontsManagerBase::ms_instance = NULL;
wxFontsManagerBase::wxFontsManagerBase() wxFontsManagerBase::wxFontsManagerBase()
{ {
m_hash = new wxFontBundleHash(); m_hash = new wxFontBundleHash();
m_list = new wxFontBundleList; m_list = new wxFontBundleList;
m_list->DeleteContents(true); m_list->DeleteContents(true);
} }
wxFontsManagerBase::~wxFontsManagerBase() wxFontsManagerBase::~wxFontsManagerBase()
{ {
delete m_hash; delete m_hash;
delete m_list; delete m_list;
} }
/* static */ /* static */
wxFontsManager *wxFontsManagerBase::Get() wxFontsManager *wxFontsManagerBase::Get()
{ {
if ( !ms_instance ) if ( !ms_instance )
ms_instance = new wxFontsManager(); ms_instance = new wxFontsManager();
return ms_instance; return ms_instance;
} }
/* static */ /* static */
void wxFontsManagerBase::CleanUp() void wxFontsManagerBase::CleanUp()
{ {
wxDELETE(ms_instance); wxDELETE(ms_instance);
} }
wxFontBundle *wxFontsManagerBase::GetBundle(const wxString& name) const wxFontBundle *wxFontsManagerBase::GetBundle(const wxString& name) const
{ {
return (*m_hash)[name.Lower()]; return (*m_hash)[name.Lower()];
} }
wxFontBundle * wxFontBundle *
wxFontsManagerBase::GetBundleForFont(const wxFontMgrFontRefData& font) const wxFontsManagerBase::GetBundleForFont(const wxFontMgrFontRefData& font) const
{ {
wxFontBundle *bundle = NULL; wxFontBundle *bundle = NULL;
wxString facename = font.GetFaceName(); wxString facename = font.GetFaceName();
if ( !facename.empty() ) if ( !facename.empty() )
bundle = GetBundle(facename); bundle = GetBundle(facename);
if ( !bundle ) if ( !bundle )
{ {
facename = GetDefaultFacename((wxFontFamily)font.GetFamily()); facename = GetDefaultFacename((wxFontFamily)font.GetFamily());
if ( !facename.empty() ) if ( !facename.empty() )
bundle = GetBundle(facename); bundle = GetBundle(facename);
} }
if ( !bundle ) if ( !bundle )
{ {
if ( m_list->GetFirst() ) if ( m_list->GetFirst() )
bundle = m_list->GetFirst()->GetData(); bundle = m_list->GetFirst()->GetData();
else else
wxFAIL_MSG(wxT("Fatal error, no fonts available!")); wxFAIL_MSG(wxT("Fatal error, no fonts available!"));
} }
return bundle; return bundle;
} }
void wxFontsManagerBase::AddBundle(wxFontBundle *bundle) void wxFontsManagerBase::AddBundle(wxFontBundle *bundle)
{ {
(*m_hash)[bundle->GetName().Lower()] = bundle; (*m_hash)[bundle->GetName().Lower()] = bundle;
m_list->Append(bundle); m_list->Append(bundle);
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontMgrFontRefData // wxFontMgrFontRefData
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
wxFontMgrFontRefData::wxFontMgrFontRefData(int size, wxFontMgrFontRefData::wxFontMgrFontRefData(int size,
int family, int family,
int style, int style,
int weight, int weight,
bool underlined, bool underlined,
const wxString& faceName, const wxString& faceName,
wxFontEncoding encoding) wxFontEncoding encoding)
{ {
if ( family == wxDEFAULT ) if ( family == wxDEFAULT )
family = wxSWISS; family = wxSWISS;
if ( style == wxDEFAULT ) if ( style == wxDEFAULT )
style = wxNORMAL; style = wxNORMAL;
if ( weight == wxDEFAULT ) if ( weight == wxDEFAULT )
weight = wxNORMAL; weight = wxNORMAL;
if ( size == wxDEFAULT ) if ( size == wxDEFAULT )
size = 12; size = 12;
m_info.family = (wxFontFamily)family; m_info.family = (wxFontFamily)family;
m_info.faceName = faceName; m_info.faceName = faceName;
m_info.style = (wxFontStyle)style; m_info.style = (wxFontStyle)style;
m_info.weight = (wxFontWeight)weight; m_info.weight = (wxFontWeight)weight;
m_info.pointSize = size; m_info.pointSize = size;
m_info.underlined = underlined; m_info.underlined = underlined;
m_info.encoding = encoding; m_info.encoding = encoding;
m_noAA = false; m_noAA = false;
m_fontFace = NULL; m_fontFace = NULL;
m_fontBundle = NULL; m_fontBundle = NULL;
m_fontValid = false; m_fontValid = false;
} }
wxFontMgrFontRefData::wxFontMgrFontRefData(const wxFontMgrFontRefData& data) wxFontMgrFontRefData::wxFontMgrFontRefData(const wxFontMgrFontRefData& data)
{ {
m_info = data.m_info; m_info = data.m_info;
m_noAA = data.m_noAA; m_noAA = data.m_noAA;
m_fontFace = data.m_fontFace; m_fontFace = data.m_fontFace;
m_fontBundle = data.m_fontBundle; m_fontBundle = data.m_fontBundle;
m_fontValid = data.m_fontValid; m_fontValid = data.m_fontValid;
if ( m_fontFace ) if ( m_fontFace )
m_fontFace->Acquire(); m_fontFace->Acquire();
} }
wxFontMgrFontRefData::~wxFontMgrFontRefData() wxFontMgrFontRefData::~wxFontMgrFontRefData()
{ {
if ( m_fontFace ) if ( m_fontFace )
m_fontFace->Release(); m_fontFace->Release();
} }
wxFontBundle *wxFontMgrFontRefData::GetFontBundle() const wxFontBundle *wxFontMgrFontRefData::GetFontBundle() const
{ {
wxConstCast(this, wxFontMgrFontRefData)->EnsureValidFont(); wxConstCast(this, wxFontMgrFontRefData)->EnsureValidFont();
return m_fontBundle; return m_fontBundle;
} }
wxFontInstance * wxFontInstance *
wxFontMgrFontRefData::GetFontInstance(float scale, bool antialiased) const wxFontMgrFontRefData::GetFontInstance(float scale, bool antialiased) const
{ {
wxConstCast(this, wxFontMgrFontRefData)->EnsureValidFont(); wxConstCast(this, wxFontMgrFontRefData)->EnsureValidFont();
return m_fontFace->GetFontInstance(m_info.pointSize * scale, return m_fontFace->GetFontInstance(m_info.pointSize * scale,
antialiased && !m_noAA); antialiased && !m_noAA);
} }
void wxFontMgrFontRefData::SetPointSize(int pointSize) void wxFontMgrFontRefData::SetPointSize(int pointSize)
{ {
m_info.pointSize = pointSize; m_info.pointSize = pointSize;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetFamily(int family) void wxFontMgrFontRefData::SetFamily(int family)
{ {
m_info.family = (wxFontFamily)family; m_info.family = (wxFontFamily)family;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetStyle(int style) void wxFontMgrFontRefData::SetStyle(int style)
{ {
m_info.style = (wxFontStyle)style; m_info.style = (wxFontStyle)style;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetWeight(int weight) void wxFontMgrFontRefData::SetWeight(int weight)
{ {
m_info.weight = (wxFontWeight)weight; m_info.weight = (wxFontWeight)weight;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetFaceName(const wxString& faceName) void wxFontMgrFontRefData::SetFaceName(const wxString& faceName)
{ {
m_info.faceName = faceName; m_info.faceName = faceName;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetUnderlined(bool underlined) void wxFontMgrFontRefData::SetUnderlined(bool underlined)
{ {
m_info.underlined = underlined; m_info.underlined = underlined;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetEncoding(wxFontEncoding encoding) void wxFontMgrFontRefData::SetEncoding(wxFontEncoding encoding)
{ {
m_info.encoding = encoding; m_info.encoding = encoding;
m_fontValid = false; m_fontValid = false;
} }
void wxFontMgrFontRefData::SetNoAntiAliasing(bool no) void wxFontMgrFontRefData::SetNoAntiAliasing(bool no)
{ {
m_noAA = no; m_noAA = no;
} }
void wxFontMgrFontRefData::EnsureValidFont() void wxFontMgrFontRefData::EnsureValidFont()
{ {
if ( !m_fontValid ) if ( !m_fontValid )
{ {
wxFontFace *old = m_fontFace; wxFontFace *old = m_fontFace;
m_fontBundle = wxFontsManager::Get()->GetBundleForFont(*this); m_fontBundle = wxFontsManager::Get()->GetBundleForFont(*this);
m_fontFace = m_fontBundle->GetFaceForFont(*this); m_fontFace = m_fontBundle->GetFaceForFont(*this);
if ( old ) if ( old )
old->Release(); old->Release();
} }
} }

View File

@ -1,181 +1,181 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/fontpickercmn.cpp // Name: src/common/fontpickercmn.cpp
// Purpose: wxFontPickerCtrl class implementation // Purpose: wxFontPickerCtrl class implementation
// Author: Francesco Montorsi // Author: Francesco Montorsi
// Modified by: // Modified by:
// Created: 15/04/2006 // Created: 15/04/2006
// RCS-ID: $Id: fontpickercmn.cpp 42999 2006-11-03 21:54:13Z VZ $ // RCS-ID: $Id: fontpickercmn.cpp 42999 2006-11-03 21:54:13Z VZ $
// Copyright: (c) Francesco Montorsi // Copyright: (c) Francesco Montorsi
// Licence: wxWindows licence // Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FONTPICKERCTRL #if wxUSE_FONTPICKERCTRL
#include "wx/fontpicker.h" #include "wx/fontpicker.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/textctrl.h" #include "wx/textctrl.h"
#endif #endif
#include "wx/fontenum.h" #include "wx/fontenum.h"
#include "wx/tokenzr.h" #include "wx/tokenzr.h"
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
const wxChar wxFontPickerCtrlNameStr[] = wxT("fontpicker"); const wxChar wxFontPickerCtrlNameStr[] = wxT("fontpicker");
const wxChar wxFontPickerWidgetNameStr[] = wxT("fontpickerwidget"); const wxChar wxFontPickerWidgetNameStr[] = wxT("fontpickerwidget");
DEFINE_EVENT_TYPE(wxEVT_COMMAND_FONTPICKER_CHANGED) DEFINE_EVENT_TYPE(wxEVT_COMMAND_FONTPICKER_CHANGED)
IMPLEMENT_DYNAMIC_CLASS(wxFontPickerCtrl, wxPickerBase) IMPLEMENT_DYNAMIC_CLASS(wxFontPickerCtrl, wxPickerBase)
IMPLEMENT_DYNAMIC_CLASS(wxFontPickerEvent, wxCommandEvent) IMPLEMENT_DYNAMIC_CLASS(wxFontPickerEvent, wxCommandEvent)
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontPickerCtrl // wxFontPickerCtrl
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
#define M_PICKER ((wxFontPickerWidget*)m_picker) #define M_PICKER ((wxFontPickerWidget*)m_picker)
bool wxFontPickerCtrl::Create( wxWindow *parent, wxWindowID id, bool wxFontPickerCtrl::Create( wxWindow *parent, wxWindowID id,
const wxFont &initial, const wxFont &initial,
const wxPoint &pos, const wxSize &size, const wxPoint &pos, const wxSize &size,
long style, const wxValidator& validator, long style, const wxValidator& validator,
const wxString &name ) const wxString &name )
{ {
if (!wxPickerBase::CreateBase(parent, id, if (!wxPickerBase::CreateBase(parent, id,
Font2String(initial.IsOk() ? initial Font2String(initial.IsOk() ? initial
: *wxNORMAL_FONT), : *wxNORMAL_FONT),
pos, size, style, validator, name)) pos, size, style, validator, name))
return false; return false;
// the picker of a wxFontPickerCtrl is a wxFontPickerWidget // the picker of a wxFontPickerCtrl is a wxFontPickerWidget
m_picker = new wxFontPickerWidget(this, wxID_ANY, initial, m_picker = new wxFontPickerWidget(this, wxID_ANY, initial,
wxDefaultPosition, wxDefaultSize, wxDefaultPosition, wxDefaultSize,
GetPickerStyle(style)); GetPickerStyle(style));
// complete sizer creation // complete sizer creation
wxPickerBase::PostCreation(); wxPickerBase::PostCreation();
m_picker->Connect(wxEVT_COMMAND_FONTPICKER_CHANGED, m_picker->Connect(wxEVT_COMMAND_FONTPICKER_CHANGED,
wxFontPickerEventHandler(wxFontPickerCtrl::OnFontChange), wxFontPickerEventHandler(wxFontPickerCtrl::OnFontChange),
NULL, this); NULL, this);
return true; return true;
} }
wxString wxFontPickerCtrl::Font2String(const wxFont &f) wxString wxFontPickerCtrl::Font2String(const wxFont &f)
{ {
wxString ret = f.GetNativeFontInfoUserDesc(); wxString ret = f.GetNativeFontInfoUserDesc();
#ifdef __WXMSW__ #ifdef __WXMSW__
// on wxMSW the encoding of the font is appended at the end of the string; // on wxMSW the encoding of the font is appended at the end of the string;
// since encoding is not very user-friendly we remove it. // since encoding is not very user-friendly we remove it.
wxFontEncoding enc = f.GetEncoding(); wxFontEncoding enc = f.GetEncoding();
if ( enc != wxFONTENCODING_DEFAULT && enc != wxFONTENCODING_SYSTEM ) if ( enc != wxFONTENCODING_DEFAULT && enc != wxFONTENCODING_SYSTEM )
ret = ret.BeforeLast(wxT(' ')); ret = ret.BeforeLast(wxT(' '));
#endif #endif
return ret; return ret;
} }
wxFont wxFontPickerCtrl::String2Font(const wxString &s) wxFont wxFontPickerCtrl::String2Font(const wxString &s)
{ {
wxString str(s); wxString str(s);
wxFont ret; wxFont ret;
double n; double n;
// put a limit on the maximum point size which the user can enter // put a limit on the maximum point size which the user can enter
// NOTE: we suppose the last word of given string is the pointsize // NOTE: we suppose the last word of given string is the pointsize
wxString size = str.AfterLast(wxT(' ')); wxString size = str.AfterLast(wxT(' '));
if (size.ToDouble(&n)) if (size.ToDouble(&n))
{ {
if (n < 1) if (n < 1)
str = str.Left(str.length() - size.length()) + wxT("1"); str = str.Left(str.length() - size.length()) + wxT("1");
else if (n >= m_nMaxPointSize) else if (n >= m_nMaxPointSize)
str = str.Left(str.length() - size.length()) + str = str.Left(str.length() - size.length()) +
wxString::Format(wxT("%d"), m_nMaxPointSize); wxString::Format(wxT("%d"), m_nMaxPointSize);
} }
if (!ret.SetNativeFontInfoUserDesc(str)) if (!ret.SetNativeFontInfoUserDesc(str))
return wxNullFont; return wxNullFont;
return ret; return ret;
} }
void wxFontPickerCtrl::SetSelectedFont(const wxFont &f) void wxFontPickerCtrl::SetSelectedFont(const wxFont &f)
{ {
M_PICKER->SetSelectedFont(f); M_PICKER->SetSelectedFont(f);
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
} }
void wxFontPickerCtrl::UpdatePickerFromTextCtrl() void wxFontPickerCtrl::UpdatePickerFromTextCtrl()
{ {
wxASSERT(m_text); wxASSERT(m_text);
if (m_bIgnoreNextTextCtrlUpdate) if (m_bIgnoreNextTextCtrlUpdate)
{ {
// ignore this update // ignore this update
m_bIgnoreNextTextCtrlUpdate = false; m_bIgnoreNextTextCtrlUpdate = false;
return; return;
} }
// NB: we don't use the wxFont::wxFont(const wxString &) constructor // NB: we don't use the wxFont::wxFont(const wxString &) constructor
// since that constructor expects the native font description // since that constructor expects the native font description
// string returned by wxFont::GetNativeFontInfoDesc() and not // string returned by wxFont::GetNativeFontInfoDesc() and not
// the user-friendly one returned by wxFont::GetNativeFontInfoUserDesc() // the user-friendly one returned by wxFont::GetNativeFontInfoUserDesc()
wxFont f = String2Font(m_text->GetValue()); wxFont f = String2Font(m_text->GetValue());
if (!f.Ok()) if (!f.Ok())
return; // invalid user input return; // invalid user input
if (M_PICKER->GetSelectedFont() != f) if (M_PICKER->GetSelectedFont() != f)
{ {
M_PICKER->SetSelectedFont(f); M_PICKER->SetSelectedFont(f);
// fire an event // fire an event
wxFontPickerEvent event(this, GetId(), f); wxFontPickerEvent event(this, GetId(), f);
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
} }
void wxFontPickerCtrl::UpdateTextCtrlFromPicker() void wxFontPickerCtrl::UpdateTextCtrlFromPicker()
{ {
if (!m_text) if (!m_text)
return; // no textctrl to update return; // no textctrl to update
// NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED // NOTE: this SetValue() will generate an unwanted wxEVT_COMMAND_TEXT_UPDATED
// which will trigger a unneeded UpdateFromTextCtrl(); thus before using // which will trigger a unneeded UpdateFromTextCtrl(); thus before using
// SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag... // SetValue() we set the m_bIgnoreNextTextCtrlUpdate flag...
m_bIgnoreNextTextCtrlUpdate = true; m_bIgnoreNextTextCtrlUpdate = true;
m_text->SetValue(Font2String(M_PICKER->GetSelectedFont())); m_text->SetValue(Font2String(M_PICKER->GetSelectedFont()));
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxFontPickerCtrl - event handlers // wxFontPickerCtrl - event handlers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxFontPickerCtrl::OnFontChange(wxFontPickerEvent &ev) void wxFontPickerCtrl::OnFontChange(wxFontPickerEvent &ev)
{ {
UpdateTextCtrlFromPicker(); UpdateTextCtrlFromPicker();
// the wxFontPickerWidget sent us a colour-change notification. // the wxFontPickerWidget sent us a colour-change notification.
// forward this event to our parent // forward this event to our parent
wxFontPickerEvent event(this, GetId(), ev.GetFont()); wxFontPickerEvent event(this, GetId(), ev.GetFont());
GetEventHandler()->ProcessEvent(event); GetEventHandler()->ProcessEvent(event);
} }
#endif // wxUSE_FONTPICKERCTRL #endif // wxUSE_FONTPICKERCTRL

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,92 +1,92 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fs_filter.cpp // Name: src/common/fs_filter.cpp
// Purpose: wxFilter file system handler // Purpose: wxFilter file system handler
// Author: Mike Wetherell // Author: Mike Wetherell
// Copyright: (c) 2006 Mike Wetherell // Copyright: (c) 2006 Mike Wetherell
// CVS-ID: $Id: fs_filter.cpp 42514 2006-10-27 10:47:13Z MW $ // CVS-ID: $Id: fs_filter.cpp 42514 2006-10-27 10:47:13Z MW $
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FILESYSTEM #if wxUSE_FILESYSTEM
#include "wx/fs_filter.h" #include "wx/fs_filter.h"
#ifndef WXPRECOMP #ifndef WXPRECOMP
#endif #endif
#include "wx/ptr_scpd.h" #include "wx/ptr_scpd.h"
wxDEFINE_SCOPED_PTR_TYPE(wxFSFile) wxDEFINE_SCOPED_PTR_TYPE(wxFSFile)
wxDEFINE_SCOPED_PTR_TYPE(wxInputStream) wxDEFINE_SCOPED_PTR_TYPE(wxInputStream)
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
// wxFilterFSHandler // wxFilterFSHandler
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
bool wxFilterFSHandler::CanOpen(const wxString& location) bool wxFilterFSHandler::CanOpen(const wxString& location)
{ {
return wxFilterClassFactory::Find(GetProtocol(location)) != NULL; return wxFilterClassFactory::Find(GetProtocol(location)) != NULL;
} }
wxFSFile* wxFilterFSHandler::OpenFile( wxFSFile* wxFilterFSHandler::OpenFile(
wxFileSystem& fs, wxFileSystem& fs,
const wxString& location) const wxString& location)
{ {
wxString right = GetRightLocation(location); wxString right = GetRightLocation(location);
if (!right.empty()) if (!right.empty())
return NULL; return NULL;
wxString protocol = GetProtocol(location); wxString protocol = GetProtocol(location);
const wxFilterClassFactory *factory = wxFilterClassFactory::Find(protocol); const wxFilterClassFactory *factory = wxFilterClassFactory::Find(protocol);
if (!factory) if (!factory)
return NULL; return NULL;
wxString left = GetLeftLocation(location); wxString left = GetLeftLocation(location);
wxFSFilePtr leftFile(fs.OpenFile(left)); wxFSFilePtr leftFile(fs.OpenFile(left));
if (!leftFile.get()) if (!leftFile.get())
return NULL; return NULL;
wxInputStreamPtr leftStream(leftFile->DetachStream()); wxInputStreamPtr leftStream(leftFile->DetachStream());
if (!leftStream.get() || !leftStream->IsOk()) if (!leftStream.get() || !leftStream->IsOk())
return NULL; return NULL;
wxInputStreamPtr stream(factory->NewStream(leftStream.release())); wxInputStreamPtr stream(factory->NewStream(leftStream.release()));
// The way compressed streams are supposed to be served is e.g.: // The way compressed streams are supposed to be served is e.g.:
// Content-type: application/postscript // Content-type: application/postscript
// Content-encoding: gzip // Content-encoding: gzip
// So the mime type should be just the mime type of the lhs. However check // So the mime type should be just the mime type of the lhs. However check
// whether the mime type is that of this compression format (e.g. // whether the mime type is that of this compression format (e.g.
// application/gzip). If so pop any extension and try GetMimeTypeFromExt, // application/gzip). If so pop any extension and try GetMimeTypeFromExt,
// e.g. if it were '.ps.gz' pop the '.gz' and try looking up '.ps' // e.g. if it were '.ps.gz' pop the '.gz' and try looking up '.ps'
wxString mime = leftFile->GetMimeType(); wxString mime = leftFile->GetMimeType();
if (factory->CanHandle(mime, wxSTREAM_MIMETYPE)) if (factory->CanHandle(mime, wxSTREAM_MIMETYPE))
mime = GetMimeTypeFromExt(factory->PopExtension(left)); mime = GetMimeTypeFromExt(factory->PopExtension(left));
return new wxFSFile(stream.release(), return new wxFSFile(stream.release(),
left + wxT("#") + protocol + wxT(":") + right, left + wxT("#") + protocol + wxT(":") + right,
mime, mime,
GetAnchor(location) GetAnchor(location)
#if wxUSE_DATETIME #if wxUSE_DATETIME
, leftFile->GetModificationTime() , leftFile->GetModificationTime()
#endif // wxUSE_DATETIME #endif // wxUSE_DATETIME
); );
} }
wxString wxFilterFSHandler::FindFirst(const wxString& WXUNUSED(spec), int WXUNUSED(flags)) wxString wxFilterFSHandler::FindFirst(const wxString& WXUNUSED(spec), int WXUNUSED(flags))
{ {
return wxEmptyString; return wxEmptyString;
} }
wxString wxFilterFSHandler::FindNext() wxString wxFilterFSHandler::FindNext()
{ {
return wxEmptyString; return wxEmptyString;
} }
#endif //wxUSE_FILESYSTEM #endif //wxUSE_FILESYSTEM

View File

@ -1,167 +1,167 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fs_inet.cpp // Name: src/common/fs_inet.cpp
// Purpose: HTTP and FTP file system // Purpose: HTTP and FTP file system
// Author: Vaclav Slavik // Author: Vaclav Slavik
// Copyright: (c) 1999 Vaclav Slavik // Copyright: (c) 1999 Vaclav Slavik
// RCS-ID: $Id: fs_inet.cpp 41033 2006-09-06 13:49:42Z RR $ // RCS-ID: $Id: fs_inet.cpp 41033 2006-09-06 13:49:42Z RR $
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if !wxUSE_SOCKETS #if !wxUSE_SOCKETS
#undef wxUSE_FS_INET #undef wxUSE_FS_INET
#define wxUSE_FS_INET 0 #define wxUSE_FS_INET 0
#endif #endif
#if wxUSE_FILESYSTEM && wxUSE_FS_INET #if wxUSE_FILESYSTEM && wxUSE_FS_INET
#ifndef WXPRECOMP #ifndef WXPRECOMP
#include "wx/module.h" #include "wx/module.h"
#endif #endif
#include "wx/wfstream.h" #include "wx/wfstream.h"
#include "wx/url.h" #include "wx/url.h"
#include "wx/filesys.h" #include "wx/filesys.h"
#include "wx/fs_inet.h" #include "wx/fs_inet.h"
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Helper classes // Helper classes
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// This stream deletes the file when destroyed // This stream deletes the file when destroyed
class wxTemporaryFileInputStream : public wxFileInputStream class wxTemporaryFileInputStream : public wxFileInputStream
{ {
public: public:
wxTemporaryFileInputStream(const wxString& filename) : wxTemporaryFileInputStream(const wxString& filename) :
wxFileInputStream(filename), m_filename(filename) {} wxFileInputStream(filename), m_filename(filename) {}
virtual ~wxTemporaryFileInputStream() virtual ~wxTemporaryFileInputStream()
{ {
// NB: copied from wxFileInputStream dtor, we need to do it before // NB: copied from wxFileInputStream dtor, we need to do it before
// wxRemoveFile // wxRemoveFile
if (m_file_destroy) if (m_file_destroy)
{ {
delete m_file; delete m_file;
m_file_destroy = false; m_file_destroy = false;
} }
wxRemoveFile(m_filename); wxRemoveFile(m_filename);
} }
protected: protected:
wxString m_filename; wxString m_filename;
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxInternetFSHandler // wxInternetFSHandler
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
static wxString StripProtocolAnchor(const wxString& location) static wxString StripProtocolAnchor(const wxString& location)
{ {
wxString myloc(location.BeforeLast(wxT('#'))); wxString myloc(location.BeforeLast(wxT('#')));
if (myloc.empty()) myloc = location.AfterFirst(wxT(':')); if (myloc.empty()) myloc = location.AfterFirst(wxT(':'));
else myloc = myloc.AfterFirst(wxT(':')); else myloc = myloc.AfterFirst(wxT(':'));
// fix malformed url: // fix malformed url:
if (!myloc.Left(2).IsSameAs(wxT("//"))) if (!myloc.Left(2).IsSameAs(wxT("//")))
{ {
if (myloc.GetChar(0) != wxT('/')) myloc = wxT("//") + myloc; if (myloc.GetChar(0) != wxT('/')) myloc = wxT("//") + myloc;
else myloc = wxT("/") + myloc; else myloc = wxT("/") + myloc;
} }
if (myloc.Mid(2).Find(wxT('/')) == wxNOT_FOUND) myloc << wxT('/'); if (myloc.Mid(2).Find(wxT('/')) == wxNOT_FOUND) myloc << wxT('/');
return myloc; return myloc;
} }
bool wxInternetFSHandler::CanOpen(const wxString& location) bool wxInternetFSHandler::CanOpen(const wxString& location)
{ {
#if wxUSE_URL #if wxUSE_URL
wxString p = GetProtocol(location); wxString p = GetProtocol(location);
if ((p == wxT("http")) || (p == wxT("ftp"))) if ((p == wxT("http")) || (p == wxT("ftp")))
{ {
wxURL url(p + wxT(":") + StripProtocolAnchor(location)); wxURL url(p + wxT(":") + StripProtocolAnchor(location));
return (url.GetError() == wxURL_NOERR); return (url.GetError() == wxURL_NOERR);
} }
#endif #endif
return false; return false;
} }
wxFSFile* wxInternetFSHandler::OpenFile(wxFileSystem& WXUNUSED(fs), wxFSFile* wxInternetFSHandler::OpenFile(wxFileSystem& WXUNUSED(fs),
const wxString& location) const wxString& location)
{ {
#if !wxUSE_URL #if !wxUSE_URL
return NULL; return NULL;
#else #else
wxString right = wxString right =
GetProtocol(location) + wxT(":") + StripProtocolAnchor(location); GetProtocol(location) + wxT(":") + StripProtocolAnchor(location);
wxURL url(right); wxURL url(right);
if (url.GetError() == wxURL_NOERR) if (url.GetError() == wxURL_NOERR)
{ {
wxInputStream *s = url.GetInputStream(); wxInputStream *s = url.GetInputStream();
wxString content = url.GetProtocol().GetContentType(); wxString content = url.GetProtocol().GetContentType();
if (content == wxEmptyString) content = GetMimeTypeFromExt(location); if (content == wxEmptyString) content = GetMimeTypeFromExt(location);
if (s) if (s)
{ {
wxString tmpfile = wxString tmpfile =
wxFileName::CreateTempFileName(wxT("wxhtml")); wxFileName::CreateTempFileName(wxT("wxhtml"));
{ // now copy streams content to temporary file: { // now copy streams content to temporary file:
wxFileOutputStream sout(tmpfile); wxFileOutputStream sout(tmpfile);
s->Read(sout); s->Read(sout);
} }
delete s; delete s;
return new wxFSFile(new wxTemporaryFileInputStream(tmpfile), return new wxFSFile(new wxTemporaryFileInputStream(tmpfile),
right, right,
content, content,
GetAnchor(location) GetAnchor(location)
#if wxUSE_DATETIME #if wxUSE_DATETIME
, wxDateTime::Now() , wxDateTime::Now()
#endif // wxUSE_DATETIME #endif // wxUSE_DATETIME
); );
} }
} }
return (wxFSFile*) NULL; // incorrect URL return (wxFSFile*) NULL; // incorrect URL
#endif #endif
} }
class wxFileSystemInternetModule : public wxModule class wxFileSystemInternetModule : public wxModule
{ {
DECLARE_DYNAMIC_CLASS(wxFileSystemInternetModule) DECLARE_DYNAMIC_CLASS(wxFileSystemInternetModule)
public: public:
wxFileSystemInternetModule() : wxFileSystemInternetModule() :
wxModule(), wxModule(),
m_handler(NULL) m_handler(NULL)
{ {
} }
virtual bool OnInit() virtual bool OnInit()
{ {
m_handler = new wxInternetFSHandler; m_handler = new wxInternetFSHandler;
wxFileSystem::AddHandler(m_handler); wxFileSystem::AddHandler(m_handler);
return true; return true;
} }
virtual void OnExit() virtual void OnExit()
{ {
delete wxFileSystem::RemoveHandler(m_handler); delete wxFileSystem::RemoveHandler(m_handler);
} }
private: private:
wxFileSystemHandler* m_handler; wxFileSystemHandler* m_handler;
}; };
IMPLEMENT_DYNAMIC_CLASS(wxFileSystemInternetModule, wxModule) IMPLEMENT_DYNAMIC_CLASS(wxFileSystemInternetModule, wxModule)
#endif // wxUSE_FILESYSTEM && wxUSE_FS_INET #endif // wxUSE_FILESYSTEM && wxUSE_FS_INET

View File

@ -1,288 +1,288 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/fs_mem.cpp // Name: src/common/fs_mem.cpp
// Purpose: in-memory file system // Purpose: in-memory file system
// Author: Vaclav Slavik // Author: Vaclav Slavik
// RCS-ID: $Id: fs_mem.cpp 46522 2007-06-18 18:37:40Z VS $ // RCS-ID: $Id: fs_mem.cpp 46522 2007-06-18 18:37:40Z VS $
// Copyright: (c) 2000 Vaclav Slavik // Copyright: (c) 2000 Vaclav Slavik
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_FILESYSTEM && wxUSE_STREAMS #if wxUSE_FILESYSTEM && wxUSE_STREAMS
#include "wx/fs_mem.h" #include "wx/fs_mem.h"
#ifndef WXPRECOMP #ifndef WXPRECOMP
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/hash.h" #include "wx/hash.h"
#if wxUSE_GUI #if wxUSE_GUI
#include "wx/bitmap.h" #include "wx/bitmap.h"
#include "wx/image.h" #include "wx/image.h"
#endif // wxUSE_GUI #endif // wxUSE_GUI
#endif #endif
#include "wx/mstream.h" #include "wx/mstream.h"
class MemFSHashObj : public wxObject class MemFSHashObj : public wxObject
{ {
public: public:
MemFSHashObj(const void *data, size_t len, const wxString& mime) MemFSHashObj(const void *data, size_t len, const wxString& mime)
{ {
m_Data = new char[len]; m_Data = new char[len];
memcpy(m_Data, data, len); memcpy(m_Data, data, len);
m_Len = len; m_Len = len;
m_MimeType = mime; m_MimeType = mime;
InitTime(); InitTime();
} }
MemFSHashObj(const wxMemoryOutputStream& stream, const wxString& mime) MemFSHashObj(const wxMemoryOutputStream& stream, const wxString& mime)
{ {
m_Len = stream.GetSize(); m_Len = stream.GetSize();
m_Data = new char[m_Len]; m_Data = new char[m_Len];
stream.CopyTo(m_Data, m_Len); stream.CopyTo(m_Data, m_Len);
m_MimeType = mime; m_MimeType = mime;
InitTime(); InitTime();
} }
virtual ~MemFSHashObj() virtual ~MemFSHashObj()
{ {
delete[] m_Data; delete[] m_Data;
} }
char *m_Data; char *m_Data;
size_t m_Len; size_t m_Len;
wxString m_MimeType; wxString m_MimeType;
#if wxUSE_DATETIME #if wxUSE_DATETIME
wxDateTime m_Time; wxDateTime m_Time;
#endif // wxUSE_DATETIME #endif // wxUSE_DATETIME
DECLARE_NO_COPY_CLASS(MemFSHashObj) DECLARE_NO_COPY_CLASS(MemFSHashObj)
private: private:
void InitTime() void InitTime()
{ {
#if wxUSE_DATETIME #if wxUSE_DATETIME
m_Time = wxDateTime::Now(); m_Time = wxDateTime::Now();
#endif // wxUSE_DATETIME #endif // wxUSE_DATETIME
} }
}; };
#if wxUSE_BASE #if wxUSE_BASE
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
// wxMemoryFSHandler // wxMemoryFSHandler
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
wxHashTable *wxMemoryFSHandlerBase::m_Hash = NULL; wxHashTable *wxMemoryFSHandlerBase::m_Hash = NULL;
wxMemoryFSHandlerBase::wxMemoryFSHandlerBase() : wxFileSystemHandler() wxMemoryFSHandlerBase::wxMemoryFSHandlerBase() : wxFileSystemHandler()
{ {
} }
wxMemoryFSHandlerBase::~wxMemoryFSHandlerBase() wxMemoryFSHandlerBase::~wxMemoryFSHandlerBase()
{ {
// as only one copy of FS handler is supposed to exist, we may silently // as only one copy of FS handler is supposed to exist, we may silently
// delete static data here. (There is no way how to remove FS handler from // delete static data here. (There is no way how to remove FS handler from
// wxFileSystem other than releasing _all_ handlers.) // wxFileSystem other than releasing _all_ handlers.)
if (m_Hash) if (m_Hash)
{ {
WX_CLEAR_HASH_TABLE(*m_Hash); WX_CLEAR_HASH_TABLE(*m_Hash);
delete m_Hash; delete m_Hash;
m_Hash = NULL; m_Hash = NULL;
} }
} }
bool wxMemoryFSHandlerBase::CanOpen(const wxString& location) bool wxMemoryFSHandlerBase::CanOpen(const wxString& location)
{ {
wxString p = GetProtocol(location); wxString p = GetProtocol(location);
return (p == wxT("memory")); return (p == wxT("memory"));
} }
wxFSFile* wxMemoryFSHandlerBase::OpenFile(wxFileSystem& WXUNUSED(fs), const wxString& location) wxFSFile* wxMemoryFSHandlerBase::OpenFile(wxFileSystem& WXUNUSED(fs), const wxString& location)
{ {
if (m_Hash) if (m_Hash)
{ {
MemFSHashObj *obj = (MemFSHashObj*) m_Hash -> Get(GetRightLocation(location)); MemFSHashObj *obj = (MemFSHashObj*) m_Hash -> Get(GetRightLocation(location));
if (obj == NULL) if (obj == NULL)
{ {
return NULL; return NULL;
} }
else else
{ {
wxString mime = obj->m_MimeType; wxString mime = obj->m_MimeType;
if ( mime.empty() ) if ( mime.empty() )
mime = GetMimeTypeFromExt(location); mime = GetMimeTypeFromExt(location);
return new wxFSFile return new wxFSFile
( (
new wxMemoryInputStream(obj -> m_Data, obj -> m_Len), new wxMemoryInputStream(obj -> m_Data, obj -> m_Len),
location, location,
mime, mime,
GetAnchor(location) GetAnchor(location)
#if wxUSE_DATETIME #if wxUSE_DATETIME
, obj -> m_Time , obj -> m_Time
#endif // wxUSE_DATETIME #endif // wxUSE_DATETIME
); );
} }
} }
else return NULL; else return NULL;
} }
wxString wxMemoryFSHandlerBase::FindFirst(const wxString& WXUNUSED(spec), wxString wxMemoryFSHandlerBase::FindFirst(const wxString& WXUNUSED(spec),
int WXUNUSED(flags)) int WXUNUSED(flags))
{ {
wxFAIL_MSG(wxT("wxMemoryFSHandlerBase::FindFirst not implemented")); wxFAIL_MSG(wxT("wxMemoryFSHandlerBase::FindFirst not implemented"));
return wxEmptyString; return wxEmptyString;
} }
wxString wxMemoryFSHandlerBase::FindNext() wxString wxMemoryFSHandlerBase::FindNext()
{ {
wxFAIL_MSG(wxT("wxMemoryFSHandlerBase::FindNext not implemented")); wxFAIL_MSG(wxT("wxMemoryFSHandlerBase::FindNext not implemented"));
return wxEmptyString; return wxEmptyString;
} }
bool wxMemoryFSHandlerBase::CheckHash(const wxString& filename) bool wxMemoryFSHandlerBase::CheckHash(const wxString& filename)
{ {
if (m_Hash == NULL) if (m_Hash == NULL)
{ {
m_Hash = new wxHashTable(wxKEY_STRING); m_Hash = new wxHashTable(wxKEY_STRING);
} }
if (m_Hash -> Get(filename) != NULL) if (m_Hash -> Get(filename) != NULL)
{ {
wxString s; wxString s;
s.Printf(_("Memory VFS already contains file '%s'!"), filename.c_str()); s.Printf(_("Memory VFS already contains file '%s'!"), filename.c_str());
wxLogError(s); wxLogError(s);
return false; return false;
} }
else else
return true; return true;
} }
/*static*/ /*static*/
void wxMemoryFSHandlerBase::AddFileWithMimeType(const wxString& filename, void wxMemoryFSHandlerBase::AddFileWithMimeType(const wxString& filename,
const wxString& textdata, const wxString& textdata,
const wxString& mimetype) const wxString& mimetype)
{ {
AddFileWithMimeType(filename, AddFileWithMimeType(filename,
(const void*) textdata.mb_str(), textdata.length(), (const void*) textdata.mb_str(), textdata.length(),
mimetype); mimetype);
} }
/*static*/ /*static*/
void wxMemoryFSHandlerBase::AddFileWithMimeType(const wxString& filename, void wxMemoryFSHandlerBase::AddFileWithMimeType(const wxString& filename,
const void *binarydata, size_t size, const void *binarydata, size_t size,
const wxString& mimetype) const wxString& mimetype)
{ {
if (!CheckHash(filename)) return; if (!CheckHash(filename)) return;
m_Hash -> Put(filename, new MemFSHashObj(binarydata, size, mimetype)); m_Hash -> Put(filename, new MemFSHashObj(binarydata, size, mimetype));
} }
/*static*/ /*static*/
void wxMemoryFSHandlerBase::AddFile(const wxString& filename, void wxMemoryFSHandlerBase::AddFile(const wxString& filename,
const wxString& textdata) const wxString& textdata)
{ {
AddFileWithMimeType(filename, textdata, wxEmptyString); AddFileWithMimeType(filename, textdata, wxEmptyString);
} }
/*static*/ /*static*/
void wxMemoryFSHandlerBase::AddFile(const wxString& filename, void wxMemoryFSHandlerBase::AddFile(const wxString& filename,
const void *binarydata, size_t size) const void *binarydata, size_t size)
{ {
AddFileWithMimeType(filename, binarydata, size, wxEmptyString); AddFileWithMimeType(filename, binarydata, size, wxEmptyString);
} }
/*static*/ void wxMemoryFSHandlerBase::RemoveFile(const wxString& filename) /*static*/ void wxMemoryFSHandlerBase::RemoveFile(const wxString& filename)
{ {
if (m_Hash == NULL || if (m_Hash == NULL ||
m_Hash -> Get(filename) == NULL) m_Hash -> Get(filename) == NULL)
{ {
wxString s; wxString s;
s.Printf(_("Trying to remove file '%s' from memory VFS, but it is not loaded!"), filename.c_str()); s.Printf(_("Trying to remove file '%s' from memory VFS, but it is not loaded!"), filename.c_str());
wxLogError(s); wxLogError(s);
} }
else else
delete m_Hash -> Delete(filename); delete m_Hash -> Delete(filename);
} }
#endif // wxUSE_BASE #endif // wxUSE_BASE
#if wxUSE_GUI #if wxUSE_GUI
#if wxUSE_IMAGE #if wxUSE_IMAGE
/*static*/ void /*static*/ void
wxMemoryFSHandler::AddFile(const wxString& filename, wxMemoryFSHandler::AddFile(const wxString& filename,
const wxImage& image, const wxImage& image,
long type) long type)
{ {
if (!CheckHash(filename)) return; if (!CheckHash(filename)) return;
wxMemoryOutputStream mems; wxMemoryOutputStream mems;
if (image.Ok() && image.SaveFile(mems, (int)type)) if (image.Ok() && image.SaveFile(mems, (int)type))
{ {
m_Hash->Put m_Hash->Put
( (
filename, filename,
new MemFSHashObj new MemFSHashObj
( (
mems, mems,
wxImage::FindHandler(type)->GetMimeType() wxImage::FindHandler(type)->GetMimeType()
) )
); );
} }
else else
{ {
wxString s; wxString s;
s.Printf(_("Failed to store image '%s' to memory VFS!"), filename.c_str()); s.Printf(_("Failed to store image '%s' to memory VFS!"), filename.c_str());
wxPrintf(wxT("'%s'\n"), s.c_str()); wxPrintf(wxT("'%s'\n"), s.c_str());
wxLogError(s); wxLogError(s);
} }
} }
/*static*/ void /*static*/ void
wxMemoryFSHandler::AddFile(const wxString& filename, wxMemoryFSHandler::AddFile(const wxString& filename,
const wxBitmap& bitmap, const wxBitmap& bitmap,
long type) long type)
{ {
#if !defined(__WXMSW__) || wxUSE_WXDIB #if !defined(__WXMSW__) || wxUSE_WXDIB
wxImage img = bitmap.ConvertToImage(); wxImage img = bitmap.ConvertToImage();
AddFile(filename, img, type); AddFile(filename, img, type);
#endif #endif
} }
#endif // wxUSE_IMAGE #endif // wxUSE_IMAGE
#endif // wxUSE_GUI #endif // wxUSE_GUI
#endif // wxUSE_FILESYSTEM && wxUSE_FS_ZIP #endif // wxUSE_FILESYSTEM && wxUSE_FS_ZIP

File diff suppressed because it is too large Load Diff

View File

@ -1,156 +1,156 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Name: src/common/gaugecmn.cpp // Name: src/common/gaugecmn.cpp
// Purpose: wxGaugeBase: common to all ports methods of wxGauge // Purpose: wxGaugeBase: common to all ports methods of wxGauge
// Author: Vadim Zeitlin // Author: Vadim Zeitlin
// Modified by: // Modified by:
// Created: 20.02.01 // Created: 20.02.01
// RCS-ID: $Id: gaugecmn.cpp 41089 2006-09-09 13:36:54Z RR $ // RCS-ID: $Id: gaugecmn.cpp 41089 2006-09-09 13:36:54Z RR $
// Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
// License: wxWindows licence // License: wxWindows licence
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ============================================================================ // ============================================================================
// declarations // declarations
// ============================================================================ // ============================================================================
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// headers // headers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif //WX_PRECOMP #endif //WX_PRECOMP
#if wxUSE_GAUGE #if wxUSE_GAUGE
#include "wx/gauge.h" #include "wx/gauge.h"
const wxChar wxGaugeNameStr[] = wxT("gauge"); const wxChar wxGaugeNameStr[] = wxT("gauge");
// ============================================================================ // ============================================================================
// implementation // implementation
// ============================================================================ // ============================================================================
wxGaugeBase::~wxGaugeBase() wxGaugeBase::~wxGaugeBase()
{ {
// this destructor is required for Darwin // this destructor is required for Darwin
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxGauge creation // wxGauge creation
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
bool wxGaugeBase::Create(wxWindow *parent, bool wxGaugeBase::Create(wxWindow *parent,
wxWindowID id, wxWindowID id,
int range, int range,
const wxPoint& pos, const wxPoint& pos,
const wxSize& size, const wxSize& size,
long style, long style,
const wxValidator& validator, const wxValidator& validator,
const wxString& name) const wxString& name)
{ {
if ( !wxControl::Create(parent, id, pos, size, style, validator, name) ) if ( !wxControl::Create(parent, id, pos, size, style, validator, name) )
return false; return false;
SetName(name); SetName(name);
#if wxUSE_VALIDATORS #if wxUSE_VALIDATORS
SetValidator(validator); SetValidator(validator);
#endif // wxUSE_VALIDATORS #endif // wxUSE_VALIDATORS
SetRange(range); SetRange(range);
SetValue(0); SetValue(0);
#if wxGAUGE_EMULATE_INDETERMINATE_MODE #if wxGAUGE_EMULATE_INDETERMINATE_MODE
m_nDirection = wxRIGHT; m_nDirection = wxRIGHT;
#endif #endif
return true; return true;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxGauge determinate mode range/position // wxGauge determinate mode range/position
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxGaugeBase::SetRange(int range) void wxGaugeBase::SetRange(int range)
{ {
m_rangeMax = range; m_rangeMax = range;
} }
int wxGaugeBase::GetRange() const int wxGaugeBase::GetRange() const
{ {
return m_rangeMax; return m_rangeMax;
} }
void wxGaugeBase::SetValue(int pos) void wxGaugeBase::SetValue(int pos)
{ {
m_gaugePos = pos; m_gaugePos = pos;
} }
int wxGaugeBase::GetValue() const int wxGaugeBase::GetValue() const
{ {
return m_gaugePos; return m_gaugePos;
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxGauge indeterminate mode // wxGauge indeterminate mode
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxGaugeBase::Pulse() void wxGaugeBase::Pulse()
{ {
#if wxGAUGE_EMULATE_INDETERMINATE_MODE #if wxGAUGE_EMULATE_INDETERMINATE_MODE
// simulate indeterminate mode // simulate indeterminate mode
int curr = GetValue(), max = GetRange(); int curr = GetValue(), max = GetRange();
if (m_nDirection == wxRIGHT) if (m_nDirection == wxRIGHT)
{ {
if (curr < max) if (curr < max)
SetValue(curr + 1); SetValue(curr + 1);
else else
{ {
SetValue(max - 1); SetValue(max - 1);
m_nDirection = wxLEFT; m_nDirection = wxLEFT;
} }
} }
else else
{ {
if (curr > 0) if (curr > 0)
SetValue(curr - 1); SetValue(curr - 1);
else else
{ {
SetValue(1); SetValue(1);
m_nDirection = wxRIGHT; m_nDirection = wxRIGHT;
} }
} }
#endif #endif
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// wxGauge appearance params // wxGauge appearance params
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void wxGaugeBase::SetShadowWidth(int WXUNUSED(w)) void wxGaugeBase::SetShadowWidth(int WXUNUSED(w))
{ {
} }
int wxGaugeBase::GetShadowWidth() const int wxGaugeBase::GetShadowWidth() const
{ {
return 0; return 0;
} }
void wxGaugeBase::SetBezelFace(int WXUNUSED(w)) void wxGaugeBase::SetBezelFace(int WXUNUSED(w))
{ {
} }
int wxGaugeBase::GetBezelFace() const int wxGaugeBase::GetBezelFace() const
{ {
return 0; return 0;
} }
#endif // wxUSE_GAUGE #endif // wxUSE_GAUGE

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,364 +1,364 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/geometry.cpp // Name: src/common/geometry.cpp
// Purpose: Common Geometry Classes // Purpose: Common Geometry Classes
// Author: Stefan Csomor // Author: Stefan Csomor
// Modified by: // Modified by:
// Created: 08/05/99 // Created: 08/05/99
// RCS-ID: // RCS-ID:
// Copyright: (c) 1999 Stefan Csomor // Copyright: (c) 1999 Stefan Csomor
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_GEOMETRY #if wxUSE_GEOMETRY
#include "wx/geometry.h" #include "wx/geometry.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/log.h" #include "wx/log.h"
#endif #endif
#include <string.h> #include <string.h>
#include "wx/datstrm.h" #include "wx/datstrm.h"
// //
// wxPoint2D // wxPoint2D
// //
// //
// wxRect2D // wxRect2D
// //
// wxDouble version // wxDouble version
// for the following calculations always remember // for the following calculations always remember
// that the right and bottom edges are not part of a rect // that the right and bottom edges are not part of a rect
bool wxRect2DDouble::Intersects( const wxRect2DDouble &rect ) const bool wxRect2DDouble::Intersects( const wxRect2DDouble &rect ) const
{ {
wxDouble left,right,bottom,top; wxDouble left,right,bottom,top;
left = wxMax ( m_x , rect.m_x ); left = wxMax ( m_x , rect.m_x );
right = wxMin ( m_x+m_width, rect.m_x + rect.m_width ); right = wxMin ( m_x+m_width, rect.m_x + rect.m_width );
top = wxMax ( m_y , rect.m_y ); top = wxMax ( m_y , rect.m_y );
bottom = wxMin ( m_y+m_height, rect.m_y + rect.m_height ); bottom = wxMin ( m_y+m_height, rect.m_y + rect.m_height );
if ( left < right && top < bottom ) if ( left < right && top < bottom )
{ {
return true; return true;
} }
return false; return false;
} }
void wxRect2DDouble::Intersect( const wxRect2DDouble &src1 , const wxRect2DDouble &src2 , wxRect2DDouble *dest ) void wxRect2DDouble::Intersect( const wxRect2DDouble &src1 , const wxRect2DDouble &src2 , wxRect2DDouble *dest )
{ {
wxDouble left,right,bottom,top; wxDouble left,right,bottom,top;
left = wxMax ( src1.m_x , src2.m_x ); left = wxMax ( src1.m_x , src2.m_x );
right = wxMin ( src1.m_x+src1.m_width, src2.m_x + src2.m_width ); right = wxMin ( src1.m_x+src1.m_width, src2.m_x + src2.m_width );
top = wxMax ( src1.m_y , src2.m_y ); top = wxMax ( src1.m_y , src2.m_y );
bottom = wxMin ( src1.m_y+src1.m_height, src2.m_y + src2.m_height ); bottom = wxMin ( src1.m_y+src1.m_height, src2.m_y + src2.m_height );
if ( left < right && top < bottom ) if ( left < right && top < bottom )
{ {
dest->m_x = left; dest->m_x = left;
dest->m_y = top; dest->m_y = top;
dest->m_width = right - left; dest->m_width = right - left;
dest->m_height = bottom - top; dest->m_height = bottom - top;
} }
else else
{ {
dest->m_width = dest->m_height = 0; dest->m_width = dest->m_height = 0;
} }
} }
void wxRect2DDouble::Union( const wxRect2DDouble &src1 , const wxRect2DDouble &src2 , wxRect2DDouble *dest ) void wxRect2DDouble::Union( const wxRect2DDouble &src1 , const wxRect2DDouble &src2 , wxRect2DDouble *dest )
{ {
wxDouble left,right,bottom,top; wxDouble left,right,bottom,top;
left = wxMin ( src1.m_x , src2.m_x ); left = wxMin ( src1.m_x , src2.m_x );
right = wxMax ( src1.m_x+src1.m_width, src2.m_x + src2.m_width ); right = wxMax ( src1.m_x+src1.m_width, src2.m_x + src2.m_width );
top = wxMin ( src1.m_y , src2.m_y ); top = wxMin ( src1.m_y , src2.m_y );
bottom = wxMax ( src1.m_y+src1.m_height, src2.m_y + src2.m_height ); bottom = wxMax ( src1.m_y+src1.m_height, src2.m_y + src2.m_height );
dest->m_x = left; dest->m_x = left;
dest->m_y = top; dest->m_y = top;
dest->m_width = right - left; dest->m_width = right - left;
dest->m_height = bottom - top; dest->m_height = bottom - top;
} }
void wxRect2DDouble::Union( const wxPoint2DDouble &pt ) void wxRect2DDouble::Union( const wxPoint2DDouble &pt )
{ {
wxDouble x = pt.m_x; wxDouble x = pt.m_x;
wxDouble y = pt.m_y; wxDouble y = pt.m_y;
if ( x < m_x ) if ( x < m_x )
{ {
SetLeft( x ); SetLeft( x );
} }
else if ( x < m_x + m_width ) else if ( x < m_x + m_width )
{ {
// contained // contained
} }
else else
{ {
SetRight( x ); SetRight( x );
} }
if ( y < m_y ) if ( y < m_y )
{ {
SetTop( y ); SetTop( y );
} }
else if ( y < m_y + m_height ) else if ( y < m_y + m_height )
{ {
// contained // contained
} }
else else
{ {
SetBottom( y ); SetBottom( y );
} }
} }
void wxRect2DDouble::ConstrainTo( const wxRect2DDouble &rect ) void wxRect2DDouble::ConstrainTo( const wxRect2DDouble &rect )
{ {
if ( GetLeft() < rect.GetLeft() ) if ( GetLeft() < rect.GetLeft() )
SetLeft( rect.GetLeft() ); SetLeft( rect.GetLeft() );
if ( GetRight() > rect.GetRight() ) if ( GetRight() > rect.GetRight() )
SetRight( rect.GetRight() ); SetRight( rect.GetRight() );
if ( GetBottom() > rect.GetBottom() ) if ( GetBottom() > rect.GetBottom() )
SetBottom( rect.GetBottom() ); SetBottom( rect.GetBottom() );
if ( GetTop() < rect.GetTop() ) if ( GetTop() < rect.GetTop() )
SetTop( rect.GetTop() ); SetTop( rect.GetTop() );
} }
wxRect2DDouble& wxRect2DDouble::operator=( const wxRect2DDouble &r ) wxRect2DDouble& wxRect2DDouble::operator=( const wxRect2DDouble &r )
{ {
m_x = r.m_x; m_x = r.m_x;
m_y = r.m_y; m_y = r.m_y;
m_width = r.m_width; m_width = r.m_width;
m_height = r.m_height; m_height = r.m_height;
return *this; return *this;
} }
// integer version // integer version
// for the following calculations always remember // for the following calculations always remember
// that the right and bottom edges are not part of a rect // that the right and bottom edges are not part of a rect
// wxPoint2D // wxPoint2D
#if wxUSE_STREAMS #if wxUSE_STREAMS
void wxPoint2DInt::WriteTo( wxDataOutputStream &stream ) const void wxPoint2DInt::WriteTo( wxDataOutputStream &stream ) const
{ {
stream.Write32( m_x ); stream.Write32( m_x );
stream.Write32( m_y ); stream.Write32( m_y );
} }
void wxPoint2DInt::ReadFrom( wxDataInputStream &stream ) void wxPoint2DInt::ReadFrom( wxDataInputStream &stream )
{ {
m_x = stream.Read32(); m_x = stream.Read32();
m_y = stream.Read32(); m_y = stream.Read32();
} }
#endif // wxUSE_STREAMS #endif // wxUSE_STREAMS
wxDouble wxPoint2DInt::GetVectorAngle() const wxDouble wxPoint2DInt::GetVectorAngle() const
{ {
if ( m_x == 0 ) if ( m_x == 0 )
{ {
if ( m_y >= 0 ) if ( m_y >= 0 )
return 90; return 90;
else else
return 270; return 270;
} }
if ( m_y == 0 ) if ( m_y == 0 )
{ {
if ( m_x >= 0 ) if ( m_x >= 0 )
return 0; return 0;
else else
return 180; return 180;
} }
// casts needed for MIPSpro compiler under SGI // casts needed for MIPSpro compiler under SGI
wxDouble deg = atan2( (double)m_y , (double)m_x ) * 180 / M_PI; wxDouble deg = atan2( (double)m_y , (double)m_x ) * 180 / M_PI;
if ( deg < 0 ) if ( deg < 0 )
{ {
deg += 360; deg += 360;
} }
return deg; return deg;
} }
void wxPoint2DInt::SetVectorAngle( wxDouble degrees ) void wxPoint2DInt::SetVectorAngle( wxDouble degrees )
{ {
wxDouble length = GetVectorLength(); wxDouble length = GetVectorLength();
m_x = (int)(length * cos( degrees / 180 * M_PI )); m_x = (int)(length * cos( degrees / 180 * M_PI ));
m_y = (int)(length * sin( degrees / 180 * M_PI )); m_y = (int)(length * sin( degrees / 180 * M_PI ));
} }
wxDouble wxPoint2DDouble::GetVectorAngle() const wxDouble wxPoint2DDouble::GetVectorAngle() const
{ {
if ( wxIsNullDouble(m_x) ) if ( wxIsNullDouble(m_x) )
{ {
if ( m_y >= 0 ) if ( m_y >= 0 )
return 90; return 90;
else else
return 270; return 270;
} }
if ( wxIsNullDouble(m_y) ) if ( wxIsNullDouble(m_y) )
{ {
if ( m_x >= 0 ) if ( m_x >= 0 )
return 0; return 0;
else else
return 180; return 180;
} }
wxDouble deg = atan2( m_y , m_x ) * 180 / M_PI; wxDouble deg = atan2( m_y , m_x ) * 180 / M_PI;
if ( deg < 0 ) if ( deg < 0 )
{ {
deg += 360; deg += 360;
} }
return deg; return deg;
} }
void wxPoint2DDouble::SetVectorAngle( wxDouble degrees ) void wxPoint2DDouble::SetVectorAngle( wxDouble degrees )
{ {
wxDouble length = GetVectorLength(); wxDouble length = GetVectorLength();
m_x = length * cos( degrees / 180 * M_PI ); m_x = length * cos( degrees / 180 * M_PI );
m_y = length * sin( degrees / 180 * M_PI ); m_y = length * sin( degrees / 180 * M_PI );
} }
// wxRect2D // wxRect2D
bool wxRect2DInt::Intersects( const wxRect2DInt &rect ) const bool wxRect2DInt::Intersects( const wxRect2DInt &rect ) const
{ {
wxInt32 left,right,bottom,top; wxInt32 left,right,bottom,top;
left = wxMax ( m_x , rect.m_x ); left = wxMax ( m_x , rect.m_x );
right = wxMin ( m_x+m_width, rect.m_x + rect.m_width ); right = wxMin ( m_x+m_width, rect.m_x + rect.m_width );
top = wxMax ( m_y , rect.m_y ); top = wxMax ( m_y , rect.m_y );
bottom = wxMin ( m_y+m_height, rect.m_y + rect.m_height ); bottom = wxMin ( m_y+m_height, rect.m_y + rect.m_height );
if ( left < right && top < bottom ) if ( left < right && top < bottom )
{ {
return true; return true;
} }
return false; return false;
} }
void wxRect2DInt::Intersect( const wxRect2DInt &src1 , const wxRect2DInt &src2 , wxRect2DInt *dest ) void wxRect2DInt::Intersect( const wxRect2DInt &src1 , const wxRect2DInt &src2 , wxRect2DInt *dest )
{ {
wxInt32 left,right,bottom,top; wxInt32 left,right,bottom,top;
left = wxMax ( src1.m_x , src2.m_x ); left = wxMax ( src1.m_x , src2.m_x );
right = wxMin ( src1.m_x+src1.m_width, src2.m_x + src2.m_width ); right = wxMin ( src1.m_x+src1.m_width, src2.m_x + src2.m_width );
top = wxMax ( src1.m_y , src2.m_y ); top = wxMax ( src1.m_y , src2.m_y );
bottom = wxMin ( src1.m_y+src1.m_height, src2.m_y + src2.m_height ); bottom = wxMin ( src1.m_y+src1.m_height, src2.m_y + src2.m_height );
if ( left < right && top < bottom ) if ( left < right && top < bottom )
{ {
dest->m_x = left; dest->m_x = left;
dest->m_y = top; dest->m_y = top;
dest->m_width = right - left; dest->m_width = right - left;
dest->m_height = bottom - top; dest->m_height = bottom - top;
} }
else else
{ {
dest->m_width = dest->m_height = 0; dest->m_width = dest->m_height = 0;
} }
} }
void wxRect2DInt::Union( const wxRect2DInt &src1 , const wxRect2DInt &src2 , wxRect2DInt *dest ) void wxRect2DInt::Union( const wxRect2DInt &src1 , const wxRect2DInt &src2 , wxRect2DInt *dest )
{ {
wxInt32 left,right,bottom,top; wxInt32 left,right,bottom,top;
left = wxMin ( src1.m_x , src2.m_x ); left = wxMin ( src1.m_x , src2.m_x );
right = wxMax ( src1.m_x+src1.m_width, src2.m_x + src2.m_width ); right = wxMax ( src1.m_x+src1.m_width, src2.m_x + src2.m_width );
top = wxMin ( src1.m_y , src2.m_y ); top = wxMin ( src1.m_y , src2.m_y );
bottom = wxMax ( src1.m_y+src1.m_height, src2.m_y + src2.m_height ); bottom = wxMax ( src1.m_y+src1.m_height, src2.m_y + src2.m_height );
dest->m_x = left; dest->m_x = left;
dest->m_y = top; dest->m_y = top;
dest->m_width = right - left; dest->m_width = right - left;
dest->m_height = bottom - top; dest->m_height = bottom - top;
} }
void wxRect2DInt::Union( const wxPoint2DInt &pt ) void wxRect2DInt::Union( const wxPoint2DInt &pt )
{ {
wxInt32 x = pt.m_x; wxInt32 x = pt.m_x;
wxInt32 y = pt.m_y; wxInt32 y = pt.m_y;
if ( x < m_x ) if ( x < m_x )
{ {
SetLeft( x ); SetLeft( x );
} }
else if ( x < m_x + m_width ) else if ( x < m_x + m_width )
{ {
// contained // contained
} }
else else
{ {
SetRight( x ); SetRight( x );
} }
if ( y < m_y ) if ( y < m_y )
{ {
SetTop( y ); SetTop( y );
} }
else if ( y < m_y + m_height ) else if ( y < m_y + m_height )
{ {
// contained // contained
} }
else else
{ {
SetBottom( y ); SetBottom( y );
} }
} }
void wxRect2DInt::ConstrainTo( const wxRect2DInt &rect ) void wxRect2DInt::ConstrainTo( const wxRect2DInt &rect )
{ {
if ( GetLeft() < rect.GetLeft() ) if ( GetLeft() < rect.GetLeft() )
SetLeft( rect.GetLeft() ); SetLeft( rect.GetLeft() );
if ( GetRight() > rect.GetRight() ) if ( GetRight() > rect.GetRight() )
SetRight( rect.GetRight() ); SetRight( rect.GetRight() );
if ( GetBottom() > rect.GetBottom() ) if ( GetBottom() > rect.GetBottom() )
SetBottom( rect.GetBottom() ); SetBottom( rect.GetBottom() );
if ( GetTop() < rect.GetTop() ) if ( GetTop() < rect.GetTop() )
SetTop( rect.GetTop() ); SetTop( rect.GetTop() );
} }
wxRect2DInt& wxRect2DInt::operator=( const wxRect2DInt &r ) wxRect2DInt& wxRect2DInt::operator=( const wxRect2DInt &r )
{ {
m_x = r.m_x; m_x = r.m_x;
m_y = r.m_y; m_y = r.m_y;
m_width = r.m_width; m_width = r.m_width;
m_height = r.m_height; m_height = r.m_height;
return *this; return *this;
} }
#if wxUSE_STREAMS #if wxUSE_STREAMS
void wxRect2DInt::WriteTo( wxDataOutputStream &stream ) const void wxRect2DInt::WriteTo( wxDataOutputStream &stream ) const
{ {
stream.Write32( m_x ); stream.Write32( m_x );
stream.Write32( m_y ); stream.Write32( m_y );
stream.Write32( m_width ); stream.Write32( m_width );
stream.Write32( m_height ); stream.Write32( m_height );
} }
void wxRect2DInt::ReadFrom( wxDataInputStream &stream ) void wxRect2DInt::ReadFrom( wxDataInputStream &stream )
{ {
m_x = stream.Read32(); m_x = stream.Read32();
m_y = stream.Read32(); m_y = stream.Read32();
m_width = stream.Read32(); m_width = stream.Read32();
m_height = stream.Read32(); m_height = stream.Read32();
} }
#endif // wxUSE_STREAMS #endif // wxUSE_STREAMS
#endif // wxUSE_GEOMETRY #endif // wxUSE_GEOMETRY

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,152 +1,152 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/hashmap.cpp // Name: src/common/hashmap.cpp
// Purpose: wxHashMap implementation // Purpose: wxHashMap implementation
// Author: Mattia Barbon // Author: Mattia Barbon
// Modified by: // Modified by:
// Created: 29/01/2002 // Created: 29/01/2002
// RCS-ID: $Id: hashmap.cpp 39802 2006-06-20 10:24:07Z ABX $ // RCS-ID: $Id: hashmap.cpp 39802 2006-06-20 10:24:07Z ABX $
// Copyright: (c) Mattia Barbon // Copyright: (c) Mattia Barbon
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/hashmap.h" #include "wx/hashmap.h"
/* FYI: This is the "One-at-a-Time" algorithm by Bob Jenkins */ /* FYI: This is the "One-at-a-Time" algorithm by Bob Jenkins */
/* from requirements by Colin Plumb. */ /* from requirements by Colin Plumb. */
/* (http://burtleburtle.net/bob/hash/doobs.html) */ /* (http://burtleburtle.net/bob/hash/doobs.html) */
/* adapted from Perl sources ( hv.h ) */ /* adapted from Perl sources ( hv.h ) */
unsigned long wxStringHash::wxCharStringHash( const wxChar* k ) unsigned long wxStringHash::wxCharStringHash( const wxChar* k )
{ {
unsigned long hash = 0; unsigned long hash = 0;
while( *k ) while( *k )
{ {
hash += *k++; hash += *k++;
hash += (hash << 10); hash += (hash << 10);
hash ^= (hash >> 6); hash ^= (hash >> 6);
} }
hash += (hash << 3); hash += (hash << 3);
hash ^= (hash >> 11); hash ^= (hash >> 11);
return hash + (hash << 15); return hash + (hash << 15);
} }
#if wxUSE_UNICODE #if wxUSE_UNICODE
unsigned long wxStringHash::charStringHash( const char* k ) unsigned long wxStringHash::charStringHash( const char* k )
{ {
unsigned long hash = 0; unsigned long hash = 0;
while( *k ) while( *k )
{ {
hash += *k++; hash += *k++;
hash += (hash << 10); hash += (hash << 10);
hash ^= (hash >> 6); hash ^= (hash >> 6);
} }
hash += (hash << 3); hash += (hash << 3);
hash ^= (hash >> 11); hash ^= (hash >> 11);
return hash + (hash << 15); return hash + (hash << 15);
} }
#endif #endif
#if !wxUSE_STL || !defined(HAVE_STL_HASH_MAP) #if !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)
/* from SGI STL */ /* from SGI STL */
const unsigned long _wxHashTableBase2::ms_primes[prime_count] = const unsigned long _wxHashTableBase2::ms_primes[prime_count] =
{ {
7ul, 13ul, 29ul, 7ul, 13ul, 29ul,
53ul, 97ul, 193ul, 389ul, 769ul, 53ul, 97ul, 193ul, 389ul, 769ul,
1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 1543ul, 3079ul, 6151ul, 12289ul, 24593ul,
49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul,
1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul,
50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul,
1610612741ul, 3221225473ul, 4294967291ul 1610612741ul, 3221225473ul, 4294967291ul
}; };
unsigned long _wxHashTableBase2::GetNextPrime( unsigned long n ) unsigned long _wxHashTableBase2::GetNextPrime( unsigned long n )
{ {
const unsigned long* ptr = &ms_primes[0]; const unsigned long* ptr = &ms_primes[0];
for( size_t i = 0; i < prime_count; ++i, ++ptr ) for( size_t i = 0; i < prime_count; ++i, ++ptr )
{ {
if( n < *ptr ) if( n < *ptr )
return *ptr; return *ptr;
} }
/* someone might try to alloc a 2^32-element hash table */ /* someone might try to alloc a 2^32-element hash table */
wxFAIL_MSG( _T("hash table too big?") ); wxFAIL_MSG( _T("hash table too big?") );
/* quiet warning */ /* quiet warning */
return 0; return 0;
} }
unsigned long _wxHashTableBase2::GetPreviousPrime( unsigned long n ) unsigned long _wxHashTableBase2::GetPreviousPrime( unsigned long n )
{ {
const unsigned long* ptr = &ms_primes[prime_count - 1]; const unsigned long* ptr = &ms_primes[prime_count - 1];
for( size_t i = 0; i < prime_count; ++i, --ptr ) for( size_t i = 0; i < prime_count; ++i, --ptr )
{ {
if( n > *ptr ) if( n > *ptr )
return *ptr; return *ptr;
} }
/* quiet warning */ /* quiet warning */
return 1; return 1;
} }
void _wxHashTableBase2::DeleteNodes( size_t buckets, void _wxHashTableBase2::DeleteNodes( size_t buckets,
_wxHashTable_NodeBase** table, _wxHashTable_NodeBase** table,
NodeDtor dtor ) NodeDtor dtor )
{ {
size_t i; size_t i;
for( i = 0; i < buckets; ++i ) for( i = 0; i < buckets; ++i )
{ {
_wxHashTable_NodeBase* node = table[i]; _wxHashTable_NodeBase* node = table[i];
_wxHashTable_NodeBase* tmp; _wxHashTable_NodeBase* tmp;
while( node ) while( node )
{ {
tmp = node->m_nxt; tmp = node->m_nxt;
dtor( node ); dtor( node );
node = tmp; node = tmp;
} }
} }
memset( table, 0, buckets * sizeof(void*) ); memset( table, 0, buckets * sizeof(void*) );
} }
void _wxHashTableBase2::CopyHashTable( _wxHashTable_NodeBase** srcTable, void _wxHashTableBase2::CopyHashTable( _wxHashTable_NodeBase** srcTable,
size_t srcBuckets, size_t srcBuckets,
_wxHashTableBase2* dst, _wxHashTableBase2* dst,
_wxHashTable_NodeBase** dstTable, _wxHashTable_NodeBase** dstTable,
BucketFromNode func, ProcessNode proc ) BucketFromNode func, ProcessNode proc )
{ {
for( size_t i = 0; i < srcBuckets; ++i ) for( size_t i = 0; i < srcBuckets; ++i )
{ {
_wxHashTable_NodeBase* nextnode; _wxHashTable_NodeBase* nextnode;
for( _wxHashTable_NodeBase* node = srcTable[i]; node; node = nextnode ) for( _wxHashTable_NodeBase* node = srcTable[i]; node; node = nextnode )
{ {
size_t bucket = func( dst, node ); size_t bucket = func( dst, node );
nextnode = node->m_nxt; nextnode = node->m_nxt;
_wxHashTable_NodeBase* newnode = proc( node ); _wxHashTable_NodeBase* newnode = proc( node );
newnode->m_nxt = dstTable[bucket]; newnode->m_nxt = dstTable[bucket];
dstTable[bucket] = newnode; dstTable[bucket] = newnode;
} }
} }
} }
_wxHashTable_NodeBase* _wxHashTableBase2::DummyProcessNode(_wxHashTable_NodeBase* node) _wxHashTable_NodeBase* _wxHashTableBase2::DummyProcessNode(_wxHashTable_NodeBase* node)
{ {
return node; return node;
} }
#endif // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP) #endif // !wxUSE_STL || !defined(HAVE_STL_HASH_MAP)

View File

@ -1,28 +1,28 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/helpbase.cpp // Name: src/common/helpbase.cpp
// Purpose: Help system base classes // Purpose: Help system base classes
// Author: Julian Smart // Author: Julian Smart
// Modified by: // Modified by:
// Created: 04/01/98 // Created: 04/01/98
// RCS-ID: $Id: helpbase.cpp 38787 2006-04-18 07:24:35Z ABX $ // RCS-ID: $Id: helpbase.cpp 38787 2006-04-18 07:24:35Z ABX $
// Copyright: (c) Julian Smart // Copyright: (c) Julian Smart
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_HELP #if wxUSE_HELP
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#endif #endif
#include "wx/helpbase.h" #include "wx/helpbase.h"
IMPLEMENT_CLASS(wxHelpControllerBase, wxObject) IMPLEMENT_CLASS(wxHelpControllerBase, wxObject)
#endif // wxUSE_HELP #endif // wxUSE_HELP

View File

@ -1,422 +1,422 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/http.cpp // Name: src/common/http.cpp
// Purpose: HTTP protocol // Purpose: HTTP protocol
// Author: Guilhem Lavaux // Author: Guilhem Lavaux
// Modified by: Simo Virokannas (authentication, Dec 2005) // Modified by: Simo Virokannas (authentication, Dec 2005)
// Created: August 1997 // Created: August 1997
// RCS-ID: $Id: http.cpp 44660 2007-03-07 23:07:17Z VZ $ // RCS-ID: $Id: http.cpp 44660 2007-03-07 23:07:17Z VZ $
// Copyright: (c) 1997, 1998 Guilhem Lavaux // Copyright: (c) 1997, 1998 Guilhem Lavaux
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_PROTOCOL_HTTP #if wxUSE_PROTOCOL_HTTP
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/string.h" #include "wx/string.h"
#include "wx/app.h" #include "wx/app.h"
#endif #endif
#include "wx/tokenzr.h" #include "wx/tokenzr.h"
#include "wx/socket.h" #include "wx/socket.h"
#include "wx/protocol/protocol.h" #include "wx/protocol/protocol.h"
#include "wx/url.h" #include "wx/url.h"
#include "wx/protocol/http.h" #include "wx/protocol/http.h"
#include "wx/sckstrm.h" #include "wx/sckstrm.h"
IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol) IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true) IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true)
wxHTTP::wxHTTP() wxHTTP::wxHTTP()
: wxProtocol() : wxProtocol()
{ {
m_addr = NULL; m_addr = NULL;
m_read = false; m_read = false;
m_proxy_mode = false; m_proxy_mode = false;
m_post_buf = wxEmptyString; m_post_buf = wxEmptyString;
m_http_response = 0; m_http_response = 0;
SetNotify(wxSOCKET_LOST_FLAG); SetNotify(wxSOCKET_LOST_FLAG);
} }
wxHTTP::~wxHTTP() wxHTTP::~wxHTTP()
{ {
ClearHeaders(); ClearHeaders();
delete m_addr; delete m_addr;
} }
void wxHTTP::ClearHeaders() void wxHTTP::ClearHeaders()
{ {
m_headers.clear(); m_headers.clear();
} }
wxString wxHTTP::GetContentType() wxString wxHTTP::GetContentType()
{ {
return GetHeader(wxT("Content-Type")); return GetHeader(wxT("Content-Type"));
} }
void wxHTTP::SetProxyMode(bool on) void wxHTTP::SetProxyMode(bool on)
{ {
m_proxy_mode = on; m_proxy_mode = on;
} }
wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header) wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
{ {
wxHeaderIterator it = m_headers.begin(); wxHeaderIterator it = m_headers.begin();
for ( wxHeaderIterator en = m_headers.end(); it != en; ++it ) for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
{ {
if ( wxStricmp(it->first, header) == 0 ) if ( wxStricmp(it->first, header) == 0 )
break; break;
} }
return it; return it;
} }
wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
{ {
wxHeaderConstIterator it = m_headers.begin(); wxHeaderConstIterator it = m_headers.begin();
for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it ) for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
{ {
if ( wxStricmp(it->first, header) == 0 ) if ( wxStricmp(it->first, header) == 0 )
break; break;
} }
return it; return it;
} }
void wxHTTP::SetHeader(const wxString& header, const wxString& h_data) void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
{ {
if (m_read) { if (m_read) {
ClearHeaders(); ClearHeaders();
m_read = false; m_read = false;
} }
wxHeaderIterator it = FindHeader(header); wxHeaderIterator it = FindHeader(header);
if (it != m_headers.end()) if (it != m_headers.end())
it->second = h_data; it->second = h_data;
else else
m_headers[header] = h_data; m_headers[header] = h_data;
} }
wxString wxHTTP::GetHeader(const wxString& header) const wxString wxHTTP::GetHeader(const wxString& header) const
{ {
wxHeaderConstIterator it = FindHeader(header); wxHeaderConstIterator it = FindHeader(header);
return it == m_headers.end() ? wxGetEmptyString() : it->second; return it == m_headers.end() ? wxGetEmptyString() : it->second;
} }
wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const
{ {
static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
wxString buf; wxString buf;
wxString toencode; wxString toencode;
buf.Printf(wxT("Basic ")); buf.Printf(wxT("Basic "));
toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str()); toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str());
size_t len = toencode.length(); size_t len = toencode.length();
const wxChar *from = toencode.c_str(); const wxChar *from = toencode.c_str();
while (len >= 3) { // encode full blocks first while (len >= 3) { // encode full blocks first
buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]); buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]);
buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]); buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]);
from += 3; from += 3;
len -= 3; len -= 3;
} }
if (len > 0) { // pad the remaining characters if (len > 0) { // pad the remaining characters
buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]); buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]);
if (len == 1) { if (len == 1) {
buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]); buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]);
} else { } else {
buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]); buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]);
} }
buf << wxString::Format(wxT("=")); buf << wxString::Format(wxT("="));
} }
return buf; return buf;
} }
void wxHTTP::SetPostBuffer(const wxString& post_buf) void wxHTTP::SetPostBuffer(const wxString& post_buf)
{ {
m_post_buf = post_buf; m_post_buf = post_buf;
} }
void wxHTTP::SendHeaders() void wxHTTP::SendHeaders()
{ {
typedef wxStringToStringHashMap::iterator iterator; typedef wxStringToStringHashMap::iterator iterator;
wxString buf; wxString buf;
for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it ) for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
{ {
buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str()); buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
const wxWX2MBbuf cbuf = buf.mb_str(); const wxWX2MBbuf cbuf = buf.mb_str();
Write(cbuf, strlen(cbuf)); Write(cbuf, strlen(cbuf));
} }
} }
bool wxHTTP::ParseHeaders() bool wxHTTP::ParseHeaders()
{ {
wxString line; wxString line;
wxStringTokenizer tokenzr; wxStringTokenizer tokenzr;
ClearHeaders(); ClearHeaders();
m_read = true; m_read = true;
for ( ;; ) for ( ;; )
{ {
m_perr = ReadLine(this, line); m_perr = ReadLine(this, line);
if (m_perr != wxPROTO_NOERR) if (m_perr != wxPROTO_NOERR)
return false; return false;
if (line.length() == 0) if (line.length() == 0)
break; break;
wxString left_str = line.BeforeFirst(':'); wxString left_str = line.BeforeFirst(':');
m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both); m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
} }
return true; return true;
} }
bool wxHTTP::Connect(const wxString& host, unsigned short port) bool wxHTTP::Connect(const wxString& host, unsigned short port)
{ {
wxIPV4address *addr; wxIPV4address *addr;
if (m_addr) { if (m_addr) {
delete m_addr; delete m_addr;
m_addr = NULL; m_addr = NULL;
Close(); Close();
} }
m_addr = addr = new wxIPV4address(); m_addr = addr = new wxIPV4address();
if (!addr->Hostname(host)) { if (!addr->Hostname(host)) {
delete m_addr; delete m_addr;
m_addr = NULL; m_addr = NULL;
m_perr = wxPROTO_NETERR; m_perr = wxPROTO_NETERR;
return false; return false;
} }
if ( port ) if ( port )
addr->Service(port); addr->Service(port);
else if (!addr->Service(wxT("http"))) else if (!addr->Service(wxT("http")))
addr->Service(80); addr->Service(80);
SetHeader(wxT("Host"), host); SetHeader(wxT("Host"), host);
return true; return true;
} }
bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait)) bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait))
{ {
if (m_addr) { if (m_addr) {
delete m_addr; delete m_addr;
Close(); Close();
} }
m_addr = addr.Clone(); m_addr = addr.Clone();
wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address); wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
if (ipv4addr) if (ipv4addr)
SetHeader(wxT("Host"), ipv4addr->OrigHostname()); SetHeader(wxT("Host"), ipv4addr->OrigHostname());
return true; return true;
} }
bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req) bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
{ {
const wxChar *request; const wxChar *request;
switch (req) switch (req)
{ {
case wxHTTP_GET: case wxHTTP_GET:
request = wxT("GET"); request = wxT("GET");
break; break;
case wxHTTP_POST: case wxHTTP_POST:
request = wxT("POST"); request = wxT("POST");
if ( GetHeader( wxT("Content-Length") ).IsNull() ) if ( GetHeader( wxT("Content-Length") ).IsNull() )
SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) ); SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) );
break; break;
default: default:
return false; return false;
} }
m_http_response = 0; m_http_response = 0;
// If there is no User-Agent defined, define it. // If there is no User-Agent defined, define it.
if (GetHeader(wxT("User-Agent")).IsNull()) if (GetHeader(wxT("User-Agent")).IsNull())
SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x")); SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
// Send authentication information // Send authentication information
if (!m_username.empty() || !m_password.empty()) { if (!m_username.empty() || !m_password.empty()) {
SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password)); SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password));
} }
SaveState(); SaveState();
// we may use non blocking sockets only if we can dispatch events from them // we may use non blocking sockets only if we can dispatch events from them
SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
: wxSOCKET_BLOCK ); : wxSOCKET_BLOCK );
Notify(false); Notify(false);
wxString buf; wxString buf;
buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str()); buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
const wxWX2MBbuf pathbuf = wxConvLocal.cWX2MB(buf); const wxWX2MBbuf pathbuf = wxConvLocal.cWX2MB(buf);
Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf)); Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf));
SendHeaders(); SendHeaders();
Write("\r\n", 2); Write("\r\n", 2);
if ( req == wxHTTP_POST ) { if ( req == wxHTTP_POST ) {
Write(m_post_buf.mbc_str(), m_post_buf.Len()); Write(m_post_buf.mbc_str(), m_post_buf.Len());
m_post_buf = wxEmptyString; m_post_buf = wxEmptyString;
} }
wxString tmp_str; wxString tmp_str;
m_perr = ReadLine(this, tmp_str); m_perr = ReadLine(this, tmp_str);
if (m_perr != wxPROTO_NOERR) { if (m_perr != wxPROTO_NOERR) {
RestoreState(); RestoreState();
return false; return false;
} }
if (!tmp_str.Contains(wxT("HTTP/"))) { if (!tmp_str.Contains(wxT("HTTP/"))) {
// TODO: support HTTP v0.9 which can have no header. // TODO: support HTTP v0.9 which can have no header.
// FIXME: tmp_str is not put back in the in-queue of the socket. // FIXME: tmp_str is not put back in the in-queue of the socket.
SetHeader(wxT("Content-Length"), wxT("-1")); SetHeader(wxT("Content-Length"), wxT("-1"));
SetHeader(wxT("Content-Type"), wxT("none/none")); SetHeader(wxT("Content-Type"), wxT("none/none"));
RestoreState(); RestoreState();
return true; return true;
} }
wxStringTokenizer token(tmp_str,wxT(' ')); wxStringTokenizer token(tmp_str,wxT(' '));
wxString tmp_str2; wxString tmp_str2;
bool ret_value; bool ret_value;
token.NextToken(); token.NextToken();
tmp_str2 = token.NextToken(); tmp_str2 = token.NextToken();
m_http_response = wxAtoi(tmp_str2); m_http_response = wxAtoi(tmp_str2);
switch (tmp_str2[0u]) switch (tmp_str2[0u])
{ {
case wxT('1'): case wxT('1'):
/* INFORMATION / SUCCESS */ /* INFORMATION / SUCCESS */
break; break;
case wxT('2'): case wxT('2'):
/* SUCCESS */ /* SUCCESS */
break; break;
case wxT('3'): case wxT('3'):
/* REDIRECTION */ /* REDIRECTION */
break; break;
default: default:
m_perr = wxPROTO_NOFILE; m_perr = wxPROTO_NOFILE;
RestoreState(); RestoreState();
return false; return false;
} }
ret_value = ParseHeaders(); ret_value = ParseHeaders();
RestoreState(); RestoreState();
return ret_value; return ret_value;
} }
class wxHTTPStream : public wxSocketInputStream class wxHTTPStream : public wxSocketInputStream
{ {
public: public:
wxHTTP *m_http; wxHTTP *m_http;
size_t m_httpsize; size_t m_httpsize;
unsigned long m_read_bytes; unsigned long m_read_bytes;
wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {} wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
size_t GetSize() const { return m_httpsize; } size_t GetSize() const { return m_httpsize; }
virtual ~wxHTTPStream(void) { m_http->Abort(); } virtual ~wxHTTPStream(void) { m_http->Abort(); }
protected: protected:
size_t OnSysRead(void *buffer, size_t bufsize); size_t OnSysRead(void *buffer, size_t bufsize);
DECLARE_NO_COPY_CLASS(wxHTTPStream) DECLARE_NO_COPY_CLASS(wxHTTPStream)
}; };
size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize) size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
{ {
if (m_httpsize > 0 && m_read_bytes >= m_httpsize) if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
{ {
m_lasterror = wxSTREAM_EOF; m_lasterror = wxSTREAM_EOF;
return 0; return 0;
} }
size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize); size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
m_read_bytes += ret; m_read_bytes += ret;
if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR ) if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
{ {
// if m_httpsize is (size_t) -1 this means read until connection closed // if m_httpsize is (size_t) -1 this means read until connection closed
// which is equivalent to getting a READ_ERROR, for clients however this // which is equivalent to getting a READ_ERROR, for clients however this
// must be translated into EOF, as it is the expected way of signalling // must be translated into EOF, as it is the expected way of signalling
// end end of the content // end end of the content
m_lasterror = wxSTREAM_EOF ; m_lasterror = wxSTREAM_EOF ;
} }
return ret; return ret;
} }
bool wxHTTP::Abort(void) bool wxHTTP::Abort(void)
{ {
return wxSocketClient::Close(); return wxSocketClient::Close();
} }
wxInputStream *wxHTTP::GetInputStream(const wxString& path) wxInputStream *wxHTTP::GetInputStream(const wxString& path)
{ {
wxHTTPStream *inp_stream; wxHTTPStream *inp_stream;
wxString new_path; wxString new_path;
m_perr = wxPROTO_CONNERR; m_perr = wxPROTO_CONNERR;
if (!m_addr) if (!m_addr)
return NULL; return NULL;
// We set m_connected back to false so wxSocketBase will know what to do. // We set m_connected back to false so wxSocketBase will know what to do.
#ifdef __WXMAC__ #ifdef __WXMAC__
wxSocketClient::Connect(*m_addr , false ); wxSocketClient::Connect(*m_addr , false );
wxSocketClient::WaitOnConnect(10); wxSocketClient::WaitOnConnect(10);
if (!wxSocketClient::IsConnected()) if (!wxSocketClient::IsConnected())
return NULL; return NULL;
#else #else
if (!wxProtocol::Connect(*m_addr)) if (!wxProtocol::Connect(*m_addr))
return NULL; return NULL;
#endif #endif
if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST)) if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST))
return NULL; return NULL;
inp_stream = new wxHTTPStream(this); inp_stream = new wxHTTPStream(this);
if (!GetHeader(wxT("Content-Length")).empty()) if (!GetHeader(wxT("Content-Length")).empty())
inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length"))); inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
else else
inp_stream->m_httpsize = (size_t)-1; inp_stream->m_httpsize = (size_t)-1;
inp_stream->m_read_bytes = 0; inp_stream->m_read_bytes = 0;
Notify(false); Notify(false);
SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL); SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
return inp_stream; return inp_stream;
} }
#endif // wxUSE_PROTOCOL_HTTP #endif // wxUSE_PROTOCOL_HTTP

View File

@ -1,142 +1,142 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/iconbndl.cpp // Name: src/common/iconbndl.cpp
// Purpose: wxIconBundle // Purpose: wxIconBundle
// Author: Mattia Barbon // Author: Mattia Barbon
// Created: 23.03.2002 // Created: 23.03.2002
// RCS-ID: $Id: iconbndl.cpp 40654 2006-08-17 16:08:13Z VS $ // RCS-ID: $Id: iconbndl.cpp 40654 2006-08-17 16:08:13Z VS $
// Copyright: (c) Mattia barbon // Copyright: (c) Mattia barbon
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#include "wx/iconbndl.h" #include "wx/iconbndl.h"
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/settings.h" #include "wx/settings.h"
#include "wx/icon.h" #include "wx/icon.h"
#include "wx/log.h" #include "wx/log.h"
#include "wx/intl.h" #include "wx/intl.h"
#include "wx/bitmap.h" #include "wx/bitmap.h"
#include "wx/image.h" #include "wx/image.h"
#endif #endif
#include "wx/arrimpl.cpp" #include "wx/arrimpl.cpp"
WX_DEFINE_OBJARRAY(wxIconArray) WX_DEFINE_OBJARRAY(wxIconArray)
const wxIconBundle& wxIconBundle::operator =( const wxIconBundle& ic ) const wxIconBundle& wxIconBundle::operator =( const wxIconBundle& ic )
{ {
if( this == &ic ) return *this; if( this == &ic ) return *this;
size_t i, max = ic.m_icons.GetCount(); size_t i, max = ic.m_icons.GetCount();
DeleteIcons(); DeleteIcons();
for( i = 0; i < max; ++i ) for( i = 0; i < max; ++i )
m_icons.Add( ic.m_icons[i] ); m_icons.Add( ic.m_icons[i] );
return *this; return *this;
} }
void wxIconBundle::DeleteIcons() void wxIconBundle::DeleteIcons()
{ {
m_icons.Empty(); m_icons.Empty();
} }
#if wxUSE_IMAGE #if wxUSE_IMAGE
void wxIconBundle::AddIcon( const wxString& file, long type ) void wxIconBundle::AddIcon( const wxString& file, long type )
#else #else
void wxIconBundle::AddIcon( const wxString& WXUNUSED(file), long WXUNUSED(type) ) void wxIconBundle::AddIcon( const wxString& WXUNUSED(file), long WXUNUSED(type) )
#endif #endif
{ {
#if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB) #if wxUSE_IMAGE && (!defined(__WXMSW__) || wxUSE_WXDIB)
size_t count = wxImage::GetImageCount( file, type ); size_t count = wxImage::GetImageCount( file, type );
size_t i; size_t i;
wxImage image; wxImage image;
for( i = 0; i < count; ++i ) for( i = 0; i < count; ++i )
{ {
if( !image.LoadFile( file, type, i ) ) if( !image.LoadFile( file, type, i ) )
{ {
wxLogError( _("Failed to load image %d from file '%s'."), wxLogError( _("Failed to load image %d from file '%s'."),
i, file.c_str() ); i, file.c_str() );
continue; continue;
} }
wxIcon* tmp = new wxIcon(); wxIcon* tmp = new wxIcon();
tmp->CopyFromBitmap( wxBitmap( image ) ); tmp->CopyFromBitmap( wxBitmap( image ) );
AddIcon( *tmp ); AddIcon( *tmp );
delete tmp; delete tmp;
} }
#endif #endif
} }
const wxIcon& wxIconBundle::GetIcon( const wxSize& size ) const const wxIcon& wxIconBundle::GetIcon( const wxSize& size ) const
{ {
// temp. variable needed to fix Borland C++ 5.5.1 problem // temp. variable needed to fix Borland C++ 5.5.1 problem
// with passing a return value through two functions // with passing a return value through two functions
wxIcon *tmp; wxIcon *tmp;
size_t max = m_icons.GetCount(); size_t max = m_icons.GetCount();
// if we have one or no icon, we can return now without doing more work: // if we have one or no icon, we can return now without doing more work:
if ( max <= 1 ) if ( max <= 1 )
{ {
if ( max == 1 ) // fix for broken BCC if ( max == 1 ) // fix for broken BCC
tmp = &m_icons[0]; tmp = &m_icons[0];
else // max == 0 else // max == 0
tmp = &wxNullIcon; tmp = &wxNullIcon;
return *tmp; return *tmp;
} }
// there are more icons, find the best match: // there are more icons, find the best match:
wxCoord sysX = wxSystemSettings::GetMetric( wxSYS_ICON_X ), wxCoord sysX = wxSystemSettings::GetMetric( wxSYS_ICON_X ),
sysY = wxSystemSettings::GetMetric( wxSYS_ICON_Y ); sysY = wxSystemSettings::GetMetric( wxSYS_ICON_Y );
wxIcon *sysIcon = 0; wxIcon *sysIcon = 0;
for( size_t i = 0; i < max; i++ ) for( size_t i = 0; i < max; i++ )
{ {
if( !m_icons[i].Ok() ) if( !m_icons[i].Ok() )
continue; continue;
wxCoord sx = m_icons[i].GetWidth(), sy = m_icons[i].GetHeight(); wxCoord sx = m_icons[i].GetWidth(), sy = m_icons[i].GetHeight();
// requested size // requested size
if( sx == size.x && sy == size.y ) if( sx == size.x && sy == size.y )
{ {
tmp = &m_icons[i]; // fix for broken BCC tmp = &m_icons[i]; // fix for broken BCC
return *tmp; return *tmp;
} }
// keep track if there is a system-size icon // keep track if there is a system-size icon
if( sx == sysX && sy == sysY ) if( sx == sysX && sy == sysY )
sysIcon = &m_icons[i]; sysIcon = &m_icons[i];
} }
// return the system-sized icon if we've got one // return the system-sized icon if we've got one
if( sysIcon ) return *sysIcon; if( sysIcon ) return *sysIcon;
// we certainly have at least one icon thanks to the <=1 check above // we certainly have at least one icon thanks to the <=1 check above
tmp = &m_icons[0]; tmp = &m_icons[0];
return *tmp; return *tmp;
} }
void wxIconBundle::AddIcon( const wxIcon& icon ) void wxIconBundle::AddIcon( const wxIcon& icon )
{ {
size_t i, max = m_icons.GetCount(); size_t i, max = m_icons.GetCount();
for( i = 0; i < max; ++i ) for( i = 0; i < max; ++i )
{ {
wxIcon& tmp = m_icons[i]; wxIcon& tmp = m_icons[i];
if( tmp.Ok() && tmp.GetWidth() == icon.GetWidth() && if( tmp.Ok() && tmp.GetWidth() == icon.GetWidth() &&
tmp.GetHeight() == icon.GetHeight() ) tmp.GetHeight() == icon.GetHeight() )
{ {
tmp = icon; tmp = icon;
return; return;
} }
} }
m_icons.Add( icon ); m_icons.Add( icon );
} }

View File

@ -1,64 +1,64 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/imagall.cpp // Name: src/common/imagall.cpp
// Purpose: wxImage access all handler // Purpose: wxImage access all handler
// Author: Sylvain Bougnoux // Author: Sylvain Bougnoux
// RCS-ID: $Id: imagall.cpp 42644 2006-10-29 18:58:25Z VZ $ // RCS-ID: $Id: imagall.cpp 42644 2006-10-29 18:58:25Z VZ $
// Copyright: (c) Sylvain Bougnoux // Copyright: (c) Sylvain Bougnoux
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_IMAGE #if wxUSE_IMAGE
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/image.h" #include "wx/image.h"
#endif #endif
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// This function allows dynamic access to all image handlers compile within // This function allows dynamic access to all image handlers compile within
// the library. This function should be in a separate file as some compilers // the library. This function should be in a separate file as some compilers
// link against the whole object file as long as just one of is function is called! // link against the whole object file as long as just one of is function is called!
void wxInitAllImageHandlers() void wxInitAllImageHandlers()
{ {
#if wxUSE_LIBPNG #if wxUSE_LIBPNG
wxImage::AddHandler( new wxPNGHandler ); wxImage::AddHandler( new wxPNGHandler );
#endif #endif
#if wxUSE_LIBJPEG #if wxUSE_LIBJPEG
wxImage::AddHandler( new wxJPEGHandler ); wxImage::AddHandler( new wxJPEGHandler );
#endif #endif
#if wxUSE_LIBTIFF #if wxUSE_LIBTIFF
wxImage::AddHandler( new wxTIFFHandler ); wxImage::AddHandler( new wxTIFFHandler );
#endif #endif
#if wxUSE_GIF #if wxUSE_GIF
wxImage::AddHandler( new wxGIFHandler ); wxImage::AddHandler( new wxGIFHandler );
#endif #endif
#if wxUSE_PNM #if wxUSE_PNM
wxImage::AddHandler( new wxPNMHandler ); wxImage::AddHandler( new wxPNMHandler );
#endif #endif
#if wxUSE_PCX #if wxUSE_PCX
wxImage::AddHandler( new wxPCXHandler ); wxImage::AddHandler( new wxPCXHandler );
#endif #endif
#if wxUSE_IFF #if wxUSE_IFF
wxImage::AddHandler( new wxIFFHandler ); wxImage::AddHandler( new wxIFFHandler );
#endif #endif
#if wxUSE_ICO_CUR #if wxUSE_ICO_CUR
wxImage::AddHandler( new wxICOHandler ); wxImage::AddHandler( new wxICOHandler );
wxImage::AddHandler( new wxCURHandler ); wxImage::AddHandler( new wxCURHandler );
wxImage::AddHandler( new wxANIHandler ); wxImage::AddHandler( new wxANIHandler );
#endif #endif
#if wxUSE_TGA #if wxUSE_TGA
wxImage::AddHandler( new wxTGAHandler ); wxImage::AddHandler( new wxTGAHandler );
#endif #endif
#if wxUSE_XPM #if wxUSE_XPM
wxImage::AddHandler( new wxXPMHandler ); wxImage::AddHandler( new wxXPMHandler );
#endif #endif
} }
#endif // wxUSE_IMAGE #endif // wxUSE_IMAGE

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,308 +1,308 @@
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Name: src/common/imagfill.cpp // Name: src/common/imagfill.cpp
// Purpose: FloodFill for wxImage // Purpose: FloodFill for wxImage
// Author: Julian Smart // Author: Julian Smart
// RCS-ID: $Id: imagfill.cpp 39957 2006-07-03 19:02:54Z ABX $ // RCS-ID: $Id: imagfill.cpp 39957 2006-07-03 19:02:54Z ABX $
// Copyright: (c) Julian Smart // Copyright: (c) Julian Smart
// Licence: wxWindows licence // Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h". // For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h" #include "wx/wxprec.h"
#ifdef __BORLANDC__ #ifdef __BORLANDC__
#pragma hdrstop #pragma hdrstop
#endif #endif
#if wxUSE_IMAGE && !defined(__WXMSW__) #if wxUSE_IMAGE && !defined(__WXMSW__)
// we have no use for this code in wxMSW... // we have no use for this code in wxMSW...
#ifndef WX_PRECOMP #ifndef WX_PRECOMP
#include "wx/brush.h" #include "wx/brush.h"
#include "wx/dc.h" #include "wx/dc.h"
#include "wx/dcmemory.h" #include "wx/dcmemory.h"
#include "wx/image.h" #include "wx/image.h"
#endif #endif
// DoFloodFill // DoFloodFill
// Fills with the colour extracted from fillBrush, starting at x,y until either // Fills with the colour extracted from fillBrush, starting at x,y until either
// a color different from the start pixel is reached (wxFLOOD_SURFACE) // a color different from the start pixel is reached (wxFLOOD_SURFACE)
// or fill color is reached (wxFLOOD_BORDER) // or fill color is reached (wxFLOOD_BORDER)
static bool LINKAGEMODE MatchPixel(wxImage *img, int x, int y, int w, int h, const wxColour& c) static bool LINKAGEMODE MatchPixel(wxImage *img, int x, int y, int w, int h, const wxColour& c)
{ {
if ((x<0)||(x>=w)||(y<0)||(y>=h)) return false; if ((x<0)||(x>=w)||(y<0)||(y>=h)) return false;
unsigned char r = img->GetRed(x,y); unsigned char r = img->GetRed(x,y);
unsigned char g = img->GetGreen(x,y); unsigned char g = img->GetGreen(x,y);
unsigned char b = img->GetBlue(x,y); unsigned char b = img->GetBlue(x,y);
return c.Red() == r && c.Green() == g && c.Blue() == b ; return c.Red() == r && c.Green() == g && c.Blue() == b ;
} }
static bool LINKAGEMODE MatchBoundaryPixel(wxImage *img, int x, int y, int w, int h, const wxColour & fill, const wxColour& bound) static bool LINKAGEMODE MatchBoundaryPixel(wxImage *img, int x, int y, int w, int h, const wxColour & fill, const wxColour& bound)
{ {
if ((x<0)||(x>=w)||(y<0)||(y>=h)) return true; if ((x<0)||(x>=w)||(y<0)||(y>=h)) return true;
unsigned char r = img->GetRed(x,y); unsigned char r = img->GetRed(x,y);
unsigned char g = img->GetGreen(x,y); unsigned char g = img->GetGreen(x,y);
unsigned char b = img->GetBlue(x,y); unsigned char b = img->GetBlue(x,y);
if ( fill.Red() == r && fill.Green() == g && fill.Blue() == b ) if ( fill.Red() == r && fill.Green() == g && fill.Blue() == b )
return true; return true;
if ( bound.Red() == r && bound.Green() == g && bound.Blue() == b ) if ( bound.Red() == r && bound.Green() == g && bound.Blue() == b )
return true; return true;
return false; return false;
} }
static void LINKAGEMODE static void LINKAGEMODE
wxImageFloodFill(wxImage *image, wxImageFloodFill(wxImage *image,
wxCoord x, wxCoord y, const wxBrush & fillBrush, wxCoord x, wxCoord y, const wxBrush & fillBrush,
const wxColour& testColour, int style, const wxColour& testColour, int style,
int WXUNUSED(LogicalFunction)) int WXUNUSED(LogicalFunction))
{ {
/* A diamond flood-fill using a circular queue system. /* A diamond flood-fill using a circular queue system.
Each pixel surrounding the current pixel is added to Each pixel surrounding the current pixel is added to
the queue if it meets the criteria, then is retrieved in the queue if it meets the criteria, then is retrieved in
its turn. Code originally based on http://www.drawit.co.nz/Developers.htm, its turn. Code originally based on http://www.drawit.co.nz/Developers.htm,
with explicit permission to use this for wxWidgets granted by Andrew Empson with explicit permission to use this for wxWidgets granted by Andrew Empson
(no copyright claimed) (no copyright claimed)
*/ */
int width = image->GetWidth(); int width = image->GetWidth();
int height = image->GetHeight(); int height = image->GetHeight();
//Draw using a pen made from the current brush colour //Draw using a pen made from the current brush colour
//Potentially allows us to use patterned flood fills in future code //Potentially allows us to use patterned flood fills in future code
wxColour fillColour = fillBrush.GetColour(); wxColour fillColour = fillBrush.GetColour();
unsigned char r = fillColour.Red(); unsigned char r = fillColour.Red();
unsigned char g = fillColour.Green(); unsigned char g = fillColour.Green();
unsigned char b = fillColour.Blue(); unsigned char b = fillColour.Blue();
//initial test : //initial test :
if (style == wxFLOOD_SURFACE) if (style == wxFLOOD_SURFACE)
{ {
//if wxFLOOD_SURFACE, if fill colour is same as required, we don't do anything //if wxFLOOD_SURFACE, if fill colour is same as required, we don't do anything
if ( image->GetRed(x,y) != r if ( image->GetRed(x,y) != r
|| image->GetGreen(x,y) != g || image->GetGreen(x,y) != g
|| image->GetBlue (x,y) != b ) || image->GetBlue (x,y) != b )
{ {
//prepare memory for queue //prepare memory for queue
//queue save, start, read //queue save, start, read
size_t *qs, *qst, *qr; size_t *qs, *qst, *qr;
//queue size (physical) //queue size (physical)
long qSz= height * width * 2; long qSz= height * width * 2;
qst = new size_t [qSz]; qst = new size_t [qSz];
//temporary x and y locations //temporary x and y locations
int xt, yt; int xt, yt;
for (int i=0; i < qSz; i++) for (int i=0; i < qSz; i++)
qst[i] = 0; qst[i] = 0;
// start queue // start queue
qs=qr=qst; qs=qr=qst;
*qs=xt=x; *qs=xt=x;
qs++; qs++;
*qs=yt=y; *qs=yt=y;
qs++; qs++;
image->SetRGB(xt,yt,r,g,b); image->SetRGB(xt,yt,r,g,b);
//Main queue loop //Main queue loop
while(qr!=qs) while(qr!=qs)
{ {
//Add new members to queue //Add new members to queue
//Above current pixel //Above current pixel
if(MatchPixel(image,xt,yt-1,width,height,testColour)) if(MatchPixel(image,xt,yt-1,width,height,testColour))
{ {
*qs=xt; *qs=xt;
qs++; qs++;
*qs=yt-1; *qs=yt-1;
qs++; qs++;
image->SetRGB(xt,yt-1,r,g,b); image->SetRGB(xt,yt-1,r,g,b);
//Loop back to beginning of queue //Loop back to beginning of queue
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Below current pixel //Below current pixel
if(MatchPixel(image,xt,yt+1,width,height,testColour)) if(MatchPixel(image,xt,yt+1,width,height,testColour))
{ {
*qs=xt; *qs=xt;
qs++; qs++;
*qs=yt+1; *qs=yt+1;
qs++; qs++;
image->SetRGB(xt,yt+1,r,g,b); image->SetRGB(xt,yt+1,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Left of current pixel //Left of current pixel
if(MatchPixel(image,xt-1,yt,width,height,testColour)) if(MatchPixel(image,xt-1,yt,width,height,testColour))
{ {
*qs=xt-1; *qs=xt-1;
qs++; qs++;
*qs=yt; *qs=yt;
qs++; qs++;
image->SetRGB(xt-1,yt,r,g,b); image->SetRGB(xt-1,yt,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Right of current pixel //Right of current pixel
if(MatchPixel(image,xt+1,yt,width,height,testColour)) if(MatchPixel(image,xt+1,yt,width,height,testColour))
{ {
*qs=xt+1; *qs=xt+1;
qs++; qs++;
*qs=yt; *qs=yt;
qs++; qs++;
image->SetRGB(xt+1,yt,r,g,b); image->SetRGB(xt+1,yt,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Retrieve current queue member //Retrieve current queue member
qr+=2; qr+=2;
//Loop back to the beginning //Loop back to the beginning
if(qr>=(qst+qSz)) qr=qst; if(qr>=(qst+qSz)) qr=qst;
xt=*qr; xt=*qr;
yt=*(qr+1); yt=*(qr+1);
//Go Back to beginning of loop //Go Back to beginning of loop
} }
delete[] qst; delete[] qst;
} }
} }
else else
{ {
//style is wxFLOOD_BORDER //style is wxFLOOD_BORDER
// fill up to testColor border - if already testColour don't do anything // fill up to testColor border - if already testColour don't do anything
if ( image->GetRed(x,y) != testColour.Red() if ( image->GetRed(x,y) != testColour.Red()
|| image->GetGreen(x,y) != testColour.Green() || image->GetGreen(x,y) != testColour.Green()
|| image->GetBlue(x,y) != testColour.Blue() ) || image->GetBlue(x,y) != testColour.Blue() )
{ {
//prepare memory for queue //prepare memory for queue
//queue save, start, read //queue save, start, read
size_t *qs, *qst, *qr; size_t *qs, *qst, *qr;
//queue size (physical) //queue size (physical)
long qSz= height * width * 2; long qSz= height * width * 2;
qst = new size_t [qSz]; qst = new size_t [qSz];
//temporary x and y locations //temporary x and y locations
int xt, yt; int xt, yt;
for (int i=0; i < qSz; i++) for (int i=0; i < qSz; i++)
qst[i] = 0; qst[i] = 0;
// start queue // start queue
qs=qr=qst; qs=qr=qst;
*qs=xt=x; *qs=xt=x;
qs++; qs++;
*qs=yt=y; *qs=yt=y;
qs++; qs++;
image->SetRGB(xt,yt,r,g,b); image->SetRGB(xt,yt,r,g,b);
//Main queue loop //Main queue loop
while (qr!=qs) while (qr!=qs)
{ {
//Add new members to queue //Add new members to queue
//Above current pixel //Above current pixel
if(!MatchBoundaryPixel(image,xt,yt-1,width,height,fillColour,testColour)) if(!MatchBoundaryPixel(image,xt,yt-1,width,height,fillColour,testColour))
{ {
*qs=xt; *qs=xt;
qs++; qs++;
*qs=yt-1; *qs=yt-1;
qs++; qs++;
image->SetRGB(xt,yt-1,r,g,b); image->SetRGB(xt,yt-1,r,g,b);
//Loop back to beginning of queue //Loop back to beginning of queue
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Below current pixel //Below current pixel
if(!MatchBoundaryPixel(image,xt,yt+1,width,height,fillColour,testColour)) if(!MatchBoundaryPixel(image,xt,yt+1,width,height,fillColour,testColour))
{ {
*qs=xt; *qs=xt;
qs++; qs++;
*qs=yt+1; *qs=yt+1;
qs++; qs++;
image->SetRGB(xt,yt+1,r,g,b); image->SetRGB(xt,yt+1,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Left of current pixel //Left of current pixel
if(!MatchBoundaryPixel(image,xt-1,yt,width,height,fillColour,testColour)) if(!MatchBoundaryPixel(image,xt-1,yt,width,height,fillColour,testColour))
{ {
*qs=xt-1; *qs=xt-1;
qs++; qs++;
*qs=yt; *qs=yt;
qs++; qs++;
image->SetRGB(xt-1,yt,r,g,b); image->SetRGB(xt-1,yt,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Right of current pixel //Right of current pixel
if(!MatchBoundaryPixel(image,xt+1,yt,width,height,fillColour,testColour)) if(!MatchBoundaryPixel(image,xt+1,yt,width,height,fillColour,testColour))
{ {
*qs=xt+1; *qs=xt+1;
qs++; qs++;
*qs=yt; *qs=yt;
qs++; qs++;
image->SetRGB(xt+1,yt,r,g,b); image->SetRGB(xt+1,yt,r,g,b);
if(qs>=(qst+qSz)) qs=qst; if(qs>=(qst+qSz)) qs=qst;
} }
//Retrieve current queue member //Retrieve current queue member
qr+=2; qr+=2;
//Loop back to the beginning //Loop back to the beginning
if(qr>=(qst+qSz)) qr=qst; if(qr>=(qst+qSz)) qr=qst;
xt=*qr; xt=*qr;
yt=*(qr+1); yt=*(qr+1);
//Go Back to beginning of loop //Go Back to beginning of loop
} }
delete[] qst; delete[] qst;
} }
} }
//all done, //all done,
} }
bool wxDoFloodFill(wxDC *dc, wxCoord x, wxCoord y, bool wxDoFloodFill(wxDC *dc, wxCoord x, wxCoord y,
const wxColour& col, int style) const wxColour& col, int style)
{ {
if (dc->GetBrush().GetStyle() == wxTRANSPARENT) if (dc->GetBrush().GetStyle() == wxTRANSPARENT)
return true; return true;
int height = 0; int height = 0;
int width = 0; int width = 0;
dc->GetSize(&width, &height); dc->GetSize(&width, &height);
//it would be nice to fail if we don't get a sensible size... //it would be nice to fail if we don't get a sensible size...
wxCHECK_MSG(width >= 1 && height >= 1, false, wxCHECK_MSG(width >= 1 && height >= 1, false,
wxT("In FloodFill, dc.GetSize routine failed, method not supported by this DC")); wxT("In FloodFill, dc.GetSize routine failed, method not supported by this DC"));
//this is much faster than doing the individual pixels //this is much faster than doing the individual pixels
wxMemoryDC memdc; wxMemoryDC memdc;
wxBitmap bitmap(width, height); wxBitmap bitmap(width, height);
memdc.SelectObject(bitmap); memdc.SelectObject(bitmap);
memdc.Blit(0, 0, width, height, dc, 0, 0); memdc.Blit(0, 0, width, height, dc, 0, 0);
memdc.SelectObject(wxNullBitmap); memdc.SelectObject(wxNullBitmap);
wxImage image = bitmap.ConvertToImage(); wxImage image = bitmap.ConvertToImage();
wxImageFloodFill(&image, x,y, dc->GetBrush(), col, style, wxImageFloodFill(&image, x,y, dc->GetBrush(), col, style,
dc->GetLogicalFunction()); dc->GetLogicalFunction());
bitmap = wxBitmap(image); bitmap = wxBitmap(image);
memdc.SelectObject(bitmap); memdc.SelectObject(bitmap);
dc->Blit(0, 0, width, height, &memdc, 0, 0); dc->Blit(0, 0, width, height, &memdc, 0, 0);
memdc.SelectObject(wxNullBitmap); memdc.SelectObject(wxNullBitmap);
return true; return true;
} }
#endif // wxUSE_IMAGE #endif // wxUSE_IMAGE

Some files were not shown because too many files have changed in this diff Show More