Fix for libraries being compiled unconditionally
[amule.git] / src / OtherFunctions.h
blob0122dbf4e188d62319f25f5c778db276bf7d7d47
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #ifndef OTHERFUNCTIONS_H
27 #define OTHERFUNCTIONS_H
29 #include <wx/intl.h> // Needed for wxLANGUAGE_ constants
31 #include "Types.h" // Needed for uint16, uint32 and uint64
33 #include <algorithm> // Needed for std::for_each // Do_not_auto_remove (mingw-gcc-3.4.5)
36 class CPath;
39 /**
40 * Helper function.
42 * @param ArgA The base value.
43 * @param ArgB The value to compare ArgA against.
44 * @return See below.
46 * Use this function to safely compare two arguments of a type that supports
47 * the "<" operator. It works like strcmp and returns a negative value if ArgA
48 * is less than ArgB, zero if ArgA is equal to ArgB and a positive value if
49 * ArgA is greater than ArgB.
51 template <class TYPE>
52 int CmpAny(const TYPE& ArgA, const TYPE& ArgB)
54 if ( ArgA < ArgB ) {
55 return -1;
56 } else if ( ArgB < ArgA ) {
57 return 1;
58 } else {
59 return 0;
63 //! Overloaded version of CmpAny for use with wxStrings.
64 inline int CmpAny(const wxString& ArgA, const wxString& ArgB)
66 if (ArgA.IsEmpty() && !ArgB.IsEmpty()) {
67 return -1;
68 } else if (!ArgA.IsEmpty() && ArgB.IsEmpty()) {
69 return 1;
70 } else if (ArgA.IsEmpty() && ArgB.IsEmpty()) {
71 return 0;
72 } else {
73 return ArgA.CmpNoCase( ArgB );
77 //! Overloaded version of CmpAny for use with C-Strings (Unicoded).
78 inline int CmpAny(const wxChar* ArgA, const wxChar* ArgB)
80 return CmpAny(wxString( ArgA ), wxString( ArgB ));
84 /**
85 * Removes the first instance of a value from a STL-like list: list, vector or deque.
87 * @param list The list to manipulate.
88 * @param item The value to search for and remove.
89 * @return The number of instances removed.
91 template <typename LIST, typename ITEM>
92 unsigned int EraseFirstValue( LIST& list, const ITEM& item )
94 typename LIST::iterator it = list.begin();
96 for (; it != list.end(); ++it) {
97 if (*it == item) {
98 list.erase(it);
100 return true;
104 return false;
109 * Removes all instances of a value from a STL-like list: list, vector or deque.
111 * @param list The list to manipulate.
112 * @param item The value to search for and remove.
113 * @return The number of instances removed.
115 template <typename LIST, typename ITEM>
116 unsigned int EraseValue( LIST& list, const ITEM& item )
118 typename LIST::iterator it = list.begin();
119 unsigned int count = 0;
121 for ( ; it != list.end(); ) {
122 if ( *it == item ) {
123 it = list.erase( it );
124 count++;
125 } else {
126 ++it;
130 return count;
134 //! Used by DeleteContents
135 struct SDoDelete
137 // Used for lists, vectors, deques, etc.
138 template <typename TYPE>
139 void operator()(TYPE* ptr) {
140 delete ptr;
143 // Used for maps, hashmaps, rangemaps, etc.
144 template <typename FIRST, typename SECOND>
145 void operator()(const std::pair<FIRST, SECOND>& pair) {
146 delete pair.second;
151 /** Frees the contents of a list or map like stl container, clearing it afterwards. */
152 template <typename STL_CONTAINER>
153 void DeleteContents(STL_CONTAINER& container)
155 // Ensure that the actual container wont contain dangling pointers during
156 // this operation, to ensure that the destructors cant access them.
157 STL_CONTAINER copy;
159 std::swap(copy, container);
160 std::for_each(copy.begin(), copy.end(), SDoDelete());
165 * Copies elements from the range [first, first + n) to the range [result, result + n).
167 template <class InputIterator, class OutputIterator>
168 OutputIterator STLCopy_n(InputIterator first, size_t n, OutputIterator result)
170 return std::copy(first, first + n, result);
175 * Returns a description of the version of aMule being used.
177 * @return A detailed description of the aMule version, including wx information.
179 * Use this rather than just using the VERSION or CURRENT_VERSION_LONG
180 * constants, when displaying information to the user. The purpose is to
181 * help with debugging.
183 wxString GetMuleVersion();
187 * Helperfunction for accessing a child of the calling widget.
189 * @param IdOrName The ID or the Name of the widget to find.
190 * @param type The widget-type to cast the found widget to.
192 * Use this function as a replacement for the following constructs:
193 * - wxStaticCast( FindWindow( <IdOrName> ), <type> )
194 * - (<type>*)FindWindow( <IdOrName> )
196 * It has the advantage of validating the cast in debug builds and being much
197 * shorter than than manually typing wxStaticCast + FindWindow. This mean that
198 * we will be alerted in case of widget changing type, instead of getting just
199 * getting bad mojo due to casting a pointer to the wrong type.
201 #define CastChild( IdOrName, type ) dynamic_cast<type*>( FindWindow( IdOrName ) )
205 * Helperfunction for accessing the child of a any widget by ID.
207 * @param ID The ID of the widget to find.
208 * @param parent The parent of the widget to find, or NULL to search from the top.
209 * @param type The type to cast the widget to.
211 * @see CastChild()
213 #define CastByID( ID, parent, type ) dynamic_cast<type*>( wxWindow::FindWindowById( (ID), (parent) ) )
217 * Helperfunction for accessing the child of a any widget by Name.
219 * @param Name The Name of the widget to find.
220 * @param parent The parent of the widget to find, or NULL to search from the top.
221 * @param type The type to cast the widget to.
223 * @see CastChild()
225 #define CastByName( Name, parent, type ) dynamic_cast<type*>( wxWindow::FindWindowByName( (Name), (parent) ) )
228 // From Gnucleus project [found by Tarod]
229 // Base16/Base32/Base64 Encode/Decode functions
230 wxString EncodeBase16(const unsigned char* buffer, unsigned int bufLen);
231 unsigned int DecodeBase16(const wxString &base16Buffer, unsigned int base16BufLen, unsigned char *buffer);
232 wxString EncodeBase32(const unsigned char* buffer, unsigned int bufLen);
233 unsigned int DecodeBase32(const wxString &base32Buffer, unsigned int base32BufLen, unsigned char *buffer);
234 wxString EncodeBase64(const char* buffer, unsigned int bufLen);
235 unsigned int DecodeBase64(const wxString &base64Buffer, unsigned int base64BufLen, unsigned char *buffer);
237 // Converts the number of bytes to human readable form.
238 wxString CastItoXBytes(uint64 count);
239 // Converts the number to human readable form, abbreviating when nessecary.
240 wxString CastItoIShort(uint64 number);
241 // Converts a number of bytes to a human readable speed value.
242 wxString CastItoSpeed(uint32 bytes);
243 // Converts an amount of seconds to human readable time.
244 wxString CastSecondsToHM(uint32 seconds, uint16 msecs = 0);
245 // Returns the amount of Bytes the provided size-type represents
246 uint32 GetTypeSize(uint8 type);
247 // Returns the string associated with a file-rating value.
248 wxString GetRateString(uint16 rate);
251 // The following functions are used to identify and/or name the type of a file
252 enum FileType { ftAny, ftVideo, ftAudio, ftArchive, ftCDImage, ftPicture, ftText, ftProgram };
253 // Examins a filename and returns the enumerated value assosiated with it, or ftAny if unknown extension
254 FileType GetFiletype(const CPath& filename);
255 // Returns the description of a filetype: Movies, Audio, Pictures and so on...
256 wxString GetFiletypeDesc(FileType type, bool translated = true);
257 // Shorthand for GetFiletypeDesc(GetFiletype(filename))
258 wxString GetFiletypeByName(const CPath& filename, bool translated = true);
261 // Returns the name associated with a category value.
262 wxString GetCatTitle(int catid);
264 /* Other */
267 //! Returns the number of items in an array.
268 #define itemsof(x) (sizeof(x)/sizeof(x[0]))
271 ///////////////////////////////////////////////////////////////////////////////
272 // ED2K File Type
275 enum EED2KFileType
277 ED2KFT_ANY,
278 ED2KFT_AUDIO,
279 ED2KFT_VIDEO,
280 ED2KFT_IMAGE,
281 ED2KFT_PROGRAM,
282 ED2KFT_DOCUMENT,
283 ED2KFT_ARCHIVE,
284 ED2KFT_CDIMAGE
287 class EED2KFileTypeClass
289 public:
290 EED2KFileTypeClass()
292 s_t = ED2KFT_ANY;
294 EED2KFileTypeClass(EED2KFileType t)
296 s_t = t;
298 EED2KFileType GetType() const
300 return s_t;
303 private:
304 EED2KFileType s_t;
307 EED2KFileType GetED2KFileTypeID(const CPath& fileName);
308 wxString GetED2KFileTypeSearchTerm(EED2KFileType iFileID);
309 wxString GetFileTypeByName(const CPath& fileName);
310 EED2KFileType GetED2KFileTypeSearchID(EED2KFileType iFileID);
311 ///////////////////////////////////////////////////////////////////////////////
313 // md4cmp -- replacement for memcmp(hash1,hash2,16)
314 // Like 'memcmp' this function returns 0, if hash1==hash2, and !0, if hash1!=hash2.
315 // NOTE: Do *NOT* use that function for determining if hash1<hash2 or hash1>hash2.
316 inline int md4cmp(const void* hash1, const void* hash2)
318 return memcmp(hash1, hash2, 16);
322 // md4clr -- replacement for memset(hash,0,16)
323 inline void md4clr(void* hash)
325 memset(hash, 0, 16);
329 // md4cpy -- replacement for memcpy(dst,src,16)
330 inline void md4cpy(void* dst, const void* src)
332 memcpy(dst, src, 16);
336 // DumpMem ... Dumps mem ;)
337 wxString DumpMemToStr(const void *buff, int n, const wxString& msg = wxEmptyString, bool ok = true);
338 void DumpMem(const void *buff, int n, const wxString& msg = wxEmptyString, bool ok = true);
339 void DumpMem_DW(const uint32 *ptr, int count);
341 // Returns special source ID for GUI.
342 // It's actually IP<<16+Port
343 #define GUI_ID(x,y) (uint64)((((uint64)x)<<16) + (uint64)y)
344 // And so...
345 #define PORT_FROM_GUI_ID(x) (x & 0xFFFF)
346 #define IP_FROM_GUI_ID(x) (x >> 16)
350 inline long int make_full_ed2k_version(int a, int b, int c) {
351 return ((a << 17) | (b << 10) | (c << 7));
355 wxString GetConfigDir(const wxString &configFile = wxT("amule.conf"));
357 #if !wxCHECK_VERSION(2, 9, 0)
358 enum {
359 wxLANGUAGE_ASTURIAN = wxLANGUAGE_USER_DEFINED + 1
361 #endif
364 * Adds aMule's custom languages to db.
366 void InitCustomLanguages();
369 * Initializes locale
371 void InitLocale(wxLocale& locale, int language);
374 * Converts a string locale definition to a wxLANGUAGE id.
376 int StrLang2wx(const wxString& language);
379 * Converts a wxLANGUAGE id to a string locale name.
381 wxString wxLang2Str(const int lang);
384 * Generate MD5Hash of prompt input
386 wxString GetPassword();
389 #if wxUSE_THREADS
391 #include <wx/thread.h>
394 * Automatically unlocks a mutex on construction and locks it on destruction.
396 * This class is the complement of wxMutexLocker. It is intended to be used
397 * when a mutex, which is locked for a period of time, needs to be
398 * temporarily unlocked for a bit. For example:
400 * wxMutexLocker lock(mutex);
402 * // ... do stuff that requires that the mutex is locked ...
405 * CMutexUnlocker unlocker(mutex);
406 * // ... do stuff that requires that the mutex is unlocked ...
409 * // ... do more stuff that requires that the mutex is locked ...
412 class CMutexUnlocker
414 public:
415 // unlock the mutex in the ctor
416 CMutexUnlocker(wxMutex& mutex)
417 : m_isOk(false), m_mutex(mutex)
418 { m_isOk = ( m_mutex.Unlock() == wxMUTEX_NO_ERROR ); }
420 // returns true if mutex was successfully unlocked in ctor
421 bool IsOk() const
422 { return m_isOk; }
424 // lock the mutex in dtor
425 ~CMutexUnlocker()
426 { if ( IsOk() ) m_mutex.Lock(); }
428 private:
429 // no assignment operator nor copy ctor
430 CMutexUnlocker(const CMutexUnlocker&);
431 CMutexUnlocker& operator=(const CMutexUnlocker&);
433 bool m_isOk;
434 wxMutex& m_mutex;
436 #endif /* wxUSE_THREADS */
439 #endif // OTHERFUNCTIONS_H
440 // File_checked_for_headers