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
)(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>
3154 #include <wx/datetime.h>
3159 wxDateTime::wxDateTime_t day
;
3160 wxDateTime::Month month
;
3162 wxDateTime::wxDateTime_t hour
, min
, sec
;
3164 wxDateTime::WeekDay wday
;
3165 time_t gmticks
, ticks
;
3167 void Init(const wxDateTime::Tm
& tm
)
3176 gmticks
= ticks
= -1;
3179 wxDateTime
DT() const
3180 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3182 bool SameDay(const wxDateTime::Tm
& tm
) const
3184 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3187 wxString
Format() const
3190 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3192 wxDateTime::GetMonthName(month
).c_str(),
3194 abs(wxDateTime::ConvertYearToBC(year
)),
3195 year
> 0 ? "AD" : "BC");
3199 wxString
FormatDate() const
3202 s
.Printf("%02d-%s-%4d%s",
3204 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3205 abs(wxDateTime::ConvertYearToBC(year
)),
3206 year
> 0 ? "AD" : "BC");
3211 static const Date testDates
[] =
3213 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3214 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3215 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3216 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3217 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3218 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3219 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3220 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3221 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3222 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3223 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3224 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3225 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3226 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3227 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3230 // this test miscellaneous static wxDateTime functions
3231 static void TestTimeStatic()
3233 puts("\n*** wxDateTime static methods test ***");
3235 // some info about the current date
3236 int year
= wxDateTime::GetCurrentYear();
3237 printf("Current year %d is %sa leap one and has %d days.\n",
3239 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3240 wxDateTime::GetNumberOfDays(year
));
3242 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3243 printf("Current month is '%s' ('%s') and it has %d days\n",
3244 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3245 wxDateTime::GetMonthName(month
).c_str(),
3246 wxDateTime::GetNumberOfDays(month
));
3249 static const size_t nYears
= 5;
3250 static const size_t years
[2][nYears
] =
3252 // first line: the years to test
3253 { 1990, 1976, 2000, 2030, 1984, },
3255 // second line: TRUE if leap, FALSE otherwise
3256 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3259 for ( size_t n
= 0; n
< nYears
; n
++ )
3261 int year
= years
[0][n
];
3262 bool should
= years
[1][n
] != 0,
3263 is
= wxDateTime::IsLeapYear(year
);
3265 printf("Year %d is %sa leap year (%s)\n",
3268 should
== is
? "ok" : "ERROR");
3270 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3274 // test constructing wxDateTime objects
3275 static void TestTimeSet()
3277 puts("\n*** wxDateTime construction test ***");
3279 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3281 const Date
& d1
= testDates
[n
];
3282 wxDateTime dt
= d1
.DT();
3285 d2
.Init(dt
.GetTm());
3287 wxString s1
= d1
.Format(),
3290 printf("Date: %s == %s (%s)\n",
3291 s1
.c_str(), s2
.c_str(),
3292 s1
== s2
? "ok" : "ERROR");
3296 // test time zones stuff
3297 static void TestTimeZones()
3299 puts("\n*** wxDateTime timezone test ***");
3301 wxDateTime now
= wxDateTime::Now();
3303 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3304 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3305 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3306 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3307 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3308 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3310 wxDateTime::Tm tm
= now
.GetTm();
3311 if ( wxDateTime(tm
) != now
)
3313 printf("ERROR: got %s instead of %s\n",
3314 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3318 // test some minimal support for the dates outside the standard range
3319 static void TestTimeRange()
3321 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3323 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3325 printf("Unix epoch:\t%s\n",
3326 wxDateTime(2440587.5).Format(fmt
).c_str());
3327 printf("Feb 29, 0: \t%s\n",
3328 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3329 printf("JDN 0: \t%s\n",
3330 wxDateTime(0.0).Format(fmt
).c_str());
3331 printf("Jan 1, 1AD:\t%s\n",
3332 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3333 printf("May 29, 2099:\t%s\n",
3334 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3337 static void TestTimeTicks()
3339 puts("\n*** wxDateTime ticks test ***");
3341 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3343 const Date
& d
= testDates
[n
];
3344 if ( d
.ticks
== -1 )
3347 wxDateTime dt
= d
.DT();
3348 long ticks
= (dt
.GetValue() / 1000).ToLong();
3349 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3350 if ( ticks
== d
.ticks
)
3356 printf(" (ERROR: should be %ld, delta = %ld)\n",
3357 d
.ticks
, ticks
- d
.ticks
);
3360 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3361 ticks
= (dt
.GetValue() / 1000).ToLong();
3362 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3363 if ( ticks
== d
.gmticks
)
3369 printf(" (ERROR: should be %ld, delta = %ld)\n",
3370 d
.gmticks
, ticks
- d
.gmticks
);
3377 // test conversions to JDN &c
3378 static void TestTimeJDN()
3380 puts("\n*** wxDateTime to JDN test ***");
3382 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3384 const Date
& d
= testDates
[n
];
3385 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3386 double jdn
= dt
.GetJulianDayNumber();
3388 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3395 printf(" (ERROR: should be %f, delta = %f)\n",
3396 d
.jdn
, jdn
- d
.jdn
);
3401 // test week days computation
3402 static void TestTimeWDays()
3404 puts("\n*** wxDateTime weekday test ***");
3406 // test GetWeekDay()
3408 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3410 const Date
& d
= testDates
[n
];
3411 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3413 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3416 wxDateTime::GetWeekDayName(wday
).c_str());
3417 if ( wday
== d
.wday
)
3423 printf(" (ERROR: should be %s)\n",
3424 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3430 // test SetToWeekDay()
3431 struct WeekDateTestData
3433 Date date
; // the real date (precomputed)
3434 int nWeek
; // its week index in the month
3435 wxDateTime::WeekDay wday
; // the weekday
3436 wxDateTime::Month month
; // the month
3437 int year
; // and the year
3439 wxString
Format() const
3442 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3444 case 1: which
= "first"; break;
3445 case 2: which
= "second"; break;
3446 case 3: which
= "third"; break;
3447 case 4: which
= "fourth"; break;
3448 case 5: which
= "fifth"; break;
3450 case -1: which
= "last"; break;
3455 which
+= " from end";
3458 s
.Printf("The %s %s of %s in %d",
3460 wxDateTime::GetWeekDayName(wday
).c_str(),
3461 wxDateTime::GetMonthName(month
).c_str(),
3468 // the array data was generated by the following python program
3470 from DateTime import *
3471 from whrandom import *
3472 from string import *
3474 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3475 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3477 week = DateTimeDelta(7)
3480 year = randint(1900, 2100)
3481 month = randint(1, 12)
3482 day = randint(1, 28)
3483 dt = DateTime(year, month, day)
3484 wday = dt.day_of_week
3486 countFromEnd = choice([-1, 1])
3489 while dt.month is month:
3490 dt = dt - countFromEnd * week
3491 weekNum = weekNum + countFromEnd
3493 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3495 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3496 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3499 static const WeekDateTestData weekDatesTestData
[] =
3501 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3502 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3503 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3504 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3505 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3506 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3507 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3508 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3509 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3510 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3511 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3512 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3513 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3514 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3515 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3516 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3517 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3518 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3519 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3520 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3523 static const char *fmt
= "%d-%b-%Y";
3526 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3528 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3530 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3532 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3534 const Date
& d
= wd
.date
;
3535 if ( d
.SameDay(dt
.GetTm()) )
3541 dt
.Set(d
.day
, d
.month
, d
.year
);
3543 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3548 // test the computation of (ISO) week numbers
3549 static void TestTimeWNumber()
3551 puts("\n*** wxDateTime week number test ***");
3553 struct WeekNumberTestData
3555 Date date
; // the date
3556 wxDateTime::wxDateTime_t week
; // the week number in the year
3557 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3558 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3559 wxDateTime::wxDateTime_t dnum
; // day number in the year
3562 // data generated with the following python script:
3564 from DateTime import *
3565 from whrandom import *
3566 from string import *
3568 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3569 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3571 def GetMonthWeek(dt):
3572 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3573 if weekNumMonth < 0:
3574 weekNumMonth = weekNumMonth + 53
3577 def GetLastSundayBefore(dt):
3578 if dt.iso_week[2] == 7:
3581 return dt - DateTimeDelta(dt.iso_week[2])
3584 year = randint(1900, 2100)
3585 month = randint(1, 12)
3586 day = randint(1, 28)
3587 dt = DateTime(year, month, day)
3588 dayNum = dt.day_of_year
3589 weekNum = dt.iso_week[1]
3590 weekNumMonth = GetMonthWeek(dt)
3593 dtSunday = GetLastSundayBefore(dt)
3595 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3596 weekNumMonth2 = weekNumMonth2 + 1
3597 dtSunday = dtSunday - DateTimeDelta(7)
3599 data = { 'day': rjust(`day`, 2), \
3600 'month': monthNames[month - 1], \
3602 'weekNum': rjust(`weekNum`, 2), \
3603 'weekNumMonth': weekNumMonth, \
3604 'weekNumMonth2': weekNumMonth2, \
3605 'dayNum': rjust(`dayNum`, 3) }
3607 print " { { %(day)s, "\
3608 "wxDateTime::%(month)s, "\
3611 "%(weekNumMonth)s, "\
3612 "%(weekNumMonth2)s, "\
3613 "%(dayNum)s }," % data
3616 static const WeekNumberTestData weekNumberTestDates
[] =
3618 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3619 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3620 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3621 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3622 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3623 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3624 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3625 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3626 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3627 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3628 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3629 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3630 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3631 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3632 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3633 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3634 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3635 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3636 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3637 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3640 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3642 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3643 const Date
& d
= wn
.date
;
3645 wxDateTime dt
= d
.DT();
3647 wxDateTime::wxDateTime_t
3648 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3649 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3650 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3651 dnum
= dt
.GetDayOfYear();
3653 printf("%s: the day number is %d",
3654 d
.FormatDate().c_str(), dnum
);
3655 if ( dnum
== wn
.dnum
)
3661 printf(" (ERROR: should be %d)", wn
.dnum
);
3664 printf(", week in month is %d", wmon
);
3665 if ( wmon
== wn
.wmon
)
3671 printf(" (ERROR: should be %d)", wn
.wmon
);
3674 printf(" or %d", wmon2
);
3675 if ( wmon2
== wn
.wmon2
)
3681 printf(" (ERROR: should be %d)", wn
.wmon2
);
3684 printf(", week in year is %d", week
);
3685 if ( week
== wn
.week
)
3691 printf(" (ERROR: should be %d)\n", wn
.week
);
3696 // test DST calculations
3697 static void TestTimeDST()
3699 puts("\n*** wxDateTime DST test ***");
3701 printf("DST is%s in effect now.\n\n",
3702 wxDateTime::Now().IsDST() ? "" : " not");
3704 // taken from http://www.energy.ca.gov/daylightsaving.html
3705 static const Date datesDST
[2][2004 - 1900 + 1] =
3708 { 1, wxDateTime::Apr
, 1990 },
3709 { 7, wxDateTime::Apr
, 1991 },
3710 { 5, wxDateTime::Apr
, 1992 },
3711 { 4, wxDateTime::Apr
, 1993 },
3712 { 3, wxDateTime::Apr
, 1994 },
3713 { 2, wxDateTime::Apr
, 1995 },
3714 { 7, wxDateTime::Apr
, 1996 },
3715 { 6, wxDateTime::Apr
, 1997 },
3716 { 5, wxDateTime::Apr
, 1998 },
3717 { 4, wxDateTime::Apr
, 1999 },
3718 { 2, wxDateTime::Apr
, 2000 },
3719 { 1, wxDateTime::Apr
, 2001 },
3720 { 7, wxDateTime::Apr
, 2002 },
3721 { 6, wxDateTime::Apr
, 2003 },
3722 { 4, wxDateTime::Apr
, 2004 },
3725 { 28, wxDateTime::Oct
, 1990 },
3726 { 27, wxDateTime::Oct
, 1991 },
3727 { 25, wxDateTime::Oct
, 1992 },
3728 { 31, wxDateTime::Oct
, 1993 },
3729 { 30, wxDateTime::Oct
, 1994 },
3730 { 29, wxDateTime::Oct
, 1995 },
3731 { 27, wxDateTime::Oct
, 1996 },
3732 { 26, wxDateTime::Oct
, 1997 },
3733 { 25, wxDateTime::Oct
, 1998 },
3734 { 31, wxDateTime::Oct
, 1999 },
3735 { 29, wxDateTime::Oct
, 2000 },
3736 { 28, wxDateTime::Oct
, 2001 },
3737 { 27, wxDateTime::Oct
, 2002 },
3738 { 26, wxDateTime::Oct
, 2003 },
3739 { 31, wxDateTime::Oct
, 2004 },
3744 for ( year
= 1990; year
< 2005; year
++ )
3746 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3747 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3749 printf("DST period in the US for year %d: from %s to %s",
3750 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3752 size_t n
= year
- 1990;
3753 const Date
& dBegin
= datesDST
[0][n
];
3754 const Date
& dEnd
= datesDST
[1][n
];
3756 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3762 printf(" (ERROR: should be %s %d to %s %d)\n",
3763 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3764 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3770 for ( year
= 1990; year
< 2005; year
++ )
3772 printf("DST period in Europe for year %d: from %s to %s\n",
3774 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3775 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3779 // test wxDateTime -> text conversion
3780 static void TestTimeFormat()
3782 puts("\n*** wxDateTime formatting test ***");
3784 // some information may be lost during conversion, so store what kind
3785 // of info should we recover after a round trip
3788 CompareNone
, // don't try comparing
3789 CompareBoth
, // dates and times should be identical
3790 CompareDate
, // dates only
3791 CompareTime
// time only
3796 CompareKind compareKind
;
3798 } formatTestFormats
[] =
3800 { CompareBoth
, "---> %c" },
3801 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3802 { CompareBoth
, "Date is %x, time is %X" },
3803 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3804 { CompareNone
, "The day of year: %j, the week of year: %W" },
3805 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3808 static const Date formatTestDates
[] =
3810 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3811 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3813 // this test can't work for other centuries because it uses two digit
3814 // years in formats, so don't even try it
3815 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3816 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3817 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3821 // an extra test (as it doesn't depend on date, don't do it in the loop)
3822 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3824 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3828 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3829 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3831 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3832 printf("%s", s
.c_str());
3834 // what can we recover?
3835 int kind
= formatTestFormats
[n
].compareKind
;
3839 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3842 // converion failed - should it have?
3843 if ( kind
== CompareNone
)
3846 puts(" (ERROR: conversion back failed)");
3850 // should have parsed the entire string
3851 puts(" (ERROR: conversion back stopped too soon)");
3855 bool equal
= FALSE
; // suppress compilaer warning
3863 equal
= dt
.IsSameDate(dt2
);
3867 equal
= dt
.IsSameTime(dt2
);
3873 printf(" (ERROR: got back '%s' instead of '%s')\n",
3874 dt2
.Format().c_str(), dt
.Format().c_str());
3885 // test text -> wxDateTime conversion
3886 static void TestTimeParse()
3888 puts("\n*** wxDateTime parse test ***");
3890 struct ParseTestData
3897 static const ParseTestData parseTestDates
[] =
3899 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3900 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3903 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3905 const char *format
= parseTestDates
[n
].format
;
3907 printf("%s => ", format
);
3910 if ( dt
.ParseRfc822Date(format
) )
3912 printf("%s ", dt
.Format().c_str());
3914 if ( parseTestDates
[n
].good
)
3916 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3923 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3928 puts("(ERROR: bad format)");
3933 printf("bad format (%s)\n",
3934 parseTestDates
[n
].good
? "ERROR" : "ok");
3939 static void TestDateTimeInteractive()
3941 puts("\n*** interactive wxDateTime tests ***");
3947 printf("Enter a date: ");
3948 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3951 // kill the last '\n'
3952 buf
[strlen(buf
) - 1] = 0;
3955 const char *p
= dt
.ParseDate(buf
);
3958 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3964 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3967 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3968 dt
.Format("%b %d, %Y").c_str(),
3970 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3971 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3972 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3975 puts("\n*** done ***");
3978 static void TestTimeMS()
3980 puts("*** testing millisecond-resolution support in wxDateTime ***");
3982 wxDateTime dt1
= wxDateTime::Now(),
3983 dt2
= wxDateTime::UNow();
3985 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3986 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3987 printf("Dummy loop: ");
3988 for ( int i
= 0; i
< 6000; i
++ )
3990 //for ( int j = 0; j < 10; j++ )
3993 s
.Printf("%g", sqrt(i
));
4002 dt2
= wxDateTime::UNow();
4003 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4005 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4007 puts("\n*** done ***");
4010 static void TestTimeArithmetics()
4012 puts("\n*** testing arithmetic operations on wxDateTime ***");
4014 static const struct ArithmData
4016 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4017 : span(sp
), name(nam
) { }
4021 } testArithmData
[] =
4023 ArithmData(wxDateSpan::Day(), "day"),
4024 ArithmData(wxDateSpan::Week(), "week"),
4025 ArithmData(wxDateSpan::Month(), "month"),
4026 ArithmData(wxDateSpan::Year(), "year"),
4027 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4030 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4032 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4034 wxDateSpan span
= testArithmData
[n
].span
;
4038 const char *name
= testArithmData
[n
].name
;
4039 printf("%s + %s = %s, %s - %s = %s\n",
4040 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4041 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4043 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4044 if ( dt1
- span
== dt
)
4050 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4053 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4054 if ( dt2
+ span
== dt
)
4060 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4063 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4064 if ( dt2
+ 2*span
== dt1
)
4070 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4077 static void TestTimeHolidays()
4079 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4081 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4082 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4083 dtEnd
= dtStart
.GetLastMonthDay();
4085 wxDateTimeArray hol
;
4086 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4088 const wxChar
*format
= "%d-%b-%Y (%a)";
4090 printf("All holidays between %s and %s:\n",
4091 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4093 size_t count
= hol
.GetCount();
4094 for ( size_t n
= 0; n
< count
; n
++ )
4096 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4102 static void TestTimeZoneBug()
4104 puts("\n*** testing for DST/timezone bug ***\n");
4106 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4107 for ( int i
= 0; i
< 31; i
++ )
4109 printf("Date %s: week day %s.\n",
4110 date
.Format(_T("%d-%m-%Y")).c_str(),
4111 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4113 date
+= wxDateSpan::Day();
4119 static void TestTimeSpanFormat()
4121 puts("\n*** wxTimeSpan tests ***");
4123 static const char *formats
[] =
4125 _T("(default) %H:%M:%S"),
4126 _T("%E weeks and %D days"),
4127 _T("%l milliseconds"),
4128 _T("(with ms) %H:%M:%S:%l"),
4129 _T("100%% of minutes is %M"), // test "%%"
4130 _T("%D days and %H hours"),
4131 _T("or also %S seconds"),
4134 wxTimeSpan
ts1(1, 2, 3, 4),
4136 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4138 printf("ts1 = %s\tts2 = %s\n",
4139 ts1
.Format(formats
[n
]).c_str(),
4140 ts2
.Format(formats
[n
]).c_str());
4148 // test compatibility with the old wxDate/wxTime classes
4149 static void TestTimeCompatibility()
4151 puts("\n*** wxDateTime compatibility test ***");
4153 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4154 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4156 double jdnNow
= wxDateTime::Now().GetJDN();
4157 long jdnMidnight
= (long)(jdnNow
- 0.5);
4158 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4160 jdnMidnight
= wxDate().Set().GetJulianDate();
4161 printf("wxDateTime for today: %s\n",
4162 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4164 int flags
= wxEUROPEAN
;//wxFULL;
4167 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4168 for ( int n
= 0; n
< 7; n
++ )
4170 printf("Previous %s is %s\n",
4171 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4172 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4178 #endif // TEST_DATETIME
4180 // ----------------------------------------------------------------------------
4182 // ----------------------------------------------------------------------------
4186 #include <wx/thread.h>
4188 static size_t gs_counter
= (size_t)-1;
4189 static wxCriticalSection gs_critsect
;
4190 static wxCondition gs_cond
;
4192 class MyJoinableThread
: public wxThread
4195 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4196 { m_n
= n
; Create(); }
4198 // thread execution starts here
4199 virtual ExitCode
Entry();
4205 wxThread::ExitCode
MyJoinableThread::Entry()
4207 unsigned long res
= 1;
4208 for ( size_t n
= 1; n
< m_n
; n
++ )
4212 // it's a loooong calculation :-)
4216 return (ExitCode
)res
;
4219 class MyDetachedThread
: public wxThread
4222 MyDetachedThread(size_t n
, char ch
)
4226 m_cancelled
= FALSE
;
4231 // thread execution starts here
4232 virtual ExitCode
Entry();
4235 virtual void OnExit();
4238 size_t m_n
; // number of characters to write
4239 char m_ch
; // character to write
4241 bool m_cancelled
; // FALSE if we exit normally
4244 wxThread::ExitCode
MyDetachedThread::Entry()
4247 wxCriticalSectionLocker
lock(gs_critsect
);
4248 if ( gs_counter
== (size_t)-1 )
4254 for ( size_t n
= 0; n
< m_n
; n
++ )
4256 if ( TestDestroy() )
4266 wxThread::Sleep(100);
4272 void MyDetachedThread::OnExit()
4274 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4276 wxCriticalSectionLocker
lock(gs_critsect
);
4277 if ( !--gs_counter
&& !m_cancelled
)
4281 void TestDetachedThreads()
4283 puts("\n*** Testing detached threads ***");
4285 static const size_t nThreads
= 3;
4286 MyDetachedThread
*threads
[nThreads
];
4288 for ( n
= 0; n
< nThreads
; n
++ )
4290 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4293 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4294 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4296 for ( n
= 0; n
< nThreads
; n
++ )
4301 // wait until all threads terminate
4307 void TestJoinableThreads()
4309 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4311 // calc 10! in the background
4312 MyJoinableThread
thread(10);
4315 printf("\nThread terminated with exit code %lu.\n",
4316 (unsigned long)thread
.Wait());
4319 void TestThreadSuspend()
4321 puts("\n*** Testing thread suspend/resume functions ***");
4323 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4327 // this is for this demo only, in a real life program we'd use another
4328 // condition variable which would be signaled from wxThread::Entry() to
4329 // tell us that the thread really started running - but here just wait a
4330 // bit and hope that it will be enough (the problem is, of course, that
4331 // the thread might still not run when we call Pause() which will result
4333 wxThread::Sleep(300);
4335 for ( size_t n
= 0; n
< 3; n
++ )
4339 puts("\nThread suspended");
4342 // don't sleep but resume immediately the first time
4343 wxThread::Sleep(300);
4345 puts("Going to resume the thread");
4350 puts("Waiting until it terminates now");
4352 // wait until the thread terminates
4358 void TestThreadDelete()
4360 // As above, using Sleep() is only for testing here - we must use some
4361 // synchronisation object instead to ensure that the thread is still
4362 // running when we delete it - deleting a detached thread which already
4363 // terminated will lead to a crash!
4365 puts("\n*** Testing thread delete function ***");
4367 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4371 puts("\nDeleted a thread which didn't start to run yet.");
4373 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4377 wxThread::Sleep(300);
4381 puts("\nDeleted a running thread.");
4383 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4387 wxThread::Sleep(300);
4393 puts("\nDeleted a sleeping thread.");
4395 MyJoinableThread
thread3(20);
4400 puts("\nDeleted a joinable thread.");
4402 MyJoinableThread
thread4(2);
4405 wxThread::Sleep(300);
4409 puts("\nDeleted a joinable thread which already terminated.");
4414 #endif // TEST_THREADS
4416 // ----------------------------------------------------------------------------
4418 // ----------------------------------------------------------------------------
4422 static void PrintArray(const char* name
, const wxArrayString
& array
)
4424 printf("Dump of the array '%s'\n", name
);
4426 size_t nCount
= array
.GetCount();
4427 for ( size_t n
= 0; n
< nCount
; n
++ )
4429 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4433 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4435 printf("Dump of the array '%s'\n", name
);
4437 size_t nCount
= array
.GetCount();
4438 for ( size_t n
= 0; n
< nCount
; n
++ )
4440 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4444 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4445 const wxString
& second
)
4447 return first
.length() - second
.length();
4450 int wxCMPFUNC_CONV
IntCompare(int *first
,
4453 return *first
- *second
;
4456 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4459 return *second
- *first
;
4462 static void TestArrayOfInts()
4464 puts("*** Testing wxArrayInt ***\n");
4475 puts("After sort:");
4479 puts("After reverse sort:");
4480 a
.Sort(IntRevCompare
);
4484 #include "wx/dynarray.h"
4486 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4487 #include "wx/arrimpl.cpp"
4488 WX_DEFINE_OBJARRAY(ArrayBars
);
4490 static void TestArrayOfObjects()
4492 puts("*** Testing wxObjArray ***\n");
4496 Bar
bar("second bar");
4498 printf("Initially: %u objects in the array, %u objects total.\n",
4499 bars
.GetCount(), Bar::GetNumber());
4501 bars
.Add(new Bar("first bar"));
4504 printf("Now: %u objects in the array, %u objects total.\n",
4505 bars
.GetCount(), Bar::GetNumber());
4509 printf("After Empty(): %u objects in the array, %u objects total.\n",
4510 bars
.GetCount(), Bar::GetNumber());
4513 printf("Finally: no more objects in the array, %u objects total.\n",
4517 #endif // TEST_ARRAYS
4519 // ----------------------------------------------------------------------------
4521 // ----------------------------------------------------------------------------
4525 #include "wx/timer.h"
4526 #include "wx/tokenzr.h"
4528 static void TestStringConstruction()
4530 puts("*** Testing wxString constructores ***");
4532 #define TEST_CTOR(args, res) \
4535 printf("wxString%s = %s ", #args, s.c_str()); \
4542 printf("(ERROR: should be %s)\n", res); \
4546 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4547 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4548 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4549 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4551 static const wxChar
*s
= _T("?really!");
4552 const wxChar
*start
= wxStrchr(s
, _T('r'));
4553 const wxChar
*end
= wxStrchr(s
, _T('!'));
4554 TEST_CTOR((start
, end
), _T("really"));
4559 static void TestString()
4569 for (int i
= 0; i
< 1000000; ++i
)
4573 c
= "! How'ya doin'?";
4576 c
= "Hello world! What's up?";
4581 printf ("TestString elapsed time: %ld\n", sw
.Time());
4584 static void TestPChar()
4592 for (int i
= 0; i
< 1000000; ++i
)
4594 strcpy (a
, "Hello");
4595 strcpy (b
, " world");
4596 strcpy (c
, "! How'ya doin'?");
4599 strcpy (c
, "Hello world! What's up?");
4600 if (strcmp (c
, a
) == 0)
4604 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4607 static void TestStringSub()
4609 wxString
s("Hello, world!");
4611 puts("*** Testing wxString substring extraction ***");
4613 printf("String = '%s'\n", s
.c_str());
4614 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4615 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4616 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4617 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4618 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4619 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4621 static const wxChar
*prefixes
[] =
4625 _T("Hello, world!"),
4626 _T("Hello, world!!!"),
4632 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4634 wxString prefix
= prefixes
[n
], rest
;
4635 bool rc
= s
.StartsWith(prefix
, &rest
);
4636 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4639 printf(" (the rest is '%s')\n", rest
.c_str());
4650 static void TestStringFormat()
4652 puts("*** Testing wxString formatting ***");
4655 s
.Printf("%03d", 18);
4657 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4658 printf("Number 18: %s\n", s
.c_str());
4663 // returns "not found" for npos, value for all others
4664 static wxString
PosToString(size_t res
)
4666 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4667 : wxString::Format(_T("%u"), res
);
4671 static void TestStringFind()
4673 puts("*** Testing wxString find() functions ***");
4675 static const wxChar
*strToFind
= _T("ell");
4676 static const struct StringFindTest
4680 result
; // of searching "ell" in str
4683 { _T("Well, hello world"), 0, 1 },
4684 { _T("Well, hello world"), 6, 7 },
4685 { _T("Well, hello world"), 9, wxString::npos
},
4688 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4690 const StringFindTest
& ft
= findTestData
[n
];
4691 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4693 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4694 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4696 size_t resTrue
= ft
.result
;
4697 if ( res
== resTrue
)
4703 printf(_T("(ERROR: should be %s)\n"),
4704 PosToString(resTrue
).c_str());
4711 static void TestStringTokenizer()
4713 puts("*** Testing wxStringTokenizer ***");
4715 static const wxChar
*modeNames
[] =
4719 _T("return all empty"),
4724 static const struct StringTokenizerTest
4726 const wxChar
*str
; // string to tokenize
4727 const wxChar
*delims
; // delimiters to use
4728 size_t count
; // count of token
4729 wxStringTokenizerMode mode
; // how should we tokenize it
4730 } tokenizerTestData
[] =
4732 { _T(""), _T(" "), 0 },
4733 { _T("Hello, world"), _T(" "), 2 },
4734 { _T("Hello, world "), _T(" "), 2 },
4735 { _T("Hello, world"), _T(","), 2 },
4736 { _T("Hello, world!"), _T(",!"), 2 },
4737 { _T("Hello,, world!"), _T(",!"), 3 },
4738 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4739 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4740 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4741 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4742 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4743 { _T("01/02/99"), _T("/-"), 3 },
4744 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4747 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4749 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4750 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4752 size_t count
= tkz
.CountTokens();
4753 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4754 MakePrintable(tt
.str
).c_str(),
4756 MakePrintable(tt
.delims
).c_str(),
4757 modeNames
[tkz
.GetMode()]);
4758 if ( count
== tt
.count
)
4764 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4769 // if we emulate strtok(), check that we do it correctly
4770 wxChar
*buf
, *s
= NULL
, *last
;
4772 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4774 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4775 wxStrcpy(buf
, tt
.str
);
4777 s
= wxStrtok(buf
, tt
.delims
, &last
);
4784 // now show the tokens themselves
4786 while ( tkz
.HasMoreTokens() )
4788 wxString token
= tkz
.GetNextToken();
4790 printf(_T("\ttoken %u: '%s'"),
4792 MakePrintable(token
).c_str());
4802 printf(" (ERROR: should be %s)\n", s
);
4805 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4809 // nothing to compare with
4814 if ( count2
!= count
)
4816 puts(_T("\tERROR: token count mismatch"));
4825 static void TestStringReplace()
4827 puts("*** Testing wxString::replace ***");
4829 static const struct StringReplaceTestData
4831 const wxChar
*original
; // original test string
4832 size_t start
, len
; // the part to replace
4833 const wxChar
*replacement
; // the replacement string
4834 const wxChar
*result
; // and the expected result
4835 } stringReplaceTestData
[] =
4837 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4838 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4839 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4840 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4841 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4844 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4846 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4848 wxString original
= data
.original
;
4849 original
.replace(data
.start
, data
.len
, data
.replacement
);
4851 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4852 data
.original
, data
.start
, data
.len
, data
.replacement
,
4855 if ( original
== data
.result
)
4861 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4868 static void TestStringMatch()
4870 wxPuts(_T("*** Testing wxString::Matches() ***"));
4872 static const struct StringMatchTestData
4875 const wxChar
*wildcard
;
4877 } stringMatchTestData
[] =
4879 { _T("foobar"), _T("foo*"), 1 },
4880 { _T("foobar"), _T("*oo*"), 1 },
4881 { _T("foobar"), _T("*bar"), 1 },
4882 { _T("foobar"), _T("??????"), 1 },
4883 { _T("foobar"), _T("f??b*"), 1 },
4884 { _T("foobar"), _T("f?b*"), 0 },
4885 { _T("foobar"), _T("*goo*"), 0 },
4886 { _T("foobar"), _T("*foo"), 0 },
4887 { _T("foobarfoo"), _T("*foo"), 1 },
4888 { _T(""), _T("*"), 1 },
4889 { _T(""), _T("?"), 0 },
4892 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4894 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4895 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4896 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4898 matches
? _T("matches") : _T("doesn't match"),
4900 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4906 #endif // TEST_STRINGS
4908 // ----------------------------------------------------------------------------
4910 // ----------------------------------------------------------------------------
4912 int main(int argc
, char **argv
)
4914 wxInitializer initializer
;
4917 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4922 #ifdef TEST_SNGLINST
4923 wxSingleInstanceChecker checker
;
4924 if ( checker
.Create(_T(".wxconsole.lock")) )
4926 if ( checker
.IsAnotherRunning() )
4928 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4933 // wait some time to give time to launch another instance
4934 wxPrintf(_T("Press \"Enter\" to continue..."));
4937 else // failed to create
4939 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4941 #endif // TEST_SNGLINST
4945 #endif // TEST_CHARSET
4948 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4950 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
4951 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4952 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4953 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4955 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4956 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4957 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
4958 wxCMD_LINE_VAL_NUMBER
},
4959 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
4960 wxCMD_LINE_VAL_DATE
},
4962 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4963 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4968 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4970 parser
.AddOption("project_name", "", "full path to project file",
4971 wxCMD_LINE_VAL_STRING
,
4972 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4974 switch ( parser
.Parse() )
4977 wxLogMessage("Help was given, terminating.");
4981 ShowCmdLine(parser
);
4985 wxLogMessage("Syntax error detected, aborting.");
4988 #endif // TEST_CMDLINE
4996 TestStringConstruction();
4999 TestStringTokenizer();
5000 TestStringReplace();
5003 #endif // TEST_STRINGS
5016 puts("*** Initially:");
5018 PrintArray("a1", a1
);
5020 wxArrayString
a2(a1
);
5021 PrintArray("a2", a2
);
5023 wxSortedArrayString
a3(a1
);
5024 PrintArray("a3", a3
);
5026 puts("*** After deleting a string from a1");
5029 PrintArray("a1", a1
);
5030 PrintArray("a2", a2
);
5031 PrintArray("a3", a3
);
5033 puts("*** After reassigning a1 to a2 and a3");
5035 PrintArray("a2", a2
);
5036 PrintArray("a3", a3
);
5038 puts("*** After sorting a1");
5040 PrintArray("a1", a1
);
5042 puts("*** After sorting a1 in reverse order");
5044 PrintArray("a1", a1
);
5046 puts("*** After sorting a1 by the string length");
5047 a1
.Sort(StringLenCompare
);
5048 PrintArray("a1", a1
);
5050 TestArrayOfObjects();
5053 #endif // TEST_ARRAYS
5061 #ifdef TEST_DLLLOADER
5063 #endif // TEST_DLLLOADER
5067 #endif // TEST_ENVIRON
5071 #endif // TEST_EXECUTE
5073 #ifdef TEST_FILECONF
5075 #endif // TEST_FILECONF
5083 #endif // TEST_LOCALE
5087 for ( size_t n
= 0; n
< 8000; n
++ )
5089 s
<< (char)('A' + (n
% 26));
5093 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5095 // this one shouldn't be truncated
5098 // but this one will because log functions use fixed size buffer
5099 // (note that it doesn't need '\n' at the end neither - will be added
5101 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5113 #ifdef TEST_FILENAME
5114 TestFileNameSplit();
5117 TestFileNameConstruction();
5119 TestFileNameComparison();
5120 TestFileNameOperations();
5122 #endif // TEST_FILENAME
5124 #ifdef TEST_FILETIME
5127 #endif // TEST_FILETIME
5130 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5131 if ( TestFtpConnect() )
5142 TestFtpInteractive();
5144 //else: connecting to the FTP server failed
5151 int nCPUs
= wxThread::GetCPUCount();
5152 printf("This system has %d CPUs\n", nCPUs
);
5154 wxThread::SetConcurrency(nCPUs
);
5156 if ( argc
> 1 && argv
[1][0] == 't' )
5157 wxLog::AddTraceMask("thread");
5160 TestDetachedThreads();
5162 TestJoinableThreads();
5164 TestThreadSuspend();
5168 #endif // TEST_THREADS
5170 #ifdef TEST_LONGLONG
5171 // seed pseudo random generator
5172 srand((unsigned)time(NULL
));
5180 TestMultiplication();
5183 TestLongLongConversion();
5184 TestBitOperations();
5185 TestLongLongComparison();
5187 TestLongLongPrint();
5188 #endif // TEST_LONGLONG
5195 wxLog::AddTraceMask(_T("mime"));
5203 TestMimeAssociate();
5206 #ifdef TEST_INFO_FUNCTIONS
5213 #endif // TEST_INFO_FUNCTIONS
5215 #ifdef TEST_PATHLIST
5217 #endif // TEST_PATHLIST
5221 #endif // TEST_REGCONF
5224 // TODO: write a real test using src/regex/tests file
5229 TestRegExSubmatch();
5230 TestRegExInteractive();
5232 TestRegExReplacement();
5233 #endif // TEST_REGEX
5235 #ifdef TEST_REGISTRY
5238 TestRegistryAssociation();
5239 #endif // TEST_REGISTRY
5247 #endif // TEST_SOCKETS
5253 #endif // TEST_STREAMS
5257 #endif // TEST_TIMER
5259 #ifdef TEST_DATETIME
5272 TestTimeArithmetics();
5279 TestTimeSpanFormat();
5281 TestDateTimeInteractive();
5282 #endif // TEST_DATETIME
5285 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5287 #endif // TEST_USLEEP
5293 #endif // TEST_VCARD
5297 #endif // TEST_WCHAR
5301 TestZipStreamRead();
5302 TestZipFileSystem();
5307 TestZlibStreamWrite();
5308 TestZlibStreamRead();