1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
42 // what to test (in alphabetic order)?
45 //#define TEST_CHARSET
46 //#define TEST_CMDLINE
47 //#define TEST_DATETIME
49 //#define TEST_DLLLOADER
50 //#define TEST_ENVIRON
51 //#define TEST_EXECUTE
53 //#define TEST_FILECONF
54 //#define TEST_FILENAME
58 //#define TEST_INFO_FUNCTIONS
62 //#define TEST_LONGLONG
64 //#define TEST_PATHLIST
65 //#define TEST_REGCONF
67 //#define TEST_REGISTRY
68 //#define TEST_SNGLINST
69 //#define TEST_SOCKETS
70 //#define TEST_STREAMS
71 //#define TEST_STRINGS
72 //#define TEST_THREADS
74 //#define TEST_VCARD -- don't enable this (VZ)
80 #include "wx/snglinst.h"
81 #endif // TEST_SNGLINST
83 // ----------------------------------------------------------------------------
84 // test class for container objects
85 // ----------------------------------------------------------------------------
87 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
89 class Bar
// Foo is already taken in the hash test
92 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
95 static size_t GetNumber() { return ms_bars
; }
97 const char *GetName() const { return m_name
; }
102 static size_t ms_bars
;
105 size_t Bar::ms_bars
= 0;
107 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
109 // ============================================================================
111 // ============================================================================
113 // ----------------------------------------------------------------------------
115 // ----------------------------------------------------------------------------
117 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
119 // replace TABs with \t and CRs with \n
120 static wxString
MakePrintable(const wxChar
*s
)
123 (void)str
.Replace(_T("\t"), _T("\\t"));
124 (void)str
.Replace(_T("\n"), _T("\\n"));
125 (void)str
.Replace(_T("\r"), _T("\\r"));
130 #endif // MakePrintable() is used
132 // ----------------------------------------------------------------------------
133 // wxFontMapper::CharsetToEncoding
134 // ----------------------------------------------------------------------------
138 #include "wx/fontmap.h"
140 static void TestCharset()
142 static const wxChar
*charsets
[] =
144 // some vali charsets
153 // and now some bogus ones
160 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
162 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
163 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
165 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
166 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
170 #endif // TEST_CHARSET
172 // ----------------------------------------------------------------------------
174 // ----------------------------------------------------------------------------
178 #include "wx/cmdline.h"
179 #include "wx/datetime.h"
181 static void ShowCmdLine(const wxCmdLineParser
& parser
)
183 wxString s
= "Input files: ";
185 size_t count
= parser
.GetParamCount();
186 for ( size_t param
= 0; param
< count
; param
++ )
188 s
<< parser
.GetParam(param
) << ' ';
192 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
193 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
198 if ( parser
.Found("o", &strVal
) )
199 s
<< "Output file:\t" << strVal
<< '\n';
200 if ( parser
.Found("i", &strVal
) )
201 s
<< "Input dir:\t" << strVal
<< '\n';
202 if ( parser
.Found("s", &lVal
) )
203 s
<< "Size:\t" << lVal
<< '\n';
204 if ( parser
.Found("d", &dt
) )
205 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
206 if ( parser
.Found("project_name", &strVal
) )
207 s
<< "Project:\t" << strVal
<< '\n';
212 #endif // TEST_CMDLINE
214 // ----------------------------------------------------------------------------
216 // ----------------------------------------------------------------------------
223 static const wxChar
*ROOTDIR
= _T("/");
224 static const wxChar
*TESTDIR
= _T("/usr");
225 #elif defined(__WXMSW__)
226 static const wxChar
*ROOTDIR
= _T("c:\\");
227 static const wxChar
*TESTDIR
= _T("d:\\");
229 #error "don't know where the root directory is"
232 static void TestDirEnumHelper(wxDir
& dir
,
233 int flags
= wxDIR_DEFAULT
,
234 const wxString
& filespec
= wxEmptyString
)
238 if ( !dir
.IsOpened() )
241 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
244 printf("\t%s\n", filename
.c_str());
246 cont
= dir
.GetNext(&filename
);
252 static void TestDirEnum()
254 puts("*** Testing wxDir::GetFirst/GetNext ***");
256 wxDir
dir(wxGetCwd());
258 puts("Enumerating everything in current directory:");
259 TestDirEnumHelper(dir
);
261 puts("Enumerating really everything in current directory:");
262 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
264 puts("Enumerating object files in current directory:");
265 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
267 puts("Enumerating directories in current directory:");
268 TestDirEnumHelper(dir
, wxDIR_DIRS
);
270 puts("Enumerating files in current directory:");
271 TestDirEnumHelper(dir
, wxDIR_FILES
);
273 puts("Enumerating files including hidden in current directory:");
274 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
278 puts("Enumerating everything in root directory:");
279 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
281 puts("Enumerating directories in root directory:");
282 TestDirEnumHelper(dir
, wxDIR_DIRS
);
284 puts("Enumerating files in root directory:");
285 TestDirEnumHelper(dir
, wxDIR_FILES
);
287 puts("Enumerating files including hidden in root directory:");
288 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
290 puts("Enumerating files in non existing directory:");
291 wxDir
dirNo("nosuchdir");
292 TestDirEnumHelper(dirNo
);
295 class DirPrintTraverser
: public wxDirTraverser
298 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
300 return wxDIR_CONTINUE
;
303 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
305 wxString path
, name
, ext
;
306 wxSplitPath(dirname
, &path
, &name
, &ext
);
309 name
<< _T('.') << ext
;
312 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
314 if ( wxIsPathSeparator(*p
) )
318 printf("%s%s\n", indent
.c_str(), name
.c_str());
320 return wxDIR_CONTINUE
;
324 static void TestDirTraverse()
326 puts("*** Testing wxDir::Traverse() ***");
330 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
331 printf("There are %u files under '%s'\n", n
, TESTDIR
);
334 printf("First one is '%s'\n", files
[0u].c_str());
335 printf(" last one is '%s'\n", files
[n
- 1].c_str());
338 // enum again with custom traverser
340 DirPrintTraverser traverser
;
341 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
346 // ----------------------------------------------------------------------------
348 // ----------------------------------------------------------------------------
350 #ifdef TEST_DLLLOADER
352 #include "wx/dynlib.h"
354 static void TestDllLoad()
356 #if defined(__WXMSW__)
357 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
358 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
359 #elif defined(__UNIX__)
360 // weird: using just libc.so does *not* work!
361 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
362 static const wxChar
*FUNC_NAME
= _T("strlen");
364 #error "don't know how to test wxDllLoader on this platform"
367 puts("*** testing wxDllLoader ***\n");
369 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
372 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
376 typedef int (*strlenType
)(const char *);
377 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
380 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
381 FUNC_NAME
, LIB_NAME
);
385 if ( pfnStrlen("foo") != 3 )
387 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
395 wxDllLoader::UnloadLibrary(dllHandle
);
399 #endif // TEST_DLLLOADER
401 // ----------------------------------------------------------------------------
403 // ----------------------------------------------------------------------------
407 #include "wx/utils.h"
409 static wxString
MyGetEnv(const wxString
& var
)
412 if ( !wxGetEnv(var
, &val
) )
415 val
= wxString(_T('\'')) + val
+ _T('\'');
420 static void TestEnvironment()
422 const wxChar
*var
= _T("wxTestVar");
424 puts("*** testing environment access functions ***");
426 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
427 wxSetEnv(var
, _T("value for wxTestVar"));
428 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
429 wxSetEnv(var
, _T("another value"));
430 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
432 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
433 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
436 #endif // TEST_ENVIRON
438 // ----------------------------------------------------------------------------
440 // ----------------------------------------------------------------------------
444 #include "wx/utils.h"
446 static void TestExecute()
448 puts("*** testing wxExecute ***");
451 #define COMMAND "cat -n ../../Makefile" // "echo hi"
452 #define SHELL_COMMAND "echo hi from shell"
453 #define REDIRECT_COMMAND COMMAND // "date"
454 #elif defined(__WXMSW__)
455 #define COMMAND "command.com -c 'echo hi'"
456 #define SHELL_COMMAND "echo hi"
457 #define REDIRECT_COMMAND COMMAND
459 #error "no command to exec"
462 printf("Testing wxShell: ");
464 if ( wxShell(SHELL_COMMAND
) )
469 printf("Testing wxExecute: ");
471 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
476 #if 0 // no, it doesn't work (yet?)
477 printf("Testing async wxExecute: ");
479 if ( wxExecute(COMMAND
) != 0 )
480 puts("Ok (command launched).");
485 printf("Testing wxExecute with redirection:\n");
486 wxArrayString output
;
487 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
493 size_t count
= output
.GetCount();
494 for ( size_t n
= 0; n
< count
; n
++ )
496 printf("\t%s\n", output
[n
].c_str());
503 #endif // TEST_EXECUTE
505 // ----------------------------------------------------------------------------
507 // ----------------------------------------------------------------------------
512 #include "wx/ffile.h"
513 #include "wx/textfile.h"
515 static void TestFileRead()
517 puts("*** wxFile read test ***");
519 wxFile
file(_T("testdata.fc"));
520 if ( file
.IsOpened() )
522 printf("File length: %lu\n", file
.Length());
524 puts("File dump:\n----------");
526 static const off_t len
= 1024;
530 off_t nRead
= file
.Read(buf
, len
);
531 if ( nRead
== wxInvalidOffset
)
533 printf("Failed to read the file.");
537 fwrite(buf
, nRead
, 1, stdout
);
547 printf("ERROR: can't open test file.\n");
553 static void TestTextFileRead()
555 puts("*** wxTextFile read test ***");
557 wxTextFile
file(_T("testdata.fc"));
560 printf("Number of lines: %u\n", file
.GetLineCount());
561 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
565 puts("\nDumping the entire file:");
566 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
568 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
570 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
572 puts("\nAnd now backwards:");
573 for ( s
= file
.GetLastLine();
574 file
.GetCurrentLine() != 0;
575 s
= file
.GetPrevLine() )
577 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
579 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
583 printf("ERROR: can't open '%s'\n", file
.GetName());
589 static void TestFileCopy()
591 puts("*** Testing wxCopyFile ***");
593 static const wxChar
*filename1
= _T("testdata.fc");
594 static const wxChar
*filename2
= _T("test2");
595 if ( !wxCopyFile(filename1
, filename2
) )
597 puts("ERROR: failed to copy file");
601 wxFFile
f1(filename1
, "rb"),
604 if ( !f1
.IsOpened() || !f2
.IsOpened() )
606 puts("ERROR: failed to open file(s)");
611 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
613 puts("ERROR: failed to read file(s)");
617 if ( (s1
.length() != s2
.length()) ||
618 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
620 puts("ERROR: copy error!");
624 puts("File was copied ok.");
630 if ( !wxRemoveFile(filename2
) )
632 puts("ERROR: failed to remove the file");
640 // ----------------------------------------------------------------------------
642 // ----------------------------------------------------------------------------
646 #include "wx/confbase.h"
647 #include "wx/fileconf.h"
649 static const struct FileConfTestData
651 const wxChar
*name
; // value name
652 const wxChar
*value
; // the value from the file
655 { _T("value1"), _T("one") },
656 { _T("value2"), _T("two") },
657 { _T("novalue"), _T("default") },
660 static void TestFileConfRead()
662 puts("*** testing wxFileConfig loading/reading ***");
664 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
665 _T("testdata.fc"), wxEmptyString
,
666 wxCONFIG_USE_RELATIVE_PATH
);
668 // test simple reading
669 puts("\nReading config file:");
670 wxString
defValue(_T("default")), value
;
671 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
673 const FileConfTestData
& data
= fcTestData
[n
];
674 value
= fileconf
.Read(data
.name
, defValue
);
675 printf("\t%s = %s ", data
.name
, value
.c_str());
676 if ( value
== data
.value
)
682 printf("(ERROR: should be %s)\n", data
.value
);
686 // test enumerating the entries
687 puts("\nEnumerating all root entries:");
690 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
693 printf("\t%s = %s\n",
695 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
697 cont
= fileconf
.GetNextEntry(name
, dummy
);
701 #endif // TEST_FILECONF
703 // ----------------------------------------------------------------------------
705 // ----------------------------------------------------------------------------
709 #include "wx/filename.h"
711 static struct FileNameInfo
713 const wxChar
*fullname
;
719 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
720 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
721 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
722 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
723 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
724 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
725 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
726 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
729 static void TestFileNameConstruction()
731 puts("*** testing wxFileName construction ***");
733 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
735 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
737 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
738 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
740 puts("ERROR (couldn't be normalized)");
744 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
751 static void TestFileNameSplit()
753 puts("*** testing wxFileName splitting ***");
755 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
757 const FileNameInfo
&fni
= filenames
[n
];
758 wxString path
, name
, ext
;
759 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
761 printf("%s -> path = '%s', name = '%s', ext = '%s'",
762 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
763 if ( path
!= fni
.path
)
764 printf(" (ERROR: path = '%s')", fni
.path
);
765 if ( name
!= fni
.name
)
766 printf(" (ERROR: name = '%s')", fni
.name
);
767 if ( ext
!= fni
.ext
)
768 printf(" (ERROR: ext = '%s')", fni
.ext
);
775 static void TestFileNameComparison()
780 static void TestFileNameOperations()
785 static void TestFileNameCwd()
790 #endif // TEST_FILENAME
792 // ----------------------------------------------------------------------------
793 // wxFileName time functions
794 // ----------------------------------------------------------------------------
798 #include <wx/filename.h>
799 #include <wx/datetime.h>
801 static void TestFileGetTimes()
803 wxFileName
fn(_T("testdata.fc"));
805 wxDateTime dtAccess
, dtMod
, dtChange
;
806 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
808 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
812 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
814 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
815 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
816 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
817 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
821 static void TestFileSetTimes()
823 wxFileName
fn(_T("testdata.fc"));
825 wxDateTime dtAccess
, dtMod
, dtChange
;
828 wxPrintf(_T("ERROR: Touch() failed.\n"));
832 #endif // TEST_FILETIME
834 // ----------------------------------------------------------------------------
836 // ----------------------------------------------------------------------------
844 Foo(int n_
) { n
= n_
; count
++; }
852 size_t Foo::count
= 0;
854 WX_DECLARE_LIST(Foo
, wxListFoos
);
855 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
857 #include "wx/listimpl.cpp"
859 WX_DEFINE_LIST(wxListFoos
);
861 static void TestHash()
863 puts("*** Testing wxHashTable ***\n");
867 hash
.DeleteContents(TRUE
);
869 printf("Hash created: %u foos in hash, %u foos totally\n",
870 hash
.GetCount(), Foo::count
);
872 static const int hashTestData
[] =
874 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
878 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
880 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
883 printf("Hash filled: %u foos in hash, %u foos totally\n",
884 hash
.GetCount(), Foo::count
);
886 puts("Hash access test:");
887 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
889 printf("\tGetting element with key %d, value %d: ",
891 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
894 printf("ERROR, not found.\n");
898 printf("%d (%s)\n", foo
->n
,
899 (size_t)foo
->n
== n
? "ok" : "ERROR");
903 printf("\nTrying to get an element not in hash: ");
905 if ( hash
.Get(1234) || hash
.Get(1, 0) )
907 puts("ERROR: found!");
911 puts("ok (not found)");
915 printf("Hash destroyed: %u foos left\n", Foo::count
);
920 // ----------------------------------------------------------------------------
922 // ----------------------------------------------------------------------------
928 WX_DECLARE_LIST(Bar
, wxListBars
);
929 #include "wx/listimpl.cpp"
930 WX_DEFINE_LIST(wxListBars
);
932 static void TestListCtor()
934 puts("*** Testing wxList construction ***\n");
938 list1
.Append(new Bar(_T("first")));
939 list1
.Append(new Bar(_T("second")));
941 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
942 list1
.GetCount(), Bar::GetNumber());
947 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
948 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
950 list1
.DeleteContents(TRUE
);
953 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
958 // ----------------------------------------------------------------------------
960 // ----------------------------------------------------------------------------
965 #include "wx/utils.h" // for wxSetEnv
967 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
969 // find the name of the language from its value
970 static const char *GetLangName(int lang
)
972 static const char *languageNames
[] =
993 "ARABIC_SAUDI_ARABIA",
1018 "CHINESE_SIMPLIFIED",
1019 "CHINESE_TRADITIONAL",
1022 "CHINESE_SINGAPORE",
1033 "ENGLISH_AUSTRALIA",
1037 "ENGLISH_CARIBBEAN",
1041 "ENGLISH_NEW_ZEALAND",
1042 "ENGLISH_PHILIPPINES",
1043 "ENGLISH_SOUTH_AFRICA",
1055 "FRENCH_LUXEMBOURG",
1064 "GERMAN_LIECHTENSTEIN",
1065 "GERMAN_LUXEMBOURG",
1106 "MALAY_BRUNEI_DARUSSALAM",
1118 "NORWEGIAN_NYNORSK",
1125 "PORTUGUESE_BRAZILIAN",
1150 "SPANISH_ARGENTINA",
1154 "SPANISH_COSTA_RICA",
1155 "SPANISH_DOMINICAN_REPUBLIC",
1157 "SPANISH_EL_SALVADOR",
1158 "SPANISH_GUATEMALA",
1162 "SPANISH_NICARAGUA",
1166 "SPANISH_PUERTO_RICO",
1169 "SPANISH_VENEZUELA",
1206 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1207 return languageNames
[lang
];
1212 static void TestDefaultLang()
1214 puts("*** Testing wxLocale::GetSystemLanguage ***");
1216 static const wxChar
*langStrings
[] =
1218 NULL
, // system default
1225 _T("de_DE.iso88591"),
1227 _T("?"), // invalid lang spec
1228 _T("klingonese"), // I bet on some systems it does exist...
1231 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1232 wxLocale::GetSystemEncodingName().c_str(),
1233 wxLocale::GetSystemEncoding());
1235 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1237 const char *langStr
= langStrings
[n
];
1240 // FIXME: this doesn't do anything at all under Windows, we need
1241 // to create a new wxLocale!
1242 wxSetEnv(_T("LC_ALL"), langStr
);
1245 int lang
= gs_localeDefault
.GetSystemLanguage();
1246 printf("Locale for '%s' is %s.\n",
1247 langStr
? langStr
: "system default", GetLangName(lang
));
1251 #endif // TEST_LOCALE
1253 // ----------------------------------------------------------------------------
1255 // ----------------------------------------------------------------------------
1259 #include "wx/mimetype.h"
1261 static void TestMimeEnum()
1263 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1265 wxArrayString mimetypes
;
1267 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1269 printf("*** All %u known filetypes: ***\n", count
);
1274 for ( size_t n
= 0; n
< count
; n
++ )
1276 wxFileType
*filetype
=
1277 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1280 printf("nothing known about the filetype '%s'!\n",
1281 mimetypes
[n
].c_str());
1285 filetype
->GetDescription(&desc
);
1286 filetype
->GetExtensions(exts
);
1288 filetype
->GetIcon(NULL
);
1291 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1294 extsAll
<< _T(", ");
1298 printf("\t%s: %s (%s)\n",
1299 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1305 static void TestMimeOverride()
1307 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1309 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1310 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1312 if ( wxFile::Exists(mailcap
) )
1313 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1315 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1317 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1320 if ( wxFile::Exists(mimetypes
) )
1321 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1323 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1325 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1331 static void TestMimeFilename()
1333 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1335 static const wxChar
*filenames
[] =
1342 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1344 const wxString fname
= filenames
[n
];
1345 wxString ext
= fname
.AfterLast(_T('.'));
1346 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1349 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1354 if ( !ft
->GetDescription(&desc
) )
1355 desc
= _T("<no description>");
1358 if ( !ft
->GetOpenCommand(&cmd
,
1359 wxFileType::MessageParameters(fname
, _T(""))) )
1360 cmd
= _T("<no command available>");
1362 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1363 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1372 static void TestMimeAssociate()
1374 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1376 wxFileTypeInfo
ftInfo(
1377 _T("application/x-xyz"),
1378 _T("xyzview '%s'"), // open cmd
1379 _T(""), // print cmd
1380 _T("XYZ File") // description
1381 _T(".xyz"), // extensions
1382 NULL
// end of extensions
1384 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1386 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1389 wxPuts(_T("ERROR: failed to create association!"));
1393 // TODO: read it back
1402 // ----------------------------------------------------------------------------
1403 // misc information functions
1404 // ----------------------------------------------------------------------------
1406 #ifdef TEST_INFO_FUNCTIONS
1408 #include "wx/utils.h"
1410 static void TestDiskInfo()
1412 puts("*** Testing wxGetDiskSpace() ***");
1417 printf("\nEnter a directory name: ");
1418 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1421 // kill the last '\n'
1422 pathname
[strlen(pathname
) - 1] = 0;
1424 wxLongLong total
, free
;
1425 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1427 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1431 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1432 (total
/ 1024).ToString().c_str(),
1433 (free
/ 1024).ToString().c_str(),
1439 static void TestOsInfo()
1441 puts("*** Testing OS info functions ***\n");
1444 wxGetOsVersion(&major
, &minor
);
1445 printf("Running under: %s, version %d.%d\n",
1446 wxGetOsDescription().c_str(), major
, minor
);
1448 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1450 printf("Host name is %s (%s).\n",
1451 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1456 static void TestUserInfo()
1458 puts("*** Testing user info functions ***\n");
1460 printf("User id is:\t%s\n", wxGetUserId().c_str());
1461 printf("User name is:\t%s\n", wxGetUserName().c_str());
1462 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1463 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1468 #endif // TEST_INFO_FUNCTIONS
1470 // ----------------------------------------------------------------------------
1472 // ----------------------------------------------------------------------------
1474 #ifdef TEST_LONGLONG
1476 #include "wx/longlong.h"
1477 #include "wx/timer.h"
1479 // make a 64 bit number from 4 16 bit ones
1480 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1482 // get a random 64 bit number
1483 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1485 static const long testLongs
[] =
1496 #if wxUSE_LONGLONG_WX
1497 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1498 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1499 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1500 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1501 #endif // wxUSE_LONGLONG_WX
1503 static void TestSpeed()
1505 static const long max
= 100000000;
1512 for ( n
= 0; n
< max
; n
++ )
1517 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1520 #if wxUSE_LONGLONG_NATIVE
1525 for ( n
= 0; n
< max
; n
++ )
1530 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1532 #endif // wxUSE_LONGLONG_NATIVE
1538 for ( n
= 0; n
< max
; n
++ )
1543 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1547 static void TestLongLongConversion()
1549 puts("*** Testing wxLongLong conversions ***\n");
1553 for ( size_t n
= 0; n
< 100000; n
++ )
1557 #if wxUSE_LONGLONG_NATIVE
1558 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1560 wxASSERT_MSG( a
== b
, "conversions failure" );
1562 puts("Can't do it without native long long type, test skipped.");
1565 #endif // wxUSE_LONGLONG_NATIVE
1567 if ( !(nTested
% 1000) )
1579 static void TestMultiplication()
1581 puts("*** Testing wxLongLong multiplication ***\n");
1585 for ( size_t n
= 0; n
< 100000; n
++ )
1590 #if wxUSE_LONGLONG_NATIVE
1591 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1592 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1594 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1595 #else // !wxUSE_LONGLONG_NATIVE
1596 puts("Can't do it without native long long type, test skipped.");
1599 #endif // wxUSE_LONGLONG_NATIVE
1601 if ( !(nTested
% 1000) )
1613 static void TestDivision()
1615 puts("*** Testing wxLongLong division ***\n");
1619 for ( size_t n
= 0; n
< 100000; n
++ )
1621 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1622 // multiplication will not overflow)
1623 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1625 // get a random long (not wxLongLong for now) to divide it with
1630 #if wxUSE_LONGLONG_NATIVE
1631 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1633 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1634 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1635 #else // !wxUSE_LONGLONG_NATIVE
1636 // verify the result
1637 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1638 #endif // wxUSE_LONGLONG_NATIVE
1640 if ( !(nTested
% 1000) )
1652 static void TestAddition()
1654 puts("*** Testing wxLongLong addition ***\n");
1658 for ( size_t n
= 0; n
< 100000; n
++ )
1664 #if wxUSE_LONGLONG_NATIVE
1665 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1666 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1667 "addition failure" );
1668 #else // !wxUSE_LONGLONG_NATIVE
1669 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1670 #endif // wxUSE_LONGLONG_NATIVE
1672 if ( !(nTested
% 1000) )
1684 static void TestBitOperations()
1686 puts("*** Testing wxLongLong bit operation ***\n");
1690 for ( size_t n
= 0; n
< 100000; n
++ )
1694 #if wxUSE_LONGLONG_NATIVE
1695 for ( size_t n
= 0; n
< 33; n
++ )
1698 #else // !wxUSE_LONGLONG_NATIVE
1699 puts("Can't do it without native long long type, test skipped.");
1702 #endif // wxUSE_LONGLONG_NATIVE
1704 if ( !(nTested
% 1000) )
1716 static void TestLongLongComparison()
1718 #if wxUSE_LONGLONG_WX
1719 puts("*** Testing wxLongLong comparison ***\n");
1721 static const long ls
[2] =
1727 wxLongLongWx lls
[2];
1731 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1735 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1737 res
= lls
[m
] > testLongs
[n
];
1738 printf("0x%lx > 0x%lx is %s (%s)\n",
1739 ls
[m
], testLongs
[n
], res
? "true" : "false",
1740 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1742 res
= lls
[m
] < testLongs
[n
];
1743 printf("0x%lx < 0x%lx is %s (%s)\n",
1744 ls
[m
], testLongs
[n
], res
? "true" : "false",
1745 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1747 res
= lls
[m
] == testLongs
[n
];
1748 printf("0x%lx == 0x%lx is %s (%s)\n",
1749 ls
[m
], testLongs
[n
], res
? "true" : "false",
1750 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1753 #endif // wxUSE_LONGLONG_WX
1756 static void TestLongLongPrint()
1758 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1760 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1762 wxLongLong ll
= testLongs
[n
];
1763 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1766 wxLongLong
ll(0x12345678, 0x87654321);
1767 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1770 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1776 #endif // TEST_LONGLONG
1778 // ----------------------------------------------------------------------------
1780 // ----------------------------------------------------------------------------
1782 #ifdef TEST_PATHLIST
1784 static void TestPathList()
1786 puts("*** Testing wxPathList ***\n");
1788 wxPathList pathlist
;
1789 pathlist
.AddEnvList("PATH");
1790 wxString path
= pathlist
.FindValidPath("ls");
1793 printf("ERROR: command not found in the path.\n");
1797 printf("Command found in the path as '%s'.\n", path
.c_str());
1801 #endif // TEST_PATHLIST
1803 // ----------------------------------------------------------------------------
1804 // regular expressions
1805 // ----------------------------------------------------------------------------
1809 #include "wx/regex.h"
1811 static void TestRegExCompile()
1813 wxPuts(_T("*** Testing RE compilation ***\n"));
1815 static struct RegExCompTestData
1817 const wxChar
*pattern
;
1819 } regExCompTestData
[] =
1821 { _T("foo"), TRUE
},
1822 { _T("foo("), FALSE
},
1823 { _T("foo(bar"), FALSE
},
1824 { _T("foo(bar)"), TRUE
},
1825 { _T("foo["), FALSE
},
1826 { _T("foo[bar"), FALSE
},
1827 { _T("foo[bar]"), TRUE
},
1828 { _T("foo{"), TRUE
},
1829 { _T("foo{1"), FALSE
},
1830 { _T("foo{bar"), TRUE
},
1831 { _T("foo{1}"), TRUE
},
1832 { _T("foo{1,2}"), TRUE
},
1833 { _T("foo{bar}"), TRUE
},
1834 { _T("foo*"), TRUE
},
1835 { _T("foo**"), FALSE
},
1836 { _T("foo+"), TRUE
},
1837 { _T("foo++"), FALSE
},
1838 { _T("foo?"), TRUE
},
1839 { _T("foo??"), FALSE
},
1840 { _T("foo?+"), FALSE
},
1844 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1846 const RegExCompTestData
& data
= regExCompTestData
[n
];
1847 bool ok
= re
.Compile(data
.pattern
);
1849 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1851 ok
? _T("") : _T("not "),
1852 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1856 static void TestRegExMatch()
1858 wxPuts(_T("*** Testing RE matching ***\n"));
1860 static struct RegExMatchTestData
1862 const wxChar
*pattern
;
1865 } regExMatchTestData
[] =
1867 { _T("foo"), _T("bar"), FALSE
},
1868 { _T("foo"), _T("foobar"), TRUE
},
1869 { _T("^foo"), _T("foobar"), TRUE
},
1870 { _T("^foo"), _T("barfoo"), FALSE
},
1871 { _T("bar$"), _T("barbar"), TRUE
},
1872 { _T("bar$"), _T("barbar "), FALSE
},
1875 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1877 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1879 wxRegEx
re(data
.pattern
);
1880 bool ok
= re
.Matches(data
.text
);
1882 wxPrintf(_T("'%s' %s %s (%s)\n"),
1884 ok
? _T("matches") : _T("doesn't match"),
1886 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1890 static void TestRegExSubmatch()
1892 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1894 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1895 if ( !re
.IsValid() )
1897 wxPuts(_T("ERROR: compilation failed."));
1901 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
1903 if ( !re
.Matches(text
) )
1905 wxPuts(_T("ERROR: match expected."));
1909 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
1911 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1912 re
.GetMatch(text
, 3).c_str(),
1913 re
.GetMatch(text
, 2).c_str(),
1914 re
.GetMatch(text
, 4).c_str(),
1915 re
.GetMatch(text
, 1).c_str());
1919 static void TestRegExReplacement()
1921 wxPuts(_T("*** Testing RE replacement ***"));
1923 static struct RegExReplTestData
1927 const wxChar
*result
;
1929 } regExReplTestData
[] =
1931 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1932 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1933 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1934 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1935 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1936 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1937 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1940 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
1941 wxRegEx re
= pattern
;
1943 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
1945 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
1947 const RegExReplTestData
& data
= regExReplTestData
[n
];
1949 wxString text
= data
.text
;
1950 size_t nRepl
= re
.Replace(&text
, data
.repl
);
1952 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1953 data
.text
, data
.repl
,
1954 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
1956 if ( text
== data
.result
&& nRepl
== data
.count
)
1962 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1963 data
.count
, data
.result
);
1968 static void TestRegExInteractive()
1970 wxPuts(_T("*** Testing RE interactively ***"));
1975 printf("\nEnter a pattern: ");
1976 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1979 // kill the last '\n'
1980 pattern
[strlen(pattern
) - 1] = 0;
1983 if ( !re
.Compile(pattern
) )
1991 printf("Enter text to match: ");
1992 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
1995 // kill the last '\n'
1996 text
[strlen(text
) - 1] = 0;
1998 if ( !re
.Matches(text
) )
2000 printf("No match.\n");
2004 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2007 for ( size_t n
= 1; ; n
++ )
2009 if ( !re
.GetMatch(&start
, &len
, n
) )
2014 printf("Subexpr %u matched '%s'\n",
2015 n
, wxString(text
+ start
, len
).c_str());
2022 #endif // TEST_REGEX
2024 // ----------------------------------------------------------------------------
2025 // registry and related stuff
2026 // ----------------------------------------------------------------------------
2028 // this is for MSW only
2031 #undef TEST_REGISTRY
2036 #include "wx/confbase.h"
2037 #include "wx/msw/regconf.h"
2039 static void TestRegConfWrite()
2041 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2042 regconf
.Write(_T("Hello"), wxString(_T("world")));
2045 #endif // TEST_REGCONF
2047 #ifdef TEST_REGISTRY
2049 #include "wx/msw/registry.h"
2051 // I chose this one because I liked its name, but it probably only exists under
2053 static const wxChar
*TESTKEY
=
2054 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2056 static void TestRegistryRead()
2058 puts("*** testing registry reading ***");
2060 wxRegKey
key(TESTKEY
);
2061 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2064 puts("ERROR: test key can't be opened, aborting test.");
2069 size_t nSubKeys
, nValues
;
2070 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2072 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2075 printf("Enumerating values:\n");
2079 bool cont
= key
.GetFirstValue(value
, dummy
);
2082 printf("Value '%s': type ", value
.c_str());
2083 switch ( key
.GetValueType(value
) )
2085 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2086 case wxRegKey::Type_String
: printf("SZ"); break;
2087 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2088 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2089 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2090 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2091 default: printf("other (unknown)"); break;
2094 printf(", value = ");
2095 if ( key
.IsNumericValue(value
) )
2098 key
.QueryValue(value
, &val
);
2104 key
.QueryValue(value
, val
);
2105 printf("'%s'", val
.c_str());
2107 key
.QueryRawValue(value
, val
);
2108 printf(" (raw value '%s')", val
.c_str());
2113 cont
= key
.GetNextValue(value
, dummy
);
2117 static void TestRegistryAssociation()
2120 The second call to deleteself genertaes an error message, with a
2121 messagebox saying .flo is crucial to system operation, while the .ddf
2122 call also fails, but with no error message
2127 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2129 key
= "ddxf_auto_file" ;
2130 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2132 key
= "ddxf_auto_file" ;
2133 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2136 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2138 key
= "program \"%1\"" ;
2140 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2142 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2144 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2146 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2150 #endif // TEST_REGISTRY
2152 // ----------------------------------------------------------------------------
2154 // ----------------------------------------------------------------------------
2158 #include "wx/socket.h"
2159 #include "wx/protocol/protocol.h"
2160 #include "wx/protocol/http.h"
2162 static void TestSocketServer()
2164 puts("*** Testing wxSocketServer ***\n");
2166 static const int PORT
= 3000;
2171 wxSocketServer
*server
= new wxSocketServer(addr
);
2172 if ( !server
->Ok() )
2174 puts("ERROR: failed to bind");
2181 printf("Server: waiting for connection on port %d...\n", PORT
);
2183 wxSocketBase
*socket
= server
->Accept();
2186 puts("ERROR: wxSocketServer::Accept() failed.");
2190 puts("Server: got a client.");
2192 server
->SetTimeout(60); // 1 min
2194 while ( socket
->IsConnected() )
2200 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2202 // don't log error if the client just close the connection
2203 if ( socket
->IsConnected() )
2205 puts("ERROR: in wxSocket::Read.");
2225 printf("Server: got '%s'.\n", s
.c_str());
2226 if ( s
== _T("bye") )
2233 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2234 socket
->Write("\r\n", 2);
2235 printf("Server: wrote '%s'.\n", s
.c_str());
2238 puts("Server: lost a client.");
2243 // same as "delete server" but is consistent with GUI programs
2247 static void TestSocketClient()
2249 puts("*** Testing wxSocketClient ***\n");
2251 static const char *hostname
= "www.wxwindows.org";
2254 addr
.Hostname(hostname
);
2257 printf("--- Attempting to connect to %s:80...\n", hostname
);
2259 wxSocketClient client
;
2260 if ( !client
.Connect(addr
) )
2262 printf("ERROR: failed to connect to %s\n", hostname
);
2266 printf("--- Connected to %s:%u...\n",
2267 addr
.Hostname().c_str(), addr
.Service());
2271 // could use simply "GET" here I suppose
2273 wxString::Format("GET http://%s/\r\n", hostname
);
2274 client
.Write(cmdGet
, cmdGet
.length());
2275 printf("--- Sent command '%s' to the server\n",
2276 MakePrintable(cmdGet
).c_str());
2277 client
.Read(buf
, WXSIZEOF(buf
));
2278 printf("--- Server replied:\n%s", buf
);
2282 #endif // TEST_SOCKETS
2284 // ----------------------------------------------------------------------------
2286 // ----------------------------------------------------------------------------
2290 #include "wx/protocol/ftp.h"
2294 #define FTP_ANONYMOUS
2296 #ifdef FTP_ANONYMOUS
2297 static const char *directory
= "/pub";
2298 static const char *filename
= "welcome.msg";
2300 static const char *directory
= "/etc";
2301 static const char *filename
= "issue";
2304 static bool TestFtpConnect()
2306 puts("*** Testing FTP connect ***");
2308 #ifdef FTP_ANONYMOUS
2309 static const char *hostname
= "ftp.wxwindows.org";
2311 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2312 #else // !FTP_ANONYMOUS
2313 static const char *hostname
= "localhost";
2316 fgets(user
, WXSIZEOF(user
), stdin
);
2317 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2321 printf("Password for %s: ", password
);
2322 fgets(password
, WXSIZEOF(password
), stdin
);
2323 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2324 ftp
.SetPassword(password
);
2326 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2327 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2329 if ( !ftp
.Connect(hostname
) )
2331 printf("ERROR: failed to connect to %s\n", hostname
);
2337 printf("--- Connected to %s, current directory is '%s'\n",
2338 hostname
, ftp
.Pwd().c_str());
2344 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2345 static void TestFtpWuFtpd()
2348 static const char *hostname
= "ftp.eudora.com";
2349 if ( !ftp
.Connect(hostname
) )
2351 printf("ERROR: failed to connect to %s\n", hostname
);
2355 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2356 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2359 printf("ERROR: couldn't get input stream for %s\n", filename
);
2363 size_t size
= in
->StreamSize();
2364 printf("Reading file %s (%u bytes)...", filename
, size
);
2366 char *data
= new char[size
];
2367 if ( !in
->Read(data
, size
) )
2369 puts("ERROR: read error");
2373 printf("Successfully retrieved the file.\n");
2382 static void TestFtpList()
2384 puts("*** Testing wxFTP file listing ***\n");
2387 if ( !ftp
.ChDir(directory
) )
2389 printf("ERROR: failed to cd to %s\n", directory
);
2392 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2394 // test NLIST and LIST
2395 wxArrayString files
;
2396 if ( !ftp
.GetFilesList(files
) )
2398 puts("ERROR: failed to get NLIST of files");
2402 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2403 size_t count
= files
.GetCount();
2404 for ( size_t n
= 0; n
< count
; n
++ )
2406 printf("\t%s\n", files
[n
].c_str());
2408 puts("End of the file list");
2411 if ( !ftp
.GetDirList(files
) )
2413 puts("ERROR: failed to get LIST of files");
2417 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2418 size_t count
= files
.GetCount();
2419 for ( size_t n
= 0; n
< count
; n
++ )
2421 printf("\t%s\n", files
[n
].c_str());
2423 puts("End of the file list");
2426 if ( !ftp
.ChDir(_T("..")) )
2428 puts("ERROR: failed to cd to ..");
2431 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2434 static void TestFtpDownload()
2436 puts("*** Testing wxFTP download ***\n");
2439 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2442 printf("ERROR: couldn't get input stream for %s\n", filename
);
2446 size_t size
= in
->StreamSize();
2447 printf("Reading file %s (%u bytes)...", filename
, size
);
2450 char *data
= new char[size
];
2451 if ( !in
->Read(data
, size
) )
2453 puts("ERROR: read error");
2457 printf("\nContents of %s:\n%s\n", filename
, data
);
2465 static void TestFtpFileSize()
2467 puts("*** Testing FTP SIZE command ***");
2469 if ( !ftp
.ChDir(directory
) )
2471 printf("ERROR: failed to cd to %s\n", directory
);
2474 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2476 if ( ftp
.FileExists(filename
) )
2478 int size
= ftp
.GetFileSize(filename
);
2480 printf("ERROR: couldn't get size of '%s'\n", filename
);
2482 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2486 printf("ERROR: '%s' doesn't exist\n", filename
);
2490 static void TestFtpMisc()
2492 puts("*** Testing miscellaneous wxFTP functions ***");
2494 if ( ftp
.SendCommand("STAT") != '2' )
2496 puts("ERROR: STAT failed");
2500 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2503 if ( ftp
.SendCommand("HELP SITE") != '2' )
2505 puts("ERROR: HELP SITE failed");
2509 printf("The list of site-specific commands:\n\n%s\n",
2510 ftp
.GetLastResult().c_str());
2514 static void TestFtpInteractive()
2516 puts("\n*** Interactive wxFTP test ***");
2522 printf("Enter FTP command: ");
2523 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2526 // kill the last '\n'
2527 buf
[strlen(buf
) - 1] = 0;
2529 // special handling of LIST and NLST as they require data connection
2530 wxString
start(buf
, 4);
2532 if ( start
== "LIST" || start
== "NLST" )
2535 if ( strlen(buf
) > 4 )
2538 wxArrayString files
;
2539 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2541 printf("ERROR: failed to get %s of files\n", start
.c_str());
2545 printf("--- %s of '%s' under '%s':\n",
2546 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2547 size_t count
= files
.GetCount();
2548 for ( size_t n
= 0; n
< count
; n
++ )
2550 printf("\t%s\n", files
[n
].c_str());
2552 puts("--- End of the file list");
2557 char ch
= ftp
.SendCommand(buf
);
2558 printf("Command %s", ch
? "succeeded" : "failed");
2561 printf(" (return code %c)", ch
);
2564 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2568 puts("\n*** done ***");
2571 static void TestFtpUpload()
2573 puts("*** Testing wxFTP uploading ***\n");
2576 static const char *file1
= "test1";
2577 static const char *file2
= "test2";
2578 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2581 printf("--- Uploading to %s ---\n", file1
);
2582 out
->Write("First hello", 11);
2586 // send a command to check the remote file
2587 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2589 printf("ERROR: STAT %s failed\n", file1
);
2593 printf("STAT %s returned:\n\n%s\n",
2594 file1
, ftp
.GetLastResult().c_str());
2597 out
= ftp
.GetOutputStream(file2
);
2600 printf("--- Uploading to %s ---\n", file1
);
2601 out
->Write("Second hello", 12);
2608 // ----------------------------------------------------------------------------
2610 // ----------------------------------------------------------------------------
2614 #include "wx/wfstream.h"
2615 #include "wx/mstream.h"
2617 static void TestFileStream()
2619 puts("*** Testing wxFileInputStream ***");
2621 static const wxChar
*filename
= _T("testdata.fs");
2623 wxFileOutputStream
fsOut(filename
);
2624 fsOut
.Write("foo", 3);
2627 wxFileInputStream
fsIn(filename
);
2628 printf("File stream size: %u\n", fsIn
.GetSize());
2629 while ( !fsIn
.Eof() )
2631 putchar(fsIn
.GetC());
2634 if ( !wxRemoveFile(filename
) )
2636 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2639 puts("\n*** wxFileInputStream test done ***");
2642 static void TestMemoryStream()
2644 puts("*** Testing wxMemoryInputStream ***");
2647 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2649 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2650 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2651 while ( !memInpStream
.Eof() )
2653 putchar(memInpStream
.GetC());
2656 puts("\n*** wxMemoryInputStream test done ***");
2659 #endif // TEST_STREAMS
2661 // ----------------------------------------------------------------------------
2663 // ----------------------------------------------------------------------------
2667 #include "wx/timer.h"
2668 #include "wx/utils.h"
2670 static void TestStopWatch()
2672 puts("*** Testing wxStopWatch ***\n");
2675 printf("Sleeping 3 seconds...");
2677 printf("\telapsed time: %ldms\n", sw
.Time());
2680 printf("Sleeping 2 more seconds...");
2682 printf("\telapsed time: %ldms\n", sw
.Time());
2685 printf("And 3 more seconds...");
2687 printf("\telapsed time: %ldms\n", sw
.Time());
2690 puts("\nChecking for 'backwards clock' bug...");
2691 for ( size_t n
= 0; n
< 70; n
++ )
2695 for ( size_t m
= 0; m
< 100000; m
++ )
2697 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2699 puts("\ntime is negative - ERROR!");
2709 #endif // TEST_TIMER
2711 // ----------------------------------------------------------------------------
2713 // ----------------------------------------------------------------------------
2717 #include "wx/vcard.h"
2719 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2722 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2726 wxString(_T('\t'), level
).c_str(),
2727 vcObj
->GetName().c_str());
2730 switch ( vcObj
->GetType() )
2732 case wxVCardObject::String
:
2733 case wxVCardObject::UString
:
2736 vcObj
->GetValue(&val
);
2737 value
<< _T('"') << val
<< _T('"');
2741 case wxVCardObject::Int
:
2744 vcObj
->GetValue(&i
);
2745 value
.Printf(_T("%u"), i
);
2749 case wxVCardObject::Long
:
2752 vcObj
->GetValue(&l
);
2753 value
.Printf(_T("%lu"), l
);
2757 case wxVCardObject::None
:
2760 case wxVCardObject::Object
:
2761 value
= _T("<node>");
2765 value
= _T("<unknown value type>");
2769 printf(" = %s", value
.c_str());
2772 DumpVObject(level
+ 1, *vcObj
);
2775 vcObj
= vcard
.GetNextProp(&cookie
);
2779 static void DumpVCardAddresses(const wxVCard
& vcard
)
2781 puts("\nShowing all addresses from vCard:\n");
2785 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2789 int flags
= addr
->GetFlags();
2790 if ( flags
& wxVCardAddress::Domestic
)
2792 flagsStr
<< _T("domestic ");
2794 if ( flags
& wxVCardAddress::Intl
)
2796 flagsStr
<< _T("international ");
2798 if ( flags
& wxVCardAddress::Postal
)
2800 flagsStr
<< _T("postal ");
2802 if ( flags
& wxVCardAddress::Parcel
)
2804 flagsStr
<< _T("parcel ");
2806 if ( flags
& wxVCardAddress::Home
)
2808 flagsStr
<< _T("home ");
2810 if ( flags
& wxVCardAddress::Work
)
2812 flagsStr
<< _T("work ");
2815 printf("Address %u:\n"
2817 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2820 addr
->GetPostOffice().c_str(),
2821 addr
->GetExtAddress().c_str(),
2822 addr
->GetStreet().c_str(),
2823 addr
->GetLocality().c_str(),
2824 addr
->GetRegion().c_str(),
2825 addr
->GetPostalCode().c_str(),
2826 addr
->GetCountry().c_str()
2830 addr
= vcard
.GetNextAddress(&cookie
);
2834 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2836 puts("\nShowing all phone numbers from vCard:\n");
2840 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2844 int flags
= phone
->GetFlags();
2845 if ( flags
& wxVCardPhoneNumber::Voice
)
2847 flagsStr
<< _T("voice ");
2849 if ( flags
& wxVCardPhoneNumber::Fax
)
2851 flagsStr
<< _T("fax ");
2853 if ( flags
& wxVCardPhoneNumber::Cellular
)
2855 flagsStr
<< _T("cellular ");
2857 if ( flags
& wxVCardPhoneNumber::Modem
)
2859 flagsStr
<< _T("modem ");
2861 if ( flags
& wxVCardPhoneNumber::Home
)
2863 flagsStr
<< _T("home ");
2865 if ( flags
& wxVCardPhoneNumber::Work
)
2867 flagsStr
<< _T("work ");
2870 printf("Phone number %u:\n"
2875 phone
->GetNumber().c_str()
2879 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2883 static void TestVCardRead()
2885 puts("*** Testing wxVCard reading ***\n");
2887 wxVCard
vcard(_T("vcard.vcf"));
2888 if ( !vcard
.IsOk() )
2890 puts("ERROR: couldn't load vCard.");
2894 // read individual vCard properties
2895 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2899 vcObj
->GetValue(&value
);
2904 value
= _T("<none>");
2907 printf("Full name retrieved directly: %s\n", value
.c_str());
2910 if ( !vcard
.GetFullName(&value
) )
2912 value
= _T("<none>");
2915 printf("Full name from wxVCard API: %s\n", value
.c_str());
2917 // now show how to deal with multiply occuring properties
2918 DumpVCardAddresses(vcard
);
2919 DumpVCardPhoneNumbers(vcard
);
2921 // and finally show all
2922 puts("\nNow dumping the entire vCard:\n"
2923 "-----------------------------\n");
2925 DumpVObject(0, vcard
);
2929 static void TestVCardWrite()
2931 puts("*** Testing wxVCard writing ***\n");
2934 if ( !vcard
.IsOk() )
2936 puts("ERROR: couldn't create vCard.");
2941 vcard
.SetName("Zeitlin", "Vadim");
2942 vcard
.SetFullName("Vadim Zeitlin");
2943 vcard
.SetOrganization("wxWindows", "R&D");
2945 // just dump the vCard back
2946 puts("Entire vCard follows:\n");
2947 puts(vcard
.Write());
2951 #endif // TEST_VCARD
2953 // ----------------------------------------------------------------------------
2954 // wide char (Unicode) support
2955 // ----------------------------------------------------------------------------
2959 #include "wx/strconv.h"
2960 #include "wx/fontenc.h"
2961 #include "wx/encconv.h"
2962 #include "wx/buffer.h"
2964 static void TestUtf8()
2966 puts("*** Testing UTF8 support ***\n");
2968 static const char textInUtf8
[] =
2970 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2971 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2972 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2973 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2974 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2975 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2976 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2981 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2983 puts("ERROR: UTF-8 decoding failed.");
2987 // using wxEncodingConverter
2989 wxEncodingConverter ec
;
2990 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2991 ec
.Convert(wbuf
, buf
);
2992 #else // using wxCSConv
2993 wxCSConv
conv(_T("koi8-r"));
2994 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2996 puts("ERROR: conversion to KOI8-R failed.");
3001 printf("The resulting string (in koi8-r): %s\n", buf
);
3005 #endif // TEST_WCHAR
3007 // ----------------------------------------------------------------------------
3009 // ----------------------------------------------------------------------------
3013 #include "wx/filesys.h"
3014 #include "wx/fs_zip.h"
3015 #include "wx/zipstrm.h"
3017 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3019 static void TestZipStreamRead()
3021 puts("*** Testing ZIP reading ***\n");
3023 static const wxChar
*filename
= _T("foo");
3024 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3025 printf("Archive size: %u\n", istr
.GetSize());
3027 printf("Dumping the file '%s':\n", filename
);
3028 while ( !istr
.Eof() )
3030 putchar(istr
.GetC());
3034 puts("\n----- done ------");
3037 static void DumpZipDirectory(wxFileSystem
& fs
,
3038 const wxString
& dir
,
3039 const wxString
& indent
)
3041 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3042 TESTFILE_ZIP
, dir
.c_str());
3043 wxString wildcard
= prefix
+ _T("/*");
3045 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3046 while ( !dirname
.empty() )
3048 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3050 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3055 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3057 DumpZipDirectory(fs
, dirname
,
3058 indent
+ wxString(_T(' '), 4));
3060 dirname
= fs
.FindNext();
3063 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3064 while ( !filename
.empty() )
3066 if ( !filename
.StartsWith(prefix
, &filename
) )
3068 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3073 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3075 filename
= fs
.FindNext();
3079 static void TestZipFileSystem()
3081 puts("*** Testing ZIP file system ***\n");
3083 wxFileSystem::AddHandler(new wxZipFSHandler
);
3085 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3087 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3092 // ----------------------------------------------------------------------------
3094 // ----------------------------------------------------------------------------
3098 #include "wx/zstream.h"
3099 #include "wx/wfstream.h"
3101 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3102 static const char *TEST_DATA
= "hello and hello again";
3104 static void TestZlibStreamWrite()
3106 puts("*** Testing Zlib stream reading ***\n");
3108 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3109 wxZlibOutputStream
ostr(fileOutStream
, 0);
3110 printf("Compressing the test string... ");
3111 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3114 puts("(ERROR: failed)");
3121 puts("\n----- done ------");
3124 static void TestZlibStreamRead()
3126 puts("*** Testing Zlib stream reading ***\n");
3128 wxFileInputStream
fileInStream(FILENAME_GZ
);
3129 wxZlibInputStream
istr(fileInStream
);
3130 printf("Archive size: %u\n", istr
.GetSize());
3132 puts("Dumping the file:");
3133 while ( !istr
.Eof() )
3135 putchar(istr
.GetC());
3139 puts("\n----- done ------");
3144 // ----------------------------------------------------------------------------
3146 // ----------------------------------------------------------------------------
3148 #ifdef TEST_DATETIME
3152 #include "wx/date.h"
3153 #include "wx/datetime.h"
3158 wxDateTime::wxDateTime_t day
;
3159 wxDateTime::Month month
;
3161 wxDateTime::wxDateTime_t hour
, min
, sec
;
3163 wxDateTime::WeekDay wday
;
3164 time_t gmticks
, ticks
;
3166 void Init(const wxDateTime::Tm
& tm
)
3175 gmticks
= ticks
= -1;
3178 wxDateTime
DT() const
3179 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3181 bool SameDay(const wxDateTime::Tm
& tm
) const
3183 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3186 wxString
Format() const
3189 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3191 wxDateTime::GetMonthName(month
).c_str(),
3193 abs(wxDateTime::ConvertYearToBC(year
)),
3194 year
> 0 ? "AD" : "BC");
3198 wxString
FormatDate() const
3201 s
.Printf("%02d-%s-%4d%s",
3203 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3204 abs(wxDateTime::ConvertYearToBC(year
)),
3205 year
> 0 ? "AD" : "BC");
3210 static const Date testDates
[] =
3212 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3213 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3214 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3215 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3216 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3217 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3218 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3219 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3220 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3221 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3222 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3223 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3224 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3225 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3226 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3229 // this test miscellaneous static wxDateTime functions
3230 static void TestTimeStatic()
3232 puts("\n*** wxDateTime static methods test ***");
3234 // some info about the current date
3235 int year
= wxDateTime::GetCurrentYear();
3236 printf("Current year %d is %sa leap one and has %d days.\n",
3238 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3239 wxDateTime::GetNumberOfDays(year
));
3241 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3242 printf("Current month is '%s' ('%s') and it has %d days\n",
3243 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3244 wxDateTime::GetMonthName(month
).c_str(),
3245 wxDateTime::GetNumberOfDays(month
));
3248 static const size_t nYears
= 5;
3249 static const size_t years
[2][nYears
] =
3251 // first line: the years to test
3252 { 1990, 1976, 2000, 2030, 1984, },
3254 // second line: TRUE if leap, FALSE otherwise
3255 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3258 for ( size_t n
= 0; n
< nYears
; n
++ )
3260 int year
= years
[0][n
];
3261 bool should
= years
[1][n
] != 0,
3262 is
= wxDateTime::IsLeapYear(year
);
3264 printf("Year %d is %sa leap year (%s)\n",
3267 should
== is
? "ok" : "ERROR");
3269 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3273 // test constructing wxDateTime objects
3274 static void TestTimeSet()
3276 puts("\n*** wxDateTime construction test ***");
3278 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3280 const Date
& d1
= testDates
[n
];
3281 wxDateTime dt
= d1
.DT();
3284 d2
.Init(dt
.GetTm());
3286 wxString s1
= d1
.Format(),
3289 printf("Date: %s == %s (%s)\n",
3290 s1
.c_str(), s2
.c_str(),
3291 s1
== s2
? "ok" : "ERROR");
3295 // test time zones stuff
3296 static void TestTimeZones()
3298 puts("\n*** wxDateTime timezone test ***");
3300 wxDateTime now
= wxDateTime::Now();
3302 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3303 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3304 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3305 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3306 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3307 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3309 wxDateTime::Tm tm
= now
.GetTm();
3310 if ( wxDateTime(tm
) != now
)
3312 printf("ERROR: got %s instead of %s\n",
3313 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3317 // test some minimal support for the dates outside the standard range
3318 static void TestTimeRange()
3320 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3322 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3324 printf("Unix epoch:\t%s\n",
3325 wxDateTime(2440587.5).Format(fmt
).c_str());
3326 printf("Feb 29, 0: \t%s\n",
3327 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3328 printf("JDN 0: \t%s\n",
3329 wxDateTime(0.0).Format(fmt
).c_str());
3330 printf("Jan 1, 1AD:\t%s\n",
3331 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3332 printf("May 29, 2099:\t%s\n",
3333 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3336 static void TestTimeTicks()
3338 puts("\n*** wxDateTime ticks test ***");
3340 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3342 const Date
& d
= testDates
[n
];
3343 if ( d
.ticks
== -1 )
3346 wxDateTime dt
= d
.DT();
3347 long ticks
= (dt
.GetValue() / 1000).ToLong();
3348 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3349 if ( ticks
== d
.ticks
)
3355 printf(" (ERROR: should be %ld, delta = %ld)\n",
3356 d
.ticks
, ticks
- d
.ticks
);
3359 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3360 ticks
= (dt
.GetValue() / 1000).ToLong();
3361 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3362 if ( ticks
== d
.gmticks
)
3368 printf(" (ERROR: should be %ld, delta = %ld)\n",
3369 d
.gmticks
, ticks
- d
.gmticks
);
3376 // test conversions to JDN &c
3377 static void TestTimeJDN()
3379 puts("\n*** wxDateTime to JDN test ***");
3381 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3383 const Date
& d
= testDates
[n
];
3384 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3385 double jdn
= dt
.GetJulianDayNumber();
3387 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3394 printf(" (ERROR: should be %f, delta = %f)\n",
3395 d
.jdn
, jdn
- d
.jdn
);
3400 // test week days computation
3401 static void TestTimeWDays()
3403 puts("\n*** wxDateTime weekday test ***");
3405 // test GetWeekDay()
3407 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3409 const Date
& d
= testDates
[n
];
3410 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3412 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3415 wxDateTime::GetWeekDayName(wday
).c_str());
3416 if ( wday
== d
.wday
)
3422 printf(" (ERROR: should be %s)\n",
3423 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3429 // test SetToWeekDay()
3430 struct WeekDateTestData
3432 Date date
; // the real date (precomputed)
3433 int nWeek
; // its week index in the month
3434 wxDateTime::WeekDay wday
; // the weekday
3435 wxDateTime::Month month
; // the month
3436 int year
; // and the year
3438 wxString
Format() const
3441 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3443 case 1: which
= "first"; break;
3444 case 2: which
= "second"; break;
3445 case 3: which
= "third"; break;
3446 case 4: which
= "fourth"; break;
3447 case 5: which
= "fifth"; break;
3449 case -1: which
= "last"; break;
3454 which
+= " from end";
3457 s
.Printf("The %s %s of %s in %d",
3459 wxDateTime::GetWeekDayName(wday
).c_str(),
3460 wxDateTime::GetMonthName(month
).c_str(),
3467 // the array data was generated by the following python program
3469 from DateTime import *
3470 from whrandom import *
3471 from string import *
3473 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3474 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3476 week = DateTimeDelta(7)
3479 year = randint(1900, 2100)
3480 month = randint(1, 12)
3481 day = randint(1, 28)
3482 dt = DateTime(year, month, day)
3483 wday = dt.day_of_week
3485 countFromEnd = choice([-1, 1])
3488 while dt.month is month:
3489 dt = dt - countFromEnd * week
3490 weekNum = weekNum + countFromEnd
3492 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3494 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3495 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3498 static const WeekDateTestData weekDatesTestData
[] =
3500 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3501 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3502 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3503 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3504 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3505 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3506 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3507 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3508 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3509 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3510 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3511 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3512 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3513 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3514 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3515 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3516 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3517 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3518 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3519 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3522 static const char *fmt
= "%d-%b-%Y";
3525 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3527 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3529 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3531 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3533 const Date
& d
= wd
.date
;
3534 if ( d
.SameDay(dt
.GetTm()) )
3540 dt
.Set(d
.day
, d
.month
, d
.year
);
3542 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3547 // test the computation of (ISO) week numbers
3548 static void TestTimeWNumber()
3550 puts("\n*** wxDateTime week number test ***");
3552 struct WeekNumberTestData
3554 Date date
; // the date
3555 wxDateTime::wxDateTime_t week
; // the week number in the year
3556 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3557 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3558 wxDateTime::wxDateTime_t dnum
; // day number in the year
3561 // data generated with the following python script:
3563 from DateTime import *
3564 from whrandom import *
3565 from string import *
3567 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3568 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3570 def GetMonthWeek(dt):
3571 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3572 if weekNumMonth < 0:
3573 weekNumMonth = weekNumMonth + 53
3576 def GetLastSundayBefore(dt):
3577 if dt.iso_week[2] == 7:
3580 return dt - DateTimeDelta(dt.iso_week[2])
3583 year = randint(1900, 2100)
3584 month = randint(1, 12)
3585 day = randint(1, 28)
3586 dt = DateTime(year, month, day)
3587 dayNum = dt.day_of_year
3588 weekNum = dt.iso_week[1]
3589 weekNumMonth = GetMonthWeek(dt)
3592 dtSunday = GetLastSundayBefore(dt)
3594 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3595 weekNumMonth2 = weekNumMonth2 + 1
3596 dtSunday = dtSunday - DateTimeDelta(7)
3598 data = { 'day': rjust(`day`, 2), \
3599 'month': monthNames[month - 1], \
3601 'weekNum': rjust(`weekNum`, 2), \
3602 'weekNumMonth': weekNumMonth, \
3603 'weekNumMonth2': weekNumMonth2, \
3604 'dayNum': rjust(`dayNum`, 3) }
3606 print " { { %(day)s, "\
3607 "wxDateTime::%(month)s, "\
3610 "%(weekNumMonth)s, "\
3611 "%(weekNumMonth2)s, "\
3612 "%(dayNum)s }," % data
3615 static const WeekNumberTestData weekNumberTestDates
[] =
3617 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3618 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3619 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3620 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3621 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3622 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3623 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3624 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3625 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3626 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3627 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3628 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3629 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3630 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3631 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3632 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3633 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3634 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3635 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3636 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3639 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3641 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3642 const Date
& d
= wn
.date
;
3644 wxDateTime dt
= d
.DT();
3646 wxDateTime::wxDateTime_t
3647 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3648 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3649 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3650 dnum
= dt
.GetDayOfYear();
3652 printf("%s: the day number is %d",
3653 d
.FormatDate().c_str(), dnum
);
3654 if ( dnum
== wn
.dnum
)
3660 printf(" (ERROR: should be %d)", wn
.dnum
);
3663 printf(", week in month is %d", wmon
);
3664 if ( wmon
== wn
.wmon
)
3670 printf(" (ERROR: should be %d)", wn
.wmon
);
3673 printf(" or %d", wmon2
);
3674 if ( wmon2
== wn
.wmon2
)
3680 printf(" (ERROR: should be %d)", wn
.wmon2
);
3683 printf(", week in year is %d", week
);
3684 if ( week
== wn
.week
)
3690 printf(" (ERROR: should be %d)\n", wn
.week
);
3695 // test DST calculations
3696 static void TestTimeDST()
3698 puts("\n*** wxDateTime DST test ***");
3700 printf("DST is%s in effect now.\n\n",
3701 wxDateTime::Now().IsDST() ? "" : " not");
3703 // taken from http://www.energy.ca.gov/daylightsaving.html
3704 static const Date datesDST
[2][2004 - 1900 + 1] =
3707 { 1, wxDateTime::Apr
, 1990 },
3708 { 7, wxDateTime::Apr
, 1991 },
3709 { 5, wxDateTime::Apr
, 1992 },
3710 { 4, wxDateTime::Apr
, 1993 },
3711 { 3, wxDateTime::Apr
, 1994 },
3712 { 2, wxDateTime::Apr
, 1995 },
3713 { 7, wxDateTime::Apr
, 1996 },
3714 { 6, wxDateTime::Apr
, 1997 },
3715 { 5, wxDateTime::Apr
, 1998 },
3716 { 4, wxDateTime::Apr
, 1999 },
3717 { 2, wxDateTime::Apr
, 2000 },
3718 { 1, wxDateTime::Apr
, 2001 },
3719 { 7, wxDateTime::Apr
, 2002 },
3720 { 6, wxDateTime::Apr
, 2003 },
3721 { 4, wxDateTime::Apr
, 2004 },
3724 { 28, wxDateTime::Oct
, 1990 },
3725 { 27, wxDateTime::Oct
, 1991 },
3726 { 25, wxDateTime::Oct
, 1992 },
3727 { 31, wxDateTime::Oct
, 1993 },
3728 { 30, wxDateTime::Oct
, 1994 },
3729 { 29, wxDateTime::Oct
, 1995 },
3730 { 27, wxDateTime::Oct
, 1996 },
3731 { 26, wxDateTime::Oct
, 1997 },
3732 { 25, wxDateTime::Oct
, 1998 },
3733 { 31, wxDateTime::Oct
, 1999 },
3734 { 29, wxDateTime::Oct
, 2000 },
3735 { 28, wxDateTime::Oct
, 2001 },
3736 { 27, wxDateTime::Oct
, 2002 },
3737 { 26, wxDateTime::Oct
, 2003 },
3738 { 31, wxDateTime::Oct
, 2004 },
3743 for ( year
= 1990; year
< 2005; year
++ )
3745 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3746 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3748 printf("DST period in the US for year %d: from %s to %s",
3749 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3751 size_t n
= year
- 1990;
3752 const Date
& dBegin
= datesDST
[0][n
];
3753 const Date
& dEnd
= datesDST
[1][n
];
3755 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3761 printf(" (ERROR: should be %s %d to %s %d)\n",
3762 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3763 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3769 for ( year
= 1990; year
< 2005; year
++ )
3771 printf("DST period in Europe for year %d: from %s to %s\n",
3773 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3774 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3778 // test wxDateTime -> text conversion
3779 static void TestTimeFormat()
3781 puts("\n*** wxDateTime formatting test ***");
3783 // some information may be lost during conversion, so store what kind
3784 // of info should we recover after a round trip
3787 CompareNone
, // don't try comparing
3788 CompareBoth
, // dates and times should be identical
3789 CompareDate
, // dates only
3790 CompareTime
// time only
3795 CompareKind compareKind
;
3797 } formatTestFormats
[] =
3799 { CompareBoth
, "---> %c" },
3800 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3801 { CompareBoth
, "Date is %x, time is %X" },
3802 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3803 { CompareNone
, "The day of year: %j, the week of year: %W" },
3804 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3807 static const Date formatTestDates
[] =
3809 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3810 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3812 // this test can't work for other centuries because it uses two digit
3813 // years in formats, so don't even try it
3814 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3815 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3816 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3820 // an extra test (as it doesn't depend on date, don't do it in the loop)
3821 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3823 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3827 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3828 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3830 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3831 printf("%s", s
.c_str());
3833 // what can we recover?
3834 int kind
= formatTestFormats
[n
].compareKind
;
3838 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3841 // converion failed - should it have?
3842 if ( kind
== CompareNone
)
3845 puts(" (ERROR: conversion back failed)");
3849 // should have parsed the entire string
3850 puts(" (ERROR: conversion back stopped too soon)");
3854 bool equal
= FALSE
; // suppress compilaer warning
3862 equal
= dt
.IsSameDate(dt2
);
3866 equal
= dt
.IsSameTime(dt2
);
3872 printf(" (ERROR: got back '%s' instead of '%s')\n",
3873 dt2
.Format().c_str(), dt
.Format().c_str());
3884 // test text -> wxDateTime conversion
3885 static void TestTimeParse()
3887 puts("\n*** wxDateTime parse test ***");
3889 struct ParseTestData
3896 static const ParseTestData parseTestDates
[] =
3898 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3899 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3902 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3904 const char *format
= parseTestDates
[n
].format
;
3906 printf("%s => ", format
);
3909 if ( dt
.ParseRfc822Date(format
) )
3911 printf("%s ", dt
.Format().c_str());
3913 if ( parseTestDates
[n
].good
)
3915 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3922 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3927 puts("(ERROR: bad format)");
3932 printf("bad format (%s)\n",
3933 parseTestDates
[n
].good
? "ERROR" : "ok");
3938 static void TestDateTimeInteractive()
3940 puts("\n*** interactive wxDateTime tests ***");
3946 printf("Enter a date: ");
3947 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3950 // kill the last '\n'
3951 buf
[strlen(buf
) - 1] = 0;
3954 const char *p
= dt
.ParseDate(buf
);
3957 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3963 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3966 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3967 dt
.Format("%b %d, %Y").c_str(),
3969 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3970 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3971 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3974 puts("\n*** done ***");
3977 static void TestTimeMS()
3979 puts("*** testing millisecond-resolution support in wxDateTime ***");
3981 wxDateTime dt1
= wxDateTime::Now(),
3982 dt2
= wxDateTime::UNow();
3984 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3985 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3986 printf("Dummy loop: ");
3987 for ( int i
= 0; i
< 6000; i
++ )
3989 //for ( int j = 0; j < 10; j++ )
3992 s
.Printf("%g", sqrt(i
));
4001 dt2
= wxDateTime::UNow();
4002 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4004 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4006 puts("\n*** done ***");
4009 static void TestTimeArithmetics()
4011 puts("\n*** testing arithmetic operations on wxDateTime ***");
4013 static const struct ArithmData
4015 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4016 : span(sp
), name(nam
) { }
4020 } testArithmData
[] =
4022 ArithmData(wxDateSpan::Day(), "day"),
4023 ArithmData(wxDateSpan::Week(), "week"),
4024 ArithmData(wxDateSpan::Month(), "month"),
4025 ArithmData(wxDateSpan::Year(), "year"),
4026 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4029 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4031 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4033 wxDateSpan span
= testArithmData
[n
].span
;
4037 const char *name
= testArithmData
[n
].name
;
4038 printf("%s + %s = %s, %s - %s = %s\n",
4039 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4040 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4042 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4043 if ( dt1
- span
== dt
)
4049 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4052 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4053 if ( dt2
+ span
== dt
)
4059 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4062 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4063 if ( dt2
+ 2*span
== dt1
)
4069 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4076 static void TestTimeHolidays()
4078 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4080 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4081 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4082 dtEnd
= dtStart
.GetLastMonthDay();
4084 wxDateTimeArray hol
;
4085 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4087 const wxChar
*format
= "%d-%b-%Y (%a)";
4089 printf("All holidays between %s and %s:\n",
4090 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4092 size_t count
= hol
.GetCount();
4093 for ( size_t n
= 0; n
< count
; n
++ )
4095 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4101 static void TestTimeZoneBug()
4103 puts("\n*** testing for DST/timezone bug ***\n");
4105 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4106 for ( int i
= 0; i
< 31; i
++ )
4108 printf("Date %s: week day %s.\n",
4109 date
.Format(_T("%d-%m-%Y")).c_str(),
4110 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4112 date
+= wxDateSpan::Day();
4118 static void TestTimeSpanFormat()
4120 puts("\n*** wxTimeSpan tests ***");
4122 static const char *formats
[] =
4124 _T("(default) %H:%M:%S"),
4125 _T("%E weeks and %D days"),
4126 _T("%l milliseconds"),
4127 _T("(with ms) %H:%M:%S:%l"),
4128 _T("100%% of minutes is %M"), // test "%%"
4129 _T("%D days and %H hours"),
4130 _T("or also %S seconds"),
4133 wxTimeSpan
ts1(1, 2, 3, 4),
4135 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4137 printf("ts1 = %s\tts2 = %s\n",
4138 ts1
.Format(formats
[n
]).c_str(),
4139 ts2
.Format(formats
[n
]).c_str());
4147 // test compatibility with the old wxDate/wxTime classes
4148 static void TestTimeCompatibility()
4150 puts("\n*** wxDateTime compatibility test ***");
4152 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4153 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4155 double jdnNow
= wxDateTime::Now().GetJDN();
4156 long jdnMidnight
= (long)(jdnNow
- 0.5);
4157 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4159 jdnMidnight
= wxDate().Set().GetJulianDate();
4160 printf("wxDateTime for today: %s\n",
4161 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4163 int flags
= wxEUROPEAN
;//wxFULL;
4166 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4167 for ( int n
= 0; n
< 7; n
++ )
4169 printf("Previous %s is %s\n",
4170 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4171 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4177 #endif // TEST_DATETIME
4179 // ----------------------------------------------------------------------------
4181 // ----------------------------------------------------------------------------
4185 #include "wx/thread.h"
4187 static size_t gs_counter
= (size_t)-1;
4188 static wxCriticalSection gs_critsect
;
4189 static wxCondition gs_cond
;
4191 class MyJoinableThread
: public wxThread
4194 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4195 { m_n
= n
; Create(); }
4197 // thread execution starts here
4198 virtual ExitCode
Entry();
4204 wxThread::ExitCode
MyJoinableThread::Entry()
4206 unsigned long res
= 1;
4207 for ( size_t n
= 1; n
< m_n
; n
++ )
4211 // it's a loooong calculation :-)
4215 return (ExitCode
)res
;
4218 class MyDetachedThread
: public wxThread
4221 MyDetachedThread(size_t n
, char ch
)
4225 m_cancelled
= FALSE
;
4230 // thread execution starts here
4231 virtual ExitCode
Entry();
4234 virtual void OnExit();
4237 size_t m_n
; // number of characters to write
4238 char m_ch
; // character to write
4240 bool m_cancelled
; // FALSE if we exit normally
4243 wxThread::ExitCode
MyDetachedThread::Entry()
4246 wxCriticalSectionLocker
lock(gs_critsect
);
4247 if ( gs_counter
== (size_t)-1 )
4253 for ( size_t n
= 0; n
< m_n
; n
++ )
4255 if ( TestDestroy() )
4265 wxThread::Sleep(100);
4271 void MyDetachedThread::OnExit()
4273 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4275 wxCriticalSectionLocker
lock(gs_critsect
);
4276 if ( !--gs_counter
&& !m_cancelled
)
4280 void TestDetachedThreads()
4282 puts("\n*** Testing detached threads ***");
4284 static const size_t nThreads
= 3;
4285 MyDetachedThread
*threads
[nThreads
];
4287 for ( n
= 0; n
< nThreads
; n
++ )
4289 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4292 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4293 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4295 for ( n
= 0; n
< nThreads
; n
++ )
4300 // wait until all threads terminate
4306 void TestJoinableThreads()
4308 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4310 // calc 10! in the background
4311 MyJoinableThread
thread(10);
4314 printf("\nThread terminated with exit code %lu.\n",
4315 (unsigned long)thread
.Wait());
4318 void TestThreadSuspend()
4320 puts("\n*** Testing thread suspend/resume functions ***");
4322 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4326 // this is for this demo only, in a real life program we'd use another
4327 // condition variable which would be signaled from wxThread::Entry() to
4328 // tell us that the thread really started running - but here just wait a
4329 // bit and hope that it will be enough (the problem is, of course, that
4330 // the thread might still not run when we call Pause() which will result
4332 wxThread::Sleep(300);
4334 for ( size_t n
= 0; n
< 3; n
++ )
4338 puts("\nThread suspended");
4341 // don't sleep but resume immediately the first time
4342 wxThread::Sleep(300);
4344 puts("Going to resume the thread");
4349 puts("Waiting until it terminates now");
4351 // wait until the thread terminates
4357 void TestThreadDelete()
4359 // As above, using Sleep() is only for testing here - we must use some
4360 // synchronisation object instead to ensure that the thread is still
4361 // running when we delete it - deleting a detached thread which already
4362 // terminated will lead to a crash!
4364 puts("\n*** Testing thread delete function ***");
4366 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4370 puts("\nDeleted a thread which didn't start to run yet.");
4372 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4376 wxThread::Sleep(300);
4380 puts("\nDeleted a running thread.");
4382 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4386 wxThread::Sleep(300);
4392 puts("\nDeleted a sleeping thread.");
4394 MyJoinableThread
thread3(20);
4399 puts("\nDeleted a joinable thread.");
4401 MyJoinableThread
thread4(2);
4404 wxThread::Sleep(300);
4408 puts("\nDeleted a joinable thread which already terminated.");
4413 #endif // TEST_THREADS
4415 // ----------------------------------------------------------------------------
4417 // ----------------------------------------------------------------------------
4421 static void PrintArray(const char* name
, const wxArrayString
& array
)
4423 printf("Dump of the array '%s'\n", name
);
4425 size_t nCount
= array
.GetCount();
4426 for ( size_t n
= 0; n
< nCount
; n
++ )
4428 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4432 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4434 printf("Dump of the array '%s'\n", name
);
4436 size_t nCount
= array
.GetCount();
4437 for ( size_t n
= 0; n
< nCount
; n
++ )
4439 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4443 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4444 const wxString
& second
)
4446 return first
.length() - second
.length();
4449 int wxCMPFUNC_CONV
IntCompare(int *first
,
4452 return *first
- *second
;
4455 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4458 return *second
- *first
;
4461 static void TestArrayOfInts()
4463 puts("*** Testing wxArrayInt ***\n");
4474 puts("After sort:");
4478 puts("After reverse sort:");
4479 a
.Sort(IntRevCompare
);
4483 #include "wx/dynarray.h"
4485 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4486 #include "wx/arrimpl.cpp"
4487 WX_DEFINE_OBJARRAY(ArrayBars
);
4489 static void TestArrayOfObjects()
4491 puts("*** Testing wxObjArray ***\n");
4495 Bar
bar("second bar");
4497 printf("Initially: %u objects in the array, %u objects total.\n",
4498 bars
.GetCount(), Bar::GetNumber());
4500 bars
.Add(new Bar("first bar"));
4503 printf("Now: %u objects in the array, %u objects total.\n",
4504 bars
.GetCount(), Bar::GetNumber());
4508 printf("After Empty(): %u objects in the array, %u objects total.\n",
4509 bars
.GetCount(), Bar::GetNumber());
4512 printf("Finally: no more objects in the array, %u objects total.\n",
4516 #endif // TEST_ARRAYS
4518 // ----------------------------------------------------------------------------
4520 // ----------------------------------------------------------------------------
4524 #include "wx/timer.h"
4525 #include "wx/tokenzr.h"
4527 static void TestStringConstruction()
4529 puts("*** Testing wxString constructores ***");
4531 #define TEST_CTOR(args, res) \
4534 printf("wxString%s = %s ", #args, s.c_str()); \
4541 printf("(ERROR: should be %s)\n", res); \
4545 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4546 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4547 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4548 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4550 static const wxChar
*s
= _T("?really!");
4551 const wxChar
*start
= wxStrchr(s
, _T('r'));
4552 const wxChar
*end
= wxStrchr(s
, _T('!'));
4553 TEST_CTOR((start
, end
), _T("really"));
4558 static void TestString()
4568 for (int i
= 0; i
< 1000000; ++i
)
4572 c
= "! How'ya doin'?";
4575 c
= "Hello world! What's up?";
4580 printf ("TestString elapsed time: %ld\n", sw
.Time());
4583 static void TestPChar()
4591 for (int i
= 0; i
< 1000000; ++i
)
4593 strcpy (a
, "Hello");
4594 strcpy (b
, " world");
4595 strcpy (c
, "! How'ya doin'?");
4598 strcpy (c
, "Hello world! What's up?");
4599 if (strcmp (c
, a
) == 0)
4603 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4606 static void TestStringSub()
4608 wxString
s("Hello, world!");
4610 puts("*** Testing wxString substring extraction ***");
4612 printf("String = '%s'\n", s
.c_str());
4613 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4614 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4615 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4616 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4617 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4618 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4620 static const wxChar
*prefixes
[] =
4624 _T("Hello, world!"),
4625 _T("Hello, world!!!"),
4631 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4633 wxString prefix
= prefixes
[n
], rest
;
4634 bool rc
= s
.StartsWith(prefix
, &rest
);
4635 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4638 printf(" (the rest is '%s')\n", rest
.c_str());
4649 static void TestStringFormat()
4651 puts("*** Testing wxString formatting ***");
4654 s
.Printf("%03d", 18);
4656 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4657 printf("Number 18: %s\n", s
.c_str());
4662 // returns "not found" for npos, value for all others
4663 static wxString
PosToString(size_t res
)
4665 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4666 : wxString::Format(_T("%u"), res
);
4670 static void TestStringFind()
4672 puts("*** Testing wxString find() functions ***");
4674 static const wxChar
*strToFind
= _T("ell");
4675 static const struct StringFindTest
4679 result
; // of searching "ell" in str
4682 { _T("Well, hello world"), 0, 1 },
4683 { _T("Well, hello world"), 6, 7 },
4684 { _T("Well, hello world"), 9, wxString::npos
},
4687 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4689 const StringFindTest
& ft
= findTestData
[n
];
4690 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4692 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4693 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4695 size_t resTrue
= ft
.result
;
4696 if ( res
== resTrue
)
4702 printf(_T("(ERROR: should be %s)\n"),
4703 PosToString(resTrue
).c_str());
4710 static void TestStringTokenizer()
4712 puts("*** Testing wxStringTokenizer ***");
4714 static const wxChar
*modeNames
[] =
4718 _T("return all empty"),
4723 static const struct StringTokenizerTest
4725 const wxChar
*str
; // string to tokenize
4726 const wxChar
*delims
; // delimiters to use
4727 size_t count
; // count of token
4728 wxStringTokenizerMode mode
; // how should we tokenize it
4729 } tokenizerTestData
[] =
4731 { _T(""), _T(" "), 0 },
4732 { _T("Hello, world"), _T(" "), 2 },
4733 { _T("Hello, world "), _T(" "), 2 },
4734 { _T("Hello, world"), _T(","), 2 },
4735 { _T("Hello, world!"), _T(",!"), 2 },
4736 { _T("Hello,, world!"), _T(",!"), 3 },
4737 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4738 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4739 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4740 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4741 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4742 { _T("01/02/99"), _T("/-"), 3 },
4743 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4746 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4748 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4749 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4751 size_t count
= tkz
.CountTokens();
4752 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4753 MakePrintable(tt
.str
).c_str(),
4755 MakePrintable(tt
.delims
).c_str(),
4756 modeNames
[tkz
.GetMode()]);
4757 if ( count
== tt
.count
)
4763 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4768 // if we emulate strtok(), check that we do it correctly
4769 wxChar
*buf
, *s
= NULL
, *last
;
4771 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4773 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4774 wxStrcpy(buf
, tt
.str
);
4776 s
= wxStrtok(buf
, tt
.delims
, &last
);
4783 // now show the tokens themselves
4785 while ( tkz
.HasMoreTokens() )
4787 wxString token
= tkz
.GetNextToken();
4789 printf(_T("\ttoken %u: '%s'"),
4791 MakePrintable(token
).c_str());
4801 printf(" (ERROR: should be %s)\n", s
);
4804 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4808 // nothing to compare with
4813 if ( count2
!= count
)
4815 puts(_T("\tERROR: token count mismatch"));
4824 static void TestStringReplace()
4826 puts("*** Testing wxString::replace ***");
4828 static const struct StringReplaceTestData
4830 const wxChar
*original
; // original test string
4831 size_t start
, len
; // the part to replace
4832 const wxChar
*replacement
; // the replacement string
4833 const wxChar
*result
; // and the expected result
4834 } stringReplaceTestData
[] =
4836 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4837 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4838 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4839 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4840 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4843 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4845 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4847 wxString original
= data
.original
;
4848 original
.replace(data
.start
, data
.len
, data
.replacement
);
4850 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4851 data
.original
, data
.start
, data
.len
, data
.replacement
,
4854 if ( original
== data
.result
)
4860 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4867 static void TestStringMatch()
4869 wxPuts(_T("*** Testing wxString::Matches() ***"));
4871 static const struct StringMatchTestData
4874 const wxChar
*wildcard
;
4876 } stringMatchTestData
[] =
4878 { _T("foobar"), _T("foo*"), 1 },
4879 { _T("foobar"), _T("*oo*"), 1 },
4880 { _T("foobar"), _T("*bar"), 1 },
4881 { _T("foobar"), _T("??????"), 1 },
4882 { _T("foobar"), _T("f??b*"), 1 },
4883 { _T("foobar"), _T("f?b*"), 0 },
4884 { _T("foobar"), _T("*goo*"), 0 },
4885 { _T("foobar"), _T("*foo"), 0 },
4886 { _T("foobarfoo"), _T("*foo"), 1 },
4887 { _T(""), _T("*"), 1 },
4888 { _T(""), _T("?"), 0 },
4891 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4893 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4894 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4895 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4897 matches
? _T("matches") : _T("doesn't match"),
4899 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4905 #endif // TEST_STRINGS
4907 // ----------------------------------------------------------------------------
4909 // ----------------------------------------------------------------------------
4911 int main(int argc
, char **argv
)
4913 wxInitializer initializer
;
4916 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4921 #ifdef TEST_SNGLINST
4922 wxSingleInstanceChecker checker
;
4923 if ( checker
.Create(_T(".wxconsole.lock")) )
4925 if ( checker
.IsAnotherRunning() )
4927 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4932 // wait some time to give time to launch another instance
4933 wxPrintf(_T("Press \"Enter\" to continue..."));
4936 else // failed to create
4938 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4940 #endif // TEST_SNGLINST
4944 #endif // TEST_CHARSET
4947 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4949 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
4950 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4951 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4952 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4954 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4955 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4956 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
4957 wxCMD_LINE_VAL_NUMBER
},
4958 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
4959 wxCMD_LINE_VAL_DATE
},
4961 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4962 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4967 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4969 parser
.AddOption("project_name", "", "full path to project file",
4970 wxCMD_LINE_VAL_STRING
,
4971 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4973 switch ( parser
.Parse() )
4976 wxLogMessage("Help was given, terminating.");
4980 ShowCmdLine(parser
);
4984 wxLogMessage("Syntax error detected, aborting.");
4987 #endif // TEST_CMDLINE
4995 TestStringConstruction();
4998 TestStringTokenizer();
4999 TestStringReplace();
5002 #endif // TEST_STRINGS
5015 puts("*** Initially:");
5017 PrintArray("a1", a1
);
5019 wxArrayString
a2(a1
);
5020 PrintArray("a2", a2
);
5022 wxSortedArrayString
a3(a1
);
5023 PrintArray("a3", a3
);
5025 puts("*** After deleting a string from a1");
5028 PrintArray("a1", a1
);
5029 PrintArray("a2", a2
);
5030 PrintArray("a3", a3
);
5032 puts("*** After reassigning a1 to a2 and a3");
5034 PrintArray("a2", a2
);
5035 PrintArray("a3", a3
);
5037 puts("*** After sorting a1");
5039 PrintArray("a1", a1
);
5041 puts("*** After sorting a1 in reverse order");
5043 PrintArray("a1", a1
);
5045 puts("*** After sorting a1 by the string length");
5046 a1
.Sort(StringLenCompare
);
5047 PrintArray("a1", a1
);
5049 TestArrayOfObjects();
5052 #endif // TEST_ARRAYS
5060 #ifdef TEST_DLLLOADER
5062 #endif // TEST_DLLLOADER
5066 #endif // TEST_ENVIRON
5070 #endif // TEST_EXECUTE
5072 #ifdef TEST_FILECONF
5074 #endif // TEST_FILECONF
5082 #endif // TEST_LOCALE
5086 for ( size_t n
= 0; n
< 8000; n
++ )
5088 s
<< (char)('A' + (n
% 26));
5092 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5094 // this one shouldn't be truncated
5097 // but this one will because log functions use fixed size buffer
5098 // (note that it doesn't need '\n' at the end neither - will be added
5100 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5112 #ifdef TEST_FILENAME
5113 TestFileNameSplit();
5116 TestFileNameConstruction();
5118 TestFileNameComparison();
5119 TestFileNameOperations();
5121 #endif // TEST_FILENAME
5123 #ifdef TEST_FILETIME
5126 #endif // TEST_FILETIME
5129 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5130 if ( TestFtpConnect() )
5141 TestFtpInteractive();
5143 //else: connecting to the FTP server failed
5150 int nCPUs
= wxThread::GetCPUCount();
5151 printf("This system has %d CPUs\n", nCPUs
);
5153 wxThread::SetConcurrency(nCPUs
);
5155 if ( argc
> 1 && argv
[1][0] == 't' )
5156 wxLog::AddTraceMask("thread");
5159 TestDetachedThreads();
5161 TestJoinableThreads();
5163 TestThreadSuspend();
5167 #endif // TEST_THREADS
5169 #ifdef TEST_LONGLONG
5170 // seed pseudo random generator
5171 srand((unsigned)time(NULL
));
5179 TestMultiplication();
5182 TestLongLongConversion();
5183 TestBitOperations();
5184 TestLongLongComparison();
5186 TestLongLongPrint();
5187 #endif // TEST_LONGLONG
5194 wxLog::AddTraceMask(_T("mime"));
5202 TestMimeAssociate();
5205 #ifdef TEST_INFO_FUNCTIONS
5212 #endif // TEST_INFO_FUNCTIONS
5214 #ifdef TEST_PATHLIST
5216 #endif // TEST_PATHLIST
5220 #endif // TEST_REGCONF
5223 // TODO: write a real test using src/regex/tests file
5228 TestRegExSubmatch();
5229 TestRegExInteractive();
5231 TestRegExReplacement();
5232 #endif // TEST_REGEX
5234 #ifdef TEST_REGISTRY
5237 TestRegistryAssociation();
5238 #endif // TEST_REGISTRY
5246 #endif // TEST_SOCKETS
5252 #endif // TEST_STREAMS
5256 #endif // TEST_TIMER
5258 #ifdef TEST_DATETIME
5271 TestTimeArithmetics();
5278 TestTimeSpanFormat();
5280 TestDateTimeInteractive();
5281 #endif // TEST_DATETIME
5284 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5286 #endif // TEST_USLEEP
5292 #endif // TEST_VCARD
5296 #endif // TEST_WCHAR
5300 TestZipStreamRead();
5301 TestZipFileSystem();
5306 TestZlibStreamWrite();
5307 TestZlibStreamRead();