1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2011 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.
10 //
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.
15 //
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
24 //
25 
26 #ifndef OTHERFUNCTIONS_H
27 #define OTHERFUNCTIONS_H
28 
29 #include <wx/intl.h>		// Needed for wxLANGUAGE_ constants
30 
31 #include "Types.h"		// Needed for uint16, uint32 and uint64
32 #include "Preferences.h"	// Needed for AllCategoryFilter enumeration
33 #include "MD4Hash.h"		// Needed for CMD4Hash
34 
35 #include <algorithm>		// Needed for std::for_each	// Do_not_auto_remove (mingw-gcc-3.4.5)
36 
37 
38 class CPath;
39 
40 
41 /**
42  * Helper function.
43  *
44  * @param ArgA The base value.
45  * @param ArgB The value to compare ArgA against.
46  * @return See below.
47  *
48  * Use this function to safely compare two arguments of a type that supports
49  * the "<" operator. It works like strcmp and returns a negative value if ArgA
50  * is less than ArgB, zero if ArgA is equal to ArgB and a positive value if
51  * ArgA is greater than ArgB.
52  */
53 template <class TYPE>
CmpAny(const TYPE & ArgA,const TYPE & ArgB)54 int CmpAny(const TYPE& ArgA, const TYPE& ArgB)
55 {
56 	if ( ArgA < ArgB ) {
57 		return -1;
58 	} else if ( ArgB < ArgA ) {
59 		return  1;
60 	} else {
61 		return  0;
62 	}
63 }
64 
65 //! Overloaded version of CmpAny for use with wxStrings.
CmpAny(const wxString & ArgA,const wxString & ArgB)66 inline int CmpAny(const wxString& ArgA, const wxString& ArgB)
67 {
68 	if (ArgA.IsEmpty() && !ArgB.IsEmpty()) {
69 		return -1;
70 	} else if (!ArgA.IsEmpty() && ArgB.IsEmpty()) {
71 		return 1;
72 	} else if (ArgA.IsEmpty() && ArgB.IsEmpty()) {
73 		return 0;
74 	} else {
75 		return ArgA.CmpNoCase( ArgB );
76 	}
77 }
78 
79 //! Overloaded version of CmpAny for use with C-Strings (Unicoded).
CmpAny(const wxChar * ArgA,const wxChar * ArgB)80 inline int CmpAny(const wxChar* ArgA, const wxChar* ArgB)
81 {
82 	return CmpAny(wxString( ArgA ), wxString( ArgB ));
83 }
84 
85 
86 /**
87  * Removes the first instance of a value from a STL-like list: list, vector or deque.
88  *
89  * @param list The list to manipulate.
90  * @param item The value to search for and remove.
91  * @return The number of instances removed.
92  */
93 template <typename LIST, typename ITEM>
EraseFirstValue(LIST & list,const ITEM & item)94 unsigned int EraseFirstValue( LIST& list, const ITEM& item )
95 {
96 	typename LIST::iterator it = list.begin();
97 
98 	for (; it != list.end(); ++it) {
99 		if (*it == item) {
100 			list.erase(it);
101 
102 			return true;
103 		}
104 	}
105 
106 	return false;
107 }
108 
109 
110 /**
111  * Removes all instances of a value from a STL-like list: list, vector or deque.
112  *
113  * @param list The list to manipulate.
114  * @param item The value to search for and remove.
115  * @return The number of instances removed.
116  */
117 template <typename LIST, typename ITEM>
EraseValue(LIST & list,const ITEM & item)118 unsigned int EraseValue( LIST& list, const ITEM& item )
119 {
120 	typename LIST::iterator it = list.begin();
121 	unsigned int count = 0;
122 
123 	for ( ; it != list.end(); ) {
124 		if ( *it == item ) {
125 			it = list.erase( it );
126 			count++;
127 		} else {
128 			++it;
129 		}
130 	}
131 
132 	return count;
133 }
134 
135 
136 //! Used by DeleteContents
137 struct SDoDelete
138 {
139 	// Used for lists, vectors, deques, etc.
140 	template <typename TYPE>
operatorSDoDelete141 	void operator()(TYPE* ptr) {
142 		delete ptr;
143 	}
144 
145 	// Used for maps, hashmaps, rangemaps, etc.
146 	template <typename FIRST, typename SECOND>
operatorSDoDelete147 	void operator()(const std::pair<FIRST, SECOND>& pair) {
148 		delete pair.second;
149 	}
150 };
151 
152 
153 /** Frees the contents of a list or map like stl container, clearing it afterwards. */
154 template <typename STL_CONTAINER>
DeleteContents(STL_CONTAINER & container)155 void DeleteContents(STL_CONTAINER& container)
156 {
157 	// Ensure that the actual container wont contain dangling pointers during
158 	// this operation, to ensure that the destructors cant access them.
159 	STL_CONTAINER copy;
160 
161 	std::swap(copy, container);
162 	std::for_each(copy.begin(), copy.end(), SDoDelete());
163 }
164 
165 
166 /**
167  * Copies elements from the range [first, first + n) to the range [result, result + n).
168  */
169 template <class InputIterator, class OutputIterator>
STLCopy_n(InputIterator first,size_t n,OutputIterator result)170 OutputIterator STLCopy_n(InputIterator first, size_t n, OutputIterator result)
171 {
172 	return std::copy(first, first + n, result);
173 }
174 
175 
176 /**
177  * Helperfunction for accessing a child of the calling widget.
178  *
179  * @param IdOrName The ID or the Name of the widget to find.
180  * @param type The widget-type to cast the found widget to.
181  *
182  * Use this function as a replacement for the following constructs:
183  *  - wxStaticCast( FindWindow( <IdOrName> ), <type> )
184  *  - (<type>*)FindWindow( <IdOrName> )
185  *
186  * It has the advantage of validating the cast in debug builds and being much
187  * shorter than than manually typing wxStaticCast + FindWindow. This mean that
188  * we will be alerted in case of widget changing type, instead of getting just
189  * getting bad mojo due to casting a pointer to the wrong type.
190  */
191 #define CastChild( IdOrName, type )			dynamic_cast<type*>( FindWindow( IdOrName ) )
192 
193 
194 /**
195  * Helperfunction for accessing the child of a any widget by ID.
196  *
197  * @param ID The ID of the widget to find.
198  * @param parent The parent of the widget to find, or NULL to search from the top.
199  * @param type The type to cast the widget to.
200  *
201  * @see CastChild()
202  */
203 #define CastByID( ID, parent, type )		dynamic_cast<type*>( wxWindow::FindWindowById( (ID), (parent) ) )
204 
205 
206 /**
207  * Helperfunction for accessing the child of a any widget by Name.
208  *
209  * @param Name The Name of the widget to find.
210  * @param parent The parent of the widget to find, or NULL to search from the top.
211  * @param type The type to cast the widget to.
212  *
213  * @see CastChild()
214  */
215 #define CastByName( Name, parent, type )	dynamic_cast<type*>( wxWindow::FindWindowByName( (Name), (parent) ) )
216 
217 
218 // From Gnucleus project [found by Tarod]
219 // Base16/Base32/Base64 Encode/Decode functions
220 wxString EncodeBase16(const unsigned char* buffer, unsigned int bufLen);
221 unsigned int DecodeBase16(const wxString &base16Buffer, unsigned int base16BufLen, unsigned char *buffer);
222 wxString EncodeBase32(const unsigned char* buffer, unsigned int bufLen);
223 unsigned int DecodeBase32(const wxString &base32Buffer, unsigned int base32BufLen, unsigned char *buffer);
224 wxString EncodeBase64(const char* buffer, unsigned int bufLen);
225 unsigned int DecodeBase64(const wxString &base64Buffer, unsigned int base64BufLen, unsigned char *buffer);
226 
227 // Converts the number of bytes to human readable form.
228 wxString CastItoXBytes(uint64 count);
229 // Converts the number to human readable form, abbreviating when nessecary.
230 wxString CastItoIShort(uint64 number);
231 // Converts a number of bytes to a human readable speed value.
232 wxString CastItoSpeed(uint32 bytes);
233 // Converts an amount of seconds to human readable time.
234 wxString CastSecondsToHM(uint32 seconds, uint16 msecs = 0);
235 // Returns the amount of Bytes the provided size-type represents
236 uint32 GetTypeSize(uint8 type);
237 // Returns the string associated with a file-rating value.
238 wxString GetRateString(uint16 rate);
239 
240 
241 // The following functions are used to identify and/or name the type of a file
242 enum FileType { ftAny, ftVideo, ftAudio, ftArchive, ftCDImage, ftPicture, ftText, ftProgram };
243 // Examins a filename and returns the enumerated value assosiated with it, or ftAny if unknown extension
244 FileType GetFiletype(const CPath& filename);
245 // Returns the description of a filetype: Movies, Audio, Pictures and so on...
246 wxString GetFiletypeDesc(FileType type, bool translated = true);
247 // Shorthand for GetFiletypeDesc(GetFiletype(filename))
248 wxString GetFiletypeByName(const CPath& filename, bool translated = true);
249 
250 
251 // Returns the name associated with a category value.
252 wxString GetCatTitle(AllCategoryFilter cat);
253 
254 
255 ///////////////////////////////////////////////////////////////////////////////
256 // ED2K File Type
257 //
258 
259 enum EED2KFileType
260 {
261 	ED2KFT_ANY,
262 	ED2KFT_AUDIO,
263 	ED2KFT_VIDEO,
264 	ED2KFT_IMAGE,
265 	ED2KFT_PROGRAM,
266 	ED2KFT_DOCUMENT,
267 	ED2KFT_ARCHIVE,
268 	ED2KFT_CDIMAGE
269 };
270 
271 class EED2KFileTypeClass
272 {
273 public:
EED2KFileTypeClass()274 	EED2KFileTypeClass()
275 	{
276 		s_t = ED2KFT_ANY;
277 	}
EED2KFileTypeClass(EED2KFileType t)278 	EED2KFileTypeClass(EED2KFileType t)
279 	{
280 		s_t = t;
281 	}
GetType()282 	EED2KFileType GetType() const
283 	{
284 		return s_t;
285 	}
286 
287 private:
288 	EED2KFileType s_t;
289 };
290 
291 EED2KFileType GetED2KFileTypeID(const CPath& fileName);
292 wxString GetED2KFileTypeSearchTerm(EED2KFileType iFileID);
293 wxString GetFileTypeByName(const CPath& fileName);
294 EED2KFileType GetED2KFileTypeSearchID(EED2KFileType iFileID);
295 ///////////////////////////////////////////////////////////////////////////////
296 
297 // md4cmp -- replacement for memcmp(hash1,hash2,16)
298 // Like 'memcmp' this function returns 0, if hash1==hash2, and !0, if hash1!=hash2.
299 // NOTE: Do *NOT* use that function for determining if hash1<hash2 or hash1>hash2.
md4cmp(const void * hash1,const void * hash2)300 inline int md4cmp(const void* hash1, const void* hash2)
301 {
302 	return memcmp(hash1, hash2, 16);
303 }
304 
305 
306 // md4clr -- replacement for memset(hash,0,16)
md4clr(void * hash)307 inline void md4clr(void* hash)
308 {
309 	memset(hash, 0, 16);
310 }
311 
312 
313 // md4cpy -- replacement for memcpy(dst,src,16)
md4cpy(void * dst,const void * src)314 inline void md4cpy(void* dst, const void* src)
315 {
316 	memcpy(dst, src, 16);
317 }
318 
319 
320 // DumpMem ... Dumps mem ;)
321 wxString DumpMemToStr(const void *buff, int n, const wxString& msg = wxEmptyString, bool ok = true);
322 void DumpMem(const void *buff, int n, const wxString& msg = wxEmptyString, bool ok = true);
323 void DumpMem_DW(const uint32 *ptr, int count);
324 
325 // Returns special source ID for GUI.
326 // It's actually IP<<16+Port
327 #define GUI_ID(x,y) (uint64)((((uint64)x)<<16) + (uint64)y)
328 // And so...
329 #define PORT_FROM_GUI_ID(x) (x & 0xFFFF)
330 #define IP_FROM_GUI_ID(x) (x >> 16)
331 
332 
333 
make_full_ed2k_version(int a,int b,int c)334 inline long int make_full_ed2k_version(int a, int b, int c) {
335 	return ((a << 17) | (b << 10) | (c << 7));
336 }
337 
338 
339 wxString GetConfigDir(const wxString &configFile);
340 
341 #if !wxCHECK_VERSION(2, 9, 0)
342 enum {
343 	wxLANGUAGE_ASTURIAN	= wxLANGUAGE_USER_DEFINED + 1
344 };
345 #endif
346 
347 /**
348  * Adds aMule's custom languages to db.
349  */
350 void InitCustomLanguages();
351 
352 /**
353  * Initializes locale
354  */
355 void InitLocale(wxLocale& locale, int language);
356 
357 /**
358  * Converts a string locale definition to a wxLANGUAGE id.
359  */
360 int StrLang2wx(const wxString& language);
361 
362 /**
363  * Converts a wxLANGUAGE id to a string locale name.
364  */
365 wxString wxLang2Str(const int lang);
366 
367 /**
368  * Generate MD5Hash of prompt input
369  */
370 CMD4Hash GetPassword(bool allowEmptyPassword = false);
371 
372 
373 #if wxUSE_THREADS
374 
375 #include <wx/thread.h>
376 
377 /**
378  * Automatically unlocks a mutex on construction and locks it on destruction.
379  *
380  * This class is the complement of wxMutexLocker.  It is intended to be used
381  * when a mutex, which is locked for a period of time, needs to be
382  * temporarily unlocked for a bit.  For example:
383  *
384  *	wxMutexLocker lock(mutex);
385  *
386  *	// ... do stuff that requires that the mutex is locked ...
387  *
388  *	{
389  *		CMutexUnlocker unlocker(mutex);
390  *		// ... do stuff that requires that the mutex is unlocked ...
391  *	}
392  *
393  *	// ... do more stuff that requires that the mutex is locked ...
394  *
395  */
396 class CMutexUnlocker
397 {
398 public:
399     // unlock the mutex in the ctor
CMutexUnlocker(wxMutex & mutex)400     CMutexUnlocker(wxMutex& mutex)
401         : m_isOk(false), m_mutex(mutex)
402         { m_isOk = ( m_mutex.Unlock() == wxMUTEX_NO_ERROR ); }
403 
404     // returns true if mutex was successfully unlocked in ctor
IsOk()405     bool IsOk() const
406         { return m_isOk; }
407 
408     // lock the mutex in dtor
~CMutexUnlocker()409     ~CMutexUnlocker()
410         { if ( IsOk() ) m_mutex.Lock(); }
411 
412 private:
413     // no assignment operator nor copy ctor
414     CMutexUnlocker(const CMutexUnlocker&);
415     CMutexUnlocker& operator=(const CMutexUnlocker&);
416 
417     bool     m_isOk;
418     wxMutex& m_mutex;
419 };
420 #endif /* wxUSE_THREADS */
421 
422 
423 #endif // OTHERFUNCTIONS_H
424 // File_checked_for_headers
425