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)? uncomment the line below to do all tests
50 #define TEST_DLLLOADER
59 #define TEST_INFO_FUNCTIONS
75 // #define TEST_VCARD -- don't enable this (VZ)
84 #include "wx/snglinst.h"
85 #endif // TEST_SNGLINST
87 // ----------------------------------------------------------------------------
88 // test class for container objects
89 // ----------------------------------------------------------------------------
91 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
93 class Bar
// Foo is already taken in the hash test
96 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
99 static size_t GetNumber() { return ms_bars
; }
101 const char *GetName() const { return m_name
; }
106 static size_t ms_bars
;
109 size_t Bar::ms_bars
= 0;
111 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
113 // ============================================================================
115 // ============================================================================
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
123 // replace TABs with \t and CRs with \n
124 static wxString
MakePrintable(const wxChar
*s
)
127 (void)str
.Replace(_T("\t"), _T("\\t"));
128 (void)str
.Replace(_T("\n"), _T("\\n"));
129 (void)str
.Replace(_T("\r"), _T("\\r"));
134 #endif // MakePrintable() is used
136 // ----------------------------------------------------------------------------
137 // wxFontMapper::CharsetToEncoding
138 // ----------------------------------------------------------------------------
142 #include "wx/fontmap.h"
144 static void TestCharset()
146 static const wxChar
*charsets
[] =
148 // some vali charsets
157 // and now some bogus ones
164 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
166 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
167 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
169 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
170 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
174 #endif // TEST_CHARSET
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
182 #include "wx/cmdline.h"
183 #include "wx/datetime.h"
185 #if wxUSE_CMDLINE_PARSER
187 static void ShowCmdLine(const wxCmdLineParser
& parser
)
189 wxString s
= "Input files: ";
191 size_t count
= parser
.GetParamCount();
192 for ( size_t param
= 0; param
< count
; param
++ )
194 s
<< parser
.GetParam(param
) << ' ';
198 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
199 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
204 if ( parser
.Found("o", &strVal
) )
205 s
<< "Output file:\t" << strVal
<< '\n';
206 if ( parser
.Found("i", &strVal
) )
207 s
<< "Input dir:\t" << strVal
<< '\n';
208 if ( parser
.Found("s", &lVal
) )
209 s
<< "Size:\t" << lVal
<< '\n';
210 if ( parser
.Found("d", &dt
) )
211 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
212 if ( parser
.Found("project_name", &strVal
) )
213 s
<< "Project:\t" << strVal
<< '\n';
218 #endif // wxUSE_CMDLINE_PARSER
220 static void TestCmdLineConvert()
222 static const char *cmdlines
[] =
225 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
226 "literal \\\" and \"\"",
229 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
231 const char *cmdline
= cmdlines
[n
];
232 printf("Parsing: %s\n", cmdline
);
233 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
235 size_t count
= args
.GetCount();
236 printf("\targc = %u\n", count
);
237 for ( size_t arg
= 0; arg
< count
; arg
++ )
239 printf("\targv[%u] = %s\n", arg
, args
[arg
]);
244 #endif // TEST_CMDLINE
246 // ----------------------------------------------------------------------------
248 // ----------------------------------------------------------------------------
255 static const wxChar
*ROOTDIR
= _T("/");
256 static const wxChar
*TESTDIR
= _T("/usr");
257 #elif defined(__WXMSW__)
258 static const wxChar
*ROOTDIR
= _T("c:\\");
259 static const wxChar
*TESTDIR
= _T("d:\\");
261 #error "don't know where the root directory is"
264 static void TestDirEnumHelper(wxDir
& dir
,
265 int flags
= wxDIR_DEFAULT
,
266 const wxString
& filespec
= wxEmptyString
)
270 if ( !dir
.IsOpened() )
273 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
276 printf("\t%s\n", filename
.c_str());
278 cont
= dir
.GetNext(&filename
);
284 static void TestDirEnum()
286 puts("*** Testing wxDir::GetFirst/GetNext ***");
288 wxDir
dir(wxGetCwd());
290 puts("Enumerating everything in current directory:");
291 TestDirEnumHelper(dir
);
293 puts("Enumerating really everything in current directory:");
294 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
296 puts("Enumerating object files in current directory:");
297 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
299 puts("Enumerating directories in current directory:");
300 TestDirEnumHelper(dir
, wxDIR_DIRS
);
302 puts("Enumerating files in current directory:");
303 TestDirEnumHelper(dir
, wxDIR_FILES
);
305 puts("Enumerating files including hidden in current directory:");
306 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
310 puts("Enumerating everything in root directory:");
311 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
313 puts("Enumerating directories in root directory:");
314 TestDirEnumHelper(dir
, wxDIR_DIRS
);
316 puts("Enumerating files in root directory:");
317 TestDirEnumHelper(dir
, wxDIR_FILES
);
319 puts("Enumerating files including hidden in root directory:");
320 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
322 puts("Enumerating files in non existing directory:");
323 wxDir
dirNo("nosuchdir");
324 TestDirEnumHelper(dirNo
);
327 class DirPrintTraverser
: public wxDirTraverser
330 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
332 return wxDIR_CONTINUE
;
335 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
337 wxString path
, name
, ext
;
338 wxSplitPath(dirname
, &path
, &name
, &ext
);
341 name
<< _T('.') << ext
;
344 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
346 if ( wxIsPathSeparator(*p
) )
350 printf("%s%s\n", indent
.c_str(), name
.c_str());
352 return wxDIR_CONTINUE
;
356 static void TestDirTraverse()
358 puts("*** Testing wxDir::Traverse() ***");
362 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
363 printf("There are %u files under '%s'\n", n
, TESTDIR
);
366 printf("First one is '%s'\n", files
[0u].c_str());
367 printf(" last one is '%s'\n", files
[n
- 1].c_str());
370 // enum again with custom traverser
372 DirPrintTraverser traverser
;
373 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
378 // ----------------------------------------------------------------------------
380 // ----------------------------------------------------------------------------
382 #ifdef TEST_DLLLOADER
384 #include "wx/dynlib.h"
386 static void TestDllLoad()
388 #if defined(__WXMSW__)
389 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
390 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
391 #elif defined(__UNIX__)
392 // weird: using just libc.so does *not* work!
393 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
394 static const wxChar
*FUNC_NAME
= _T("strlen");
396 #error "don't know how to test wxDllLoader on this platform"
399 puts("*** testing wxDllLoader ***\n");
401 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
404 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
408 typedef int (*strlenType
)(const char *);
409 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
412 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
413 FUNC_NAME
, LIB_NAME
);
417 if ( pfnStrlen("foo") != 3 )
419 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
427 wxDllLoader::UnloadLibrary(dllHandle
);
431 #endif // TEST_DLLLOADER
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
439 #include "wx/utils.h"
441 static wxString
MyGetEnv(const wxString
& var
)
444 if ( !wxGetEnv(var
, &val
) )
447 val
= wxString(_T('\'')) + val
+ _T('\'');
452 static void TestEnvironment()
454 const wxChar
*var
= _T("wxTestVar");
456 puts("*** testing environment access functions ***");
458 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
459 wxSetEnv(var
, _T("value for wxTestVar"));
460 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
461 wxSetEnv(var
, _T("another value"));
462 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
464 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
465 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
468 #endif // TEST_ENVIRON
470 // ----------------------------------------------------------------------------
472 // ----------------------------------------------------------------------------
476 #include "wx/utils.h"
478 static void TestExecute()
480 puts("*** testing wxExecute ***");
483 #define COMMAND "cat -n ../../Makefile" // "echo hi"
484 #define SHELL_COMMAND "echo hi from shell"
485 #define REDIRECT_COMMAND COMMAND // "date"
486 #elif defined(__WXMSW__)
487 #define COMMAND "command.com -c 'echo hi'"
488 #define SHELL_COMMAND "echo hi"
489 #define REDIRECT_COMMAND COMMAND
491 #error "no command to exec"
494 printf("Testing wxShell: ");
496 if ( wxShell(SHELL_COMMAND
) )
501 printf("Testing wxExecute: ");
503 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
508 #if 0 // no, it doesn't work (yet?)
509 printf("Testing async wxExecute: ");
511 if ( wxExecute(COMMAND
) != 0 )
512 puts("Ok (command launched).");
517 printf("Testing wxExecute with redirection:\n");
518 wxArrayString output
;
519 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
525 size_t count
= output
.GetCount();
526 for ( size_t n
= 0; n
< count
; n
++ )
528 printf("\t%s\n", output
[n
].c_str());
535 #endif // TEST_EXECUTE
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
544 #include "wx/ffile.h"
545 #include "wx/textfile.h"
547 static void TestFileRead()
549 puts("*** wxFile read test ***");
551 wxFile
file(_T("testdata.fc"));
552 if ( file
.IsOpened() )
554 printf("File length: %lu\n", file
.Length());
556 puts("File dump:\n----------");
558 static const off_t len
= 1024;
562 off_t nRead
= file
.Read(buf
, len
);
563 if ( nRead
== wxInvalidOffset
)
565 printf("Failed to read the file.");
569 fwrite(buf
, nRead
, 1, stdout
);
579 printf("ERROR: can't open test file.\n");
585 static void TestTextFileRead()
587 puts("*** wxTextFile read test ***");
589 wxTextFile
file(_T("testdata.fc"));
592 printf("Number of lines: %u\n", file
.GetLineCount());
593 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
597 puts("\nDumping the entire file:");
598 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
600 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
602 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
604 puts("\nAnd now backwards:");
605 for ( s
= file
.GetLastLine();
606 file
.GetCurrentLine() != 0;
607 s
= file
.GetPrevLine() )
609 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
611 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
615 printf("ERROR: can't open '%s'\n", file
.GetName());
621 static void TestFileCopy()
623 puts("*** Testing wxCopyFile ***");
625 static const wxChar
*filename1
= _T("testdata.fc");
626 static const wxChar
*filename2
= _T("test2");
627 if ( !wxCopyFile(filename1
, filename2
) )
629 puts("ERROR: failed to copy file");
633 wxFFile
f1(filename1
, "rb"),
636 if ( !f1
.IsOpened() || !f2
.IsOpened() )
638 puts("ERROR: failed to open file(s)");
643 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
645 puts("ERROR: failed to read file(s)");
649 if ( (s1
.length() != s2
.length()) ||
650 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
652 puts("ERROR: copy error!");
656 puts("File was copied ok.");
662 if ( !wxRemoveFile(filename2
) )
664 puts("ERROR: failed to remove the file");
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
678 #include "wx/confbase.h"
679 #include "wx/fileconf.h"
681 static const struct FileConfTestData
683 const wxChar
*name
; // value name
684 const wxChar
*value
; // the value from the file
687 { _T("value1"), _T("one") },
688 { _T("value2"), _T("two") },
689 { _T("novalue"), _T("default") },
692 static void TestFileConfRead()
694 puts("*** testing wxFileConfig loading/reading ***");
696 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
697 _T("testdata.fc"), wxEmptyString
,
698 wxCONFIG_USE_RELATIVE_PATH
);
700 // test simple reading
701 puts("\nReading config file:");
702 wxString
defValue(_T("default")), value
;
703 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
705 const FileConfTestData
& data
= fcTestData
[n
];
706 value
= fileconf
.Read(data
.name
, defValue
);
707 printf("\t%s = %s ", data
.name
, value
.c_str());
708 if ( value
== data
.value
)
714 printf("(ERROR: should be %s)\n", data
.value
);
718 // test enumerating the entries
719 puts("\nEnumerating all root entries:");
722 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
725 printf("\t%s = %s\n",
727 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
729 cont
= fileconf
.GetNextEntry(name
, dummy
);
733 #endif // TEST_FILECONF
735 // ----------------------------------------------------------------------------
737 // ----------------------------------------------------------------------------
741 #include "wx/filename.h"
743 static struct FileNameInfo
745 const wxChar
*fullname
;
751 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
752 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
753 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
754 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
755 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
756 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
757 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
758 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
761 static void TestFileNameConstruction()
763 puts("*** testing wxFileName construction ***");
765 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
767 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
769 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
770 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
772 puts("ERROR (couldn't be normalized)");
776 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
783 static void TestFileNameSplit()
785 puts("*** testing wxFileName splitting ***");
787 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
789 const FileNameInfo
&fni
= filenames
[n
];
790 wxString path
, name
, ext
;
791 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
793 printf("%s -> path = '%s', name = '%s', ext = '%s'",
794 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
795 if ( path
!= fni
.path
)
796 printf(" (ERROR: path = '%s')", fni
.path
);
797 if ( name
!= fni
.name
)
798 printf(" (ERROR: name = '%s')", fni
.name
);
799 if ( ext
!= fni
.ext
)
800 printf(" (ERROR: ext = '%s')", fni
.ext
);
807 static void TestFileNameComparison()
812 static void TestFileNameOperations()
817 static void TestFileNameCwd()
822 #endif // TEST_FILENAME
824 // ----------------------------------------------------------------------------
825 // wxFileName time functions
826 // ----------------------------------------------------------------------------
830 #include <wx/filename.h>
831 #include <wx/datetime.h>
833 static void TestFileGetTimes()
835 wxFileName
fn(_T("testdata.fc"));
837 wxDateTime dtAccess
, dtMod
, dtChange
;
838 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
840 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
844 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
846 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
847 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
848 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
849 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
853 static void TestFileSetTimes()
855 wxFileName
fn(_T("testdata.fc"));
857 wxDateTime dtAccess
, dtMod
, dtChange
;
860 wxPrintf(_T("ERROR: Touch() failed.\n"));
864 #endif // TEST_FILETIME
866 // ----------------------------------------------------------------------------
868 // ----------------------------------------------------------------------------
876 Foo(int n_
) { n
= n_
; count
++; }
884 size_t Foo::count
= 0;
886 WX_DECLARE_LIST(Foo
, wxListFoos
);
887 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
889 #include "wx/listimpl.cpp"
891 WX_DEFINE_LIST(wxListFoos
);
893 static void TestHash()
895 puts("*** Testing wxHashTable ***\n");
899 hash
.DeleteContents(TRUE
);
901 printf("Hash created: %u foos in hash, %u foos totally\n",
902 hash
.GetCount(), Foo::count
);
904 static const int hashTestData
[] =
906 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
910 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
912 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
915 printf("Hash filled: %u foos in hash, %u foos totally\n",
916 hash
.GetCount(), Foo::count
);
918 puts("Hash access test:");
919 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
921 printf("\tGetting element with key %d, value %d: ",
923 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
926 printf("ERROR, not found.\n");
930 printf("%d (%s)\n", foo
->n
,
931 (size_t)foo
->n
== n
? "ok" : "ERROR");
935 printf("\nTrying to get an element not in hash: ");
937 if ( hash
.Get(1234) || hash
.Get(1, 0) )
939 puts("ERROR: found!");
943 puts("ok (not found)");
947 printf("Hash destroyed: %u foos left\n", Foo::count
);
952 // ----------------------------------------------------------------------------
954 // ----------------------------------------------------------------------------
960 WX_DECLARE_LIST(Bar
, wxListBars
);
961 #include "wx/listimpl.cpp"
962 WX_DEFINE_LIST(wxListBars
);
964 static void TestListCtor()
966 puts("*** Testing wxList construction ***\n");
970 list1
.Append(new Bar(_T("first")));
971 list1
.Append(new Bar(_T("second")));
973 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
974 list1
.GetCount(), Bar::GetNumber());
979 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
980 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
982 list1
.DeleteContents(TRUE
);
985 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
990 // ----------------------------------------------------------------------------
992 // ----------------------------------------------------------------------------
997 #include "wx/utils.h" // for wxSetEnv
999 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1001 // find the name of the language from its value
1002 static const char *GetLangName(int lang
)
1004 static const char *languageNames
[] =
1025 "ARABIC_SAUDI_ARABIA",
1050 "CHINESE_SIMPLIFIED",
1051 "CHINESE_TRADITIONAL",
1054 "CHINESE_SINGAPORE",
1065 "ENGLISH_AUSTRALIA",
1069 "ENGLISH_CARIBBEAN",
1073 "ENGLISH_NEW_ZEALAND",
1074 "ENGLISH_PHILIPPINES",
1075 "ENGLISH_SOUTH_AFRICA",
1087 "FRENCH_LUXEMBOURG",
1096 "GERMAN_LIECHTENSTEIN",
1097 "GERMAN_LUXEMBOURG",
1138 "MALAY_BRUNEI_DARUSSALAM",
1150 "NORWEGIAN_NYNORSK",
1157 "PORTUGUESE_BRAZILIAN",
1182 "SPANISH_ARGENTINA",
1186 "SPANISH_COSTA_RICA",
1187 "SPANISH_DOMINICAN_REPUBLIC",
1189 "SPANISH_EL_SALVADOR",
1190 "SPANISH_GUATEMALA",
1194 "SPANISH_NICARAGUA",
1198 "SPANISH_PUERTO_RICO",
1201 "SPANISH_VENEZUELA",
1238 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1239 return languageNames
[lang
];
1244 static void TestDefaultLang()
1246 puts("*** Testing wxLocale::GetSystemLanguage ***");
1248 static const wxChar
*langStrings
[] =
1250 NULL
, // system default
1257 _T("de_DE.iso88591"),
1259 _T("?"), // invalid lang spec
1260 _T("klingonese"), // I bet on some systems it does exist...
1263 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1264 wxLocale::GetSystemEncodingName().c_str(),
1265 wxLocale::GetSystemEncoding());
1267 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1269 const char *langStr
= langStrings
[n
];
1272 // FIXME: this doesn't do anything at all under Windows, we need
1273 // to create a new wxLocale!
1274 wxSetEnv(_T("LC_ALL"), langStr
);
1277 int lang
= gs_localeDefault
.GetSystemLanguage();
1278 printf("Locale for '%s' is %s.\n",
1279 langStr
? langStr
: "system default", GetLangName(lang
));
1283 #endif // TEST_LOCALE
1285 // ----------------------------------------------------------------------------
1287 // ----------------------------------------------------------------------------
1291 #include "wx/mimetype.h"
1293 static void TestMimeEnum()
1295 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1297 wxArrayString mimetypes
;
1299 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1301 printf("*** All %u known filetypes: ***\n", count
);
1306 for ( size_t n
= 0; n
< count
; n
++ )
1308 wxFileType
*filetype
=
1309 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1312 printf("nothing known about the filetype '%s'!\n",
1313 mimetypes
[n
].c_str());
1317 filetype
->GetDescription(&desc
);
1318 filetype
->GetExtensions(exts
);
1320 filetype
->GetIcon(NULL
);
1323 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1326 extsAll
<< _T(", ");
1330 printf("\t%s: %s (%s)\n",
1331 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1337 static void TestMimeOverride()
1339 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1341 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1342 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1344 if ( wxFile::Exists(mailcap
) )
1345 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1347 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1349 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1352 if ( wxFile::Exists(mimetypes
) )
1353 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1355 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1357 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1363 static void TestMimeFilename()
1365 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1367 static const wxChar
*filenames
[] =
1374 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1376 const wxString fname
= filenames
[n
];
1377 wxString ext
= fname
.AfterLast(_T('.'));
1378 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1381 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1386 if ( !ft
->GetDescription(&desc
) )
1387 desc
= _T("<no description>");
1390 if ( !ft
->GetOpenCommand(&cmd
,
1391 wxFileType::MessageParameters(fname
, _T(""))) )
1392 cmd
= _T("<no command available>");
1394 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1395 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1404 static void TestMimeAssociate()
1406 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1408 wxFileTypeInfo
ftInfo(
1409 _T("application/x-xyz"),
1410 _T("xyzview '%s'"), // open cmd
1411 _T(""), // print cmd
1412 _T("XYZ File") // description
1413 _T(".xyz"), // extensions
1414 NULL
// end of extensions
1416 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1418 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1421 wxPuts(_T("ERROR: failed to create association!"));
1425 // TODO: read it back
1434 // ----------------------------------------------------------------------------
1435 // misc information functions
1436 // ----------------------------------------------------------------------------
1438 #ifdef TEST_INFO_FUNCTIONS
1440 #include "wx/utils.h"
1442 static void TestDiskInfo()
1444 puts("*** Testing wxGetDiskSpace() ***");
1449 printf("\nEnter a directory name: ");
1450 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1453 // kill the last '\n'
1454 pathname
[strlen(pathname
) - 1] = 0;
1456 wxLongLong total
, free
;
1457 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1459 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1463 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1464 (total
/ 1024).ToString().c_str(),
1465 (free
/ 1024).ToString().c_str(),
1471 static void TestOsInfo()
1473 puts("*** Testing OS info functions ***\n");
1476 wxGetOsVersion(&major
, &minor
);
1477 printf("Running under: %s, version %d.%d\n",
1478 wxGetOsDescription().c_str(), major
, minor
);
1480 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1482 printf("Host name is %s (%s).\n",
1483 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1488 static void TestUserInfo()
1490 puts("*** Testing user info functions ***\n");
1492 printf("User id is:\t%s\n", wxGetUserId().c_str());
1493 printf("User name is:\t%s\n", wxGetUserName().c_str());
1494 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1495 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1500 #endif // TEST_INFO_FUNCTIONS
1502 // ----------------------------------------------------------------------------
1504 // ----------------------------------------------------------------------------
1506 #ifdef TEST_LONGLONG
1508 #include "wx/longlong.h"
1509 #include "wx/timer.h"
1511 // make a 64 bit number from 4 16 bit ones
1512 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1514 // get a random 64 bit number
1515 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1517 static const long testLongs
[] =
1528 #if wxUSE_LONGLONG_WX
1529 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1530 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1531 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1532 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1533 #endif // wxUSE_LONGLONG_WX
1535 static void TestSpeed()
1537 static const long max
= 100000000;
1544 for ( n
= 0; n
< max
; n
++ )
1549 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1552 #if wxUSE_LONGLONG_NATIVE
1557 for ( n
= 0; n
< max
; n
++ )
1562 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1564 #endif // wxUSE_LONGLONG_NATIVE
1570 for ( n
= 0; n
< max
; n
++ )
1575 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1579 static void TestLongLongConversion()
1581 puts("*** Testing wxLongLong conversions ***\n");
1585 for ( size_t n
= 0; n
< 100000; n
++ )
1589 #if wxUSE_LONGLONG_NATIVE
1590 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1592 wxASSERT_MSG( a
== b
, "conversions failure" );
1594 puts("Can't do it without native long long type, test skipped.");
1597 #endif // wxUSE_LONGLONG_NATIVE
1599 if ( !(nTested
% 1000) )
1611 static void TestMultiplication()
1613 puts("*** Testing wxLongLong multiplication ***\n");
1617 for ( size_t n
= 0; n
< 100000; n
++ )
1622 #if wxUSE_LONGLONG_NATIVE
1623 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1624 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1626 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1627 #else // !wxUSE_LONGLONG_NATIVE
1628 puts("Can't do it without native long long type, test skipped.");
1631 #endif // wxUSE_LONGLONG_NATIVE
1633 if ( !(nTested
% 1000) )
1645 static void TestDivision()
1647 puts("*** Testing wxLongLong division ***\n");
1651 for ( size_t n
= 0; n
< 100000; n
++ )
1653 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1654 // multiplication will not overflow)
1655 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1657 // get a random long (not wxLongLong for now) to divide it with
1662 #if wxUSE_LONGLONG_NATIVE
1663 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1665 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1666 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1667 #else // !wxUSE_LONGLONG_NATIVE
1668 // verify the result
1669 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1670 #endif // wxUSE_LONGLONG_NATIVE
1672 if ( !(nTested
% 1000) )
1684 static void TestAddition()
1686 puts("*** Testing wxLongLong addition ***\n");
1690 for ( size_t n
= 0; n
< 100000; n
++ )
1696 #if wxUSE_LONGLONG_NATIVE
1697 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1698 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1699 "addition failure" );
1700 #else // !wxUSE_LONGLONG_NATIVE
1701 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1702 #endif // wxUSE_LONGLONG_NATIVE
1704 if ( !(nTested
% 1000) )
1716 static void TestBitOperations()
1718 puts("*** Testing wxLongLong bit operation ***\n");
1722 for ( size_t n
= 0; n
< 100000; n
++ )
1726 #if wxUSE_LONGLONG_NATIVE
1727 for ( size_t n
= 0; n
< 33; n
++ )
1730 #else // !wxUSE_LONGLONG_NATIVE
1731 puts("Can't do it without native long long type, test skipped.");
1734 #endif // wxUSE_LONGLONG_NATIVE
1736 if ( !(nTested
% 1000) )
1748 static void TestLongLongComparison()
1750 #if wxUSE_LONGLONG_WX
1751 puts("*** Testing wxLongLong comparison ***\n");
1753 static const long ls
[2] =
1759 wxLongLongWx lls
[2];
1763 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1767 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1769 res
= lls
[m
] > testLongs
[n
];
1770 printf("0x%lx > 0x%lx is %s (%s)\n",
1771 ls
[m
], testLongs
[n
], res
? "true" : "false",
1772 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1774 res
= lls
[m
] < testLongs
[n
];
1775 printf("0x%lx < 0x%lx is %s (%s)\n",
1776 ls
[m
], testLongs
[n
], res
? "true" : "false",
1777 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1779 res
= lls
[m
] == testLongs
[n
];
1780 printf("0x%lx == 0x%lx is %s (%s)\n",
1781 ls
[m
], testLongs
[n
], res
? "true" : "false",
1782 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1785 #endif // wxUSE_LONGLONG_WX
1788 static void TestLongLongPrint()
1790 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1792 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1794 wxLongLong ll
= testLongs
[n
];
1795 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1798 wxLongLong
ll(0x12345678, 0x87654321);
1799 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1802 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1808 #endif // TEST_LONGLONG
1810 // ----------------------------------------------------------------------------
1812 // ----------------------------------------------------------------------------
1814 #ifdef TEST_PATHLIST
1816 static void TestPathList()
1818 puts("*** Testing wxPathList ***\n");
1820 wxPathList pathlist
;
1821 pathlist
.AddEnvList("PATH");
1822 wxString path
= pathlist
.FindValidPath("ls");
1825 printf("ERROR: command not found in the path.\n");
1829 printf("Command found in the path as '%s'.\n", path
.c_str());
1833 #endif // TEST_PATHLIST
1835 // ----------------------------------------------------------------------------
1836 // regular expressions
1837 // ----------------------------------------------------------------------------
1841 #include "wx/regex.h"
1843 static void TestRegExCompile()
1845 wxPuts(_T("*** Testing RE compilation ***\n"));
1847 static struct RegExCompTestData
1849 const wxChar
*pattern
;
1851 } regExCompTestData
[] =
1853 { _T("foo"), TRUE
},
1854 { _T("foo("), FALSE
},
1855 { _T("foo(bar"), FALSE
},
1856 { _T("foo(bar)"), TRUE
},
1857 { _T("foo["), FALSE
},
1858 { _T("foo[bar"), FALSE
},
1859 { _T("foo[bar]"), TRUE
},
1860 { _T("foo{"), TRUE
},
1861 { _T("foo{1"), FALSE
},
1862 { _T("foo{bar"), TRUE
},
1863 { _T("foo{1}"), TRUE
},
1864 { _T("foo{1,2}"), TRUE
},
1865 { _T("foo{bar}"), TRUE
},
1866 { _T("foo*"), TRUE
},
1867 { _T("foo**"), FALSE
},
1868 { _T("foo+"), TRUE
},
1869 { _T("foo++"), FALSE
},
1870 { _T("foo?"), TRUE
},
1871 { _T("foo??"), FALSE
},
1872 { _T("foo?+"), FALSE
},
1876 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1878 const RegExCompTestData
& data
= regExCompTestData
[n
];
1879 bool ok
= re
.Compile(data
.pattern
);
1881 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1883 ok
? _T("") : _T("not "),
1884 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1888 static void TestRegExMatch()
1890 wxPuts(_T("*** Testing RE matching ***\n"));
1892 static struct RegExMatchTestData
1894 const wxChar
*pattern
;
1897 } regExMatchTestData
[] =
1899 { _T("foo"), _T("bar"), FALSE
},
1900 { _T("foo"), _T("foobar"), TRUE
},
1901 { _T("^foo"), _T("foobar"), TRUE
},
1902 { _T("^foo"), _T("barfoo"), FALSE
},
1903 { _T("bar$"), _T("barbar"), TRUE
},
1904 { _T("bar$"), _T("barbar "), FALSE
},
1907 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1909 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1911 wxRegEx
re(data
.pattern
);
1912 bool ok
= re
.Matches(data
.text
);
1914 wxPrintf(_T("'%s' %s %s (%s)\n"),
1916 ok
? _T("matches") : _T("doesn't match"),
1918 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1922 static void TestRegExSubmatch()
1924 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1926 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1927 if ( !re
.IsValid() )
1929 wxPuts(_T("ERROR: compilation failed."));
1933 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
1935 if ( !re
.Matches(text
) )
1937 wxPuts(_T("ERROR: match expected."));
1941 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
1943 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1944 re
.GetMatch(text
, 3).c_str(),
1945 re
.GetMatch(text
, 2).c_str(),
1946 re
.GetMatch(text
, 4).c_str(),
1947 re
.GetMatch(text
, 1).c_str());
1951 static void TestRegExReplacement()
1953 wxPuts(_T("*** Testing RE replacement ***"));
1955 static struct RegExReplTestData
1959 const wxChar
*result
;
1961 } regExReplTestData
[] =
1963 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1964 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1965 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1966 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1967 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1968 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1969 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1972 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
1973 wxRegEx re
= pattern
;
1975 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
1977 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
1979 const RegExReplTestData
& data
= regExReplTestData
[n
];
1981 wxString text
= data
.text
;
1982 size_t nRepl
= re
.Replace(&text
, data
.repl
);
1984 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1985 data
.text
, data
.repl
,
1986 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
1988 if ( text
== data
.result
&& nRepl
== data
.count
)
1994 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1995 data
.count
, data
.result
);
2000 static void TestRegExInteractive()
2002 wxPuts(_T("*** Testing RE interactively ***"));
2007 printf("\nEnter a pattern: ");
2008 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2011 // kill the last '\n'
2012 pattern
[strlen(pattern
) - 1] = 0;
2015 if ( !re
.Compile(pattern
) )
2023 printf("Enter text to match: ");
2024 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2027 // kill the last '\n'
2028 text
[strlen(text
) - 1] = 0;
2030 if ( !re
.Matches(text
) )
2032 printf("No match.\n");
2036 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2039 for ( size_t n
= 1; ; n
++ )
2041 if ( !re
.GetMatch(&start
, &len
, n
) )
2046 printf("Subexpr %u matched '%s'\n",
2047 n
, wxString(text
+ start
, len
).c_str());
2054 #endif // TEST_REGEX
2056 // ----------------------------------------------------------------------------
2057 // registry and related stuff
2058 // ----------------------------------------------------------------------------
2060 // this is for MSW only
2063 #undef TEST_REGISTRY
2068 #include "wx/confbase.h"
2069 #include "wx/msw/regconf.h"
2071 static void TestRegConfWrite()
2073 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2074 regconf
.Write(_T("Hello"), wxString(_T("world")));
2077 #endif // TEST_REGCONF
2079 #ifdef TEST_REGISTRY
2081 #include "wx/msw/registry.h"
2083 // I chose this one because I liked its name, but it probably only exists under
2085 static const wxChar
*TESTKEY
=
2086 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2088 static void TestRegistryRead()
2090 puts("*** testing registry reading ***");
2092 wxRegKey
key(TESTKEY
);
2093 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2096 puts("ERROR: test key can't be opened, aborting test.");
2101 size_t nSubKeys
, nValues
;
2102 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2104 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2107 printf("Enumerating values:\n");
2111 bool cont
= key
.GetFirstValue(value
, dummy
);
2114 printf("Value '%s': type ", value
.c_str());
2115 switch ( key
.GetValueType(value
) )
2117 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2118 case wxRegKey::Type_String
: printf("SZ"); break;
2119 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2120 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2121 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2122 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2123 default: printf("other (unknown)"); break;
2126 printf(", value = ");
2127 if ( key
.IsNumericValue(value
) )
2130 key
.QueryValue(value
, &val
);
2136 key
.QueryValue(value
, val
);
2137 printf("'%s'", val
.c_str());
2139 key
.QueryRawValue(value
, val
);
2140 printf(" (raw value '%s')", val
.c_str());
2145 cont
= key
.GetNextValue(value
, dummy
);
2149 static void TestRegistryAssociation()
2152 The second call to deleteself genertaes an error message, with a
2153 messagebox saying .flo is crucial to system operation, while the .ddf
2154 call also fails, but with no error message
2159 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2161 key
= "ddxf_auto_file" ;
2162 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2164 key
= "ddxf_auto_file" ;
2165 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2168 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2170 key
= "program \"%1\"" ;
2172 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2174 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2176 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2178 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2182 #endif // TEST_REGISTRY
2184 // ----------------------------------------------------------------------------
2186 // ----------------------------------------------------------------------------
2190 #include "wx/socket.h"
2191 #include "wx/protocol/protocol.h"
2192 #include "wx/protocol/http.h"
2194 static void TestSocketServer()
2196 puts("*** Testing wxSocketServer ***\n");
2198 static const int PORT
= 3000;
2203 wxSocketServer
*server
= new wxSocketServer(addr
);
2204 if ( !server
->Ok() )
2206 puts("ERROR: failed to bind");
2213 printf("Server: waiting for connection on port %d...\n", PORT
);
2215 wxSocketBase
*socket
= server
->Accept();
2218 puts("ERROR: wxSocketServer::Accept() failed.");
2222 puts("Server: got a client.");
2224 server
->SetTimeout(60); // 1 min
2226 while ( socket
->IsConnected() )
2232 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2234 // don't log error if the client just close the connection
2235 if ( socket
->IsConnected() )
2237 puts("ERROR: in wxSocket::Read.");
2257 printf("Server: got '%s'.\n", s
.c_str());
2258 if ( s
== _T("bye") )
2265 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2266 socket
->Write("\r\n", 2);
2267 printf("Server: wrote '%s'.\n", s
.c_str());
2270 puts("Server: lost a client.");
2275 // same as "delete server" but is consistent with GUI programs
2279 static void TestSocketClient()
2281 puts("*** Testing wxSocketClient ***\n");
2283 static const char *hostname
= "www.wxwindows.org";
2286 addr
.Hostname(hostname
);
2289 printf("--- Attempting to connect to %s:80...\n", hostname
);
2291 wxSocketClient client
;
2292 if ( !client
.Connect(addr
) )
2294 printf("ERROR: failed to connect to %s\n", hostname
);
2298 printf("--- Connected to %s:%u...\n",
2299 addr
.Hostname().c_str(), addr
.Service());
2303 // could use simply "GET" here I suppose
2305 wxString::Format("GET http://%s/\r\n", hostname
);
2306 client
.Write(cmdGet
, cmdGet
.length());
2307 printf("--- Sent command '%s' to the server\n",
2308 MakePrintable(cmdGet
).c_str());
2309 client
.Read(buf
, WXSIZEOF(buf
));
2310 printf("--- Server replied:\n%s", buf
);
2314 #endif // TEST_SOCKETS
2316 // ----------------------------------------------------------------------------
2318 // ----------------------------------------------------------------------------
2322 #include "wx/protocol/ftp.h"
2326 #define FTP_ANONYMOUS
2328 #ifdef FTP_ANONYMOUS
2329 static const char *directory
= "/pub";
2330 static const char *filename
= "welcome.msg";
2332 static const char *directory
= "/etc";
2333 static const char *filename
= "issue";
2336 static bool TestFtpConnect()
2338 puts("*** Testing FTP connect ***");
2340 #ifdef FTP_ANONYMOUS
2341 static const char *hostname
= "ftp.wxwindows.org";
2343 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2344 #else // !FTP_ANONYMOUS
2345 static const char *hostname
= "localhost";
2348 fgets(user
, WXSIZEOF(user
), stdin
);
2349 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2353 printf("Password for %s: ", password
);
2354 fgets(password
, WXSIZEOF(password
), stdin
);
2355 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2356 ftp
.SetPassword(password
);
2358 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2359 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2361 if ( !ftp
.Connect(hostname
) )
2363 printf("ERROR: failed to connect to %s\n", hostname
);
2369 printf("--- Connected to %s, current directory is '%s'\n",
2370 hostname
, ftp
.Pwd().c_str());
2376 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2377 static void TestFtpWuFtpd()
2380 static const char *hostname
= "ftp.eudora.com";
2381 if ( !ftp
.Connect(hostname
) )
2383 printf("ERROR: failed to connect to %s\n", hostname
);
2387 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2388 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2391 printf("ERROR: couldn't get input stream for %s\n", filename
);
2395 size_t size
= in
->StreamSize();
2396 printf("Reading file %s (%u bytes)...", filename
, size
);
2398 char *data
= new char[size
];
2399 if ( !in
->Read(data
, size
) )
2401 puts("ERROR: read error");
2405 printf("Successfully retrieved the file.\n");
2414 static void TestFtpList()
2416 puts("*** Testing wxFTP file listing ***\n");
2419 if ( !ftp
.ChDir(directory
) )
2421 printf("ERROR: failed to cd to %s\n", directory
);
2424 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2426 // test NLIST and LIST
2427 wxArrayString files
;
2428 if ( !ftp
.GetFilesList(files
) )
2430 puts("ERROR: failed to get NLIST of files");
2434 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2435 size_t count
= files
.GetCount();
2436 for ( size_t n
= 0; n
< count
; n
++ )
2438 printf("\t%s\n", files
[n
].c_str());
2440 puts("End of the file list");
2443 if ( !ftp
.GetDirList(files
) )
2445 puts("ERROR: failed to get LIST of files");
2449 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2450 size_t count
= files
.GetCount();
2451 for ( size_t n
= 0; n
< count
; n
++ )
2453 printf("\t%s\n", files
[n
].c_str());
2455 puts("End of the file list");
2458 if ( !ftp
.ChDir(_T("..")) )
2460 puts("ERROR: failed to cd to ..");
2463 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2466 static void TestFtpDownload()
2468 puts("*** Testing wxFTP download ***\n");
2471 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2474 printf("ERROR: couldn't get input stream for %s\n", filename
);
2478 size_t size
= in
->StreamSize();
2479 printf("Reading file %s (%u bytes)...", filename
, size
);
2482 char *data
= new char[size
];
2483 if ( !in
->Read(data
, size
) )
2485 puts("ERROR: read error");
2489 printf("\nContents of %s:\n%s\n", filename
, data
);
2497 static void TestFtpFileSize()
2499 puts("*** Testing FTP SIZE command ***");
2501 if ( !ftp
.ChDir(directory
) )
2503 printf("ERROR: failed to cd to %s\n", directory
);
2506 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2508 if ( ftp
.FileExists(filename
) )
2510 int size
= ftp
.GetFileSize(filename
);
2512 printf("ERROR: couldn't get size of '%s'\n", filename
);
2514 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2518 printf("ERROR: '%s' doesn't exist\n", filename
);
2522 static void TestFtpMisc()
2524 puts("*** Testing miscellaneous wxFTP functions ***");
2526 if ( ftp
.SendCommand("STAT") != '2' )
2528 puts("ERROR: STAT failed");
2532 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2535 if ( ftp
.SendCommand("HELP SITE") != '2' )
2537 puts("ERROR: HELP SITE failed");
2541 printf("The list of site-specific commands:\n\n%s\n",
2542 ftp
.GetLastResult().c_str());
2546 static void TestFtpInteractive()
2548 puts("\n*** Interactive wxFTP test ***");
2554 printf("Enter FTP command: ");
2555 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2558 // kill the last '\n'
2559 buf
[strlen(buf
) - 1] = 0;
2561 // special handling of LIST and NLST as they require data connection
2562 wxString
start(buf
, 4);
2564 if ( start
== "LIST" || start
== "NLST" )
2567 if ( strlen(buf
) > 4 )
2570 wxArrayString files
;
2571 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2573 printf("ERROR: failed to get %s of files\n", start
.c_str());
2577 printf("--- %s of '%s' under '%s':\n",
2578 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2579 size_t count
= files
.GetCount();
2580 for ( size_t n
= 0; n
< count
; n
++ )
2582 printf("\t%s\n", files
[n
].c_str());
2584 puts("--- End of the file list");
2589 char ch
= ftp
.SendCommand(buf
);
2590 printf("Command %s", ch
? "succeeded" : "failed");
2593 printf(" (return code %c)", ch
);
2596 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2600 puts("\n*** done ***");
2603 static void TestFtpUpload()
2605 puts("*** Testing wxFTP uploading ***\n");
2608 static const char *file1
= "test1";
2609 static const char *file2
= "test2";
2610 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2613 printf("--- Uploading to %s ---\n", file1
);
2614 out
->Write("First hello", 11);
2618 // send a command to check the remote file
2619 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2621 printf("ERROR: STAT %s failed\n", file1
);
2625 printf("STAT %s returned:\n\n%s\n",
2626 file1
, ftp
.GetLastResult().c_str());
2629 out
= ftp
.GetOutputStream(file2
);
2632 printf("--- Uploading to %s ---\n", file1
);
2633 out
->Write("Second hello", 12);
2640 // ----------------------------------------------------------------------------
2642 // ----------------------------------------------------------------------------
2646 #include "wx/wfstream.h"
2647 #include "wx/mstream.h"
2649 static void TestFileStream()
2651 puts("*** Testing wxFileInputStream ***");
2653 static const wxChar
*filename
= _T("testdata.fs");
2655 wxFileOutputStream
fsOut(filename
);
2656 fsOut
.Write("foo", 3);
2659 wxFileInputStream
fsIn(filename
);
2660 printf("File stream size: %u\n", fsIn
.GetSize());
2661 while ( !fsIn
.Eof() )
2663 putchar(fsIn
.GetC());
2666 if ( !wxRemoveFile(filename
) )
2668 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2671 puts("\n*** wxFileInputStream test done ***");
2674 static void TestMemoryStream()
2676 puts("*** Testing wxMemoryInputStream ***");
2679 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2681 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2682 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2683 while ( !memInpStream
.Eof() )
2685 putchar(memInpStream
.GetC());
2688 puts("\n*** wxMemoryInputStream test done ***");
2691 #endif // TEST_STREAMS
2693 // ----------------------------------------------------------------------------
2695 // ----------------------------------------------------------------------------
2699 #include "wx/timer.h"
2700 #include "wx/utils.h"
2702 static void TestStopWatch()
2704 puts("*** Testing wxStopWatch ***\n");
2707 printf("Sleeping 3 seconds...");
2709 printf("\telapsed time: %ldms\n", sw
.Time());
2712 printf("Sleeping 2 more seconds...");
2714 printf("\telapsed time: %ldms\n", sw
.Time());
2717 printf("And 3 more seconds...");
2719 printf("\telapsed time: %ldms\n", sw
.Time());
2722 puts("\nChecking for 'backwards clock' bug...");
2723 for ( size_t n
= 0; n
< 70; n
++ )
2727 for ( size_t m
= 0; m
< 100000; m
++ )
2729 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2731 puts("\ntime is negative - ERROR!");
2741 #endif // TEST_TIMER
2743 // ----------------------------------------------------------------------------
2745 // ----------------------------------------------------------------------------
2749 #include "wx/vcard.h"
2751 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2754 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2758 wxString(_T('\t'), level
).c_str(),
2759 vcObj
->GetName().c_str());
2762 switch ( vcObj
->GetType() )
2764 case wxVCardObject::String
:
2765 case wxVCardObject::UString
:
2768 vcObj
->GetValue(&val
);
2769 value
<< _T('"') << val
<< _T('"');
2773 case wxVCardObject::Int
:
2776 vcObj
->GetValue(&i
);
2777 value
.Printf(_T("%u"), i
);
2781 case wxVCardObject::Long
:
2784 vcObj
->GetValue(&l
);
2785 value
.Printf(_T("%lu"), l
);
2789 case wxVCardObject::None
:
2792 case wxVCardObject::Object
:
2793 value
= _T("<node>");
2797 value
= _T("<unknown value type>");
2801 printf(" = %s", value
.c_str());
2804 DumpVObject(level
+ 1, *vcObj
);
2807 vcObj
= vcard
.GetNextProp(&cookie
);
2811 static void DumpVCardAddresses(const wxVCard
& vcard
)
2813 puts("\nShowing all addresses from vCard:\n");
2817 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2821 int flags
= addr
->GetFlags();
2822 if ( flags
& wxVCardAddress::Domestic
)
2824 flagsStr
<< _T("domestic ");
2826 if ( flags
& wxVCardAddress::Intl
)
2828 flagsStr
<< _T("international ");
2830 if ( flags
& wxVCardAddress::Postal
)
2832 flagsStr
<< _T("postal ");
2834 if ( flags
& wxVCardAddress::Parcel
)
2836 flagsStr
<< _T("parcel ");
2838 if ( flags
& wxVCardAddress::Home
)
2840 flagsStr
<< _T("home ");
2842 if ( flags
& wxVCardAddress::Work
)
2844 flagsStr
<< _T("work ");
2847 printf("Address %u:\n"
2849 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2852 addr
->GetPostOffice().c_str(),
2853 addr
->GetExtAddress().c_str(),
2854 addr
->GetStreet().c_str(),
2855 addr
->GetLocality().c_str(),
2856 addr
->GetRegion().c_str(),
2857 addr
->GetPostalCode().c_str(),
2858 addr
->GetCountry().c_str()
2862 addr
= vcard
.GetNextAddress(&cookie
);
2866 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2868 puts("\nShowing all phone numbers from vCard:\n");
2872 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2876 int flags
= phone
->GetFlags();
2877 if ( flags
& wxVCardPhoneNumber::Voice
)
2879 flagsStr
<< _T("voice ");
2881 if ( flags
& wxVCardPhoneNumber::Fax
)
2883 flagsStr
<< _T("fax ");
2885 if ( flags
& wxVCardPhoneNumber::Cellular
)
2887 flagsStr
<< _T("cellular ");
2889 if ( flags
& wxVCardPhoneNumber::Modem
)
2891 flagsStr
<< _T("modem ");
2893 if ( flags
& wxVCardPhoneNumber::Home
)
2895 flagsStr
<< _T("home ");
2897 if ( flags
& wxVCardPhoneNumber::Work
)
2899 flagsStr
<< _T("work ");
2902 printf("Phone number %u:\n"
2907 phone
->GetNumber().c_str()
2911 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2915 static void TestVCardRead()
2917 puts("*** Testing wxVCard reading ***\n");
2919 wxVCard
vcard(_T("vcard.vcf"));
2920 if ( !vcard
.IsOk() )
2922 puts("ERROR: couldn't load vCard.");
2926 // read individual vCard properties
2927 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2931 vcObj
->GetValue(&value
);
2936 value
= _T("<none>");
2939 printf("Full name retrieved directly: %s\n", value
.c_str());
2942 if ( !vcard
.GetFullName(&value
) )
2944 value
= _T("<none>");
2947 printf("Full name from wxVCard API: %s\n", value
.c_str());
2949 // now show how to deal with multiply occuring properties
2950 DumpVCardAddresses(vcard
);
2951 DumpVCardPhoneNumbers(vcard
);
2953 // and finally show all
2954 puts("\nNow dumping the entire vCard:\n"
2955 "-----------------------------\n");
2957 DumpVObject(0, vcard
);
2961 static void TestVCardWrite()
2963 puts("*** Testing wxVCard writing ***\n");
2966 if ( !vcard
.IsOk() )
2968 puts("ERROR: couldn't create vCard.");
2973 vcard
.SetName("Zeitlin", "Vadim");
2974 vcard
.SetFullName("Vadim Zeitlin");
2975 vcard
.SetOrganization("wxWindows", "R&D");
2977 // just dump the vCard back
2978 puts("Entire vCard follows:\n");
2979 puts(vcard
.Write());
2983 #endif // TEST_VCARD
2985 // ----------------------------------------------------------------------------
2986 // wide char (Unicode) support
2987 // ----------------------------------------------------------------------------
2991 #include "wx/strconv.h"
2992 #include "wx/fontenc.h"
2993 #include "wx/encconv.h"
2994 #include "wx/buffer.h"
2996 static void TestUtf8()
2998 puts("*** Testing UTF8 support ***\n");
3000 static const char textInUtf8
[] =
3002 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3003 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3004 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3005 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3006 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3007 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3008 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3013 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3015 puts("ERROR: UTF-8 decoding failed.");
3019 // using wxEncodingConverter
3021 wxEncodingConverter ec
;
3022 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3023 ec
.Convert(wbuf
, buf
);
3024 #else // using wxCSConv
3025 wxCSConv
conv(_T("koi8-r"));
3026 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3028 puts("ERROR: conversion to KOI8-R failed.");
3033 printf("The resulting string (in koi8-r): %s\n", buf
);
3037 #endif // TEST_WCHAR
3039 // ----------------------------------------------------------------------------
3041 // ----------------------------------------------------------------------------
3045 #include "wx/filesys.h"
3046 #include "wx/fs_zip.h"
3047 #include "wx/zipstrm.h"
3049 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3051 static void TestZipStreamRead()
3053 puts("*** Testing ZIP reading ***\n");
3055 static const wxChar
*filename
= _T("foo");
3056 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3057 printf("Archive size: %u\n", istr
.GetSize());
3059 printf("Dumping the file '%s':\n", filename
);
3060 while ( !istr
.Eof() )
3062 putchar(istr
.GetC());
3066 puts("\n----- done ------");
3069 static void DumpZipDirectory(wxFileSystem
& fs
,
3070 const wxString
& dir
,
3071 const wxString
& indent
)
3073 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3074 TESTFILE_ZIP
, dir
.c_str());
3075 wxString wildcard
= prefix
+ _T("/*");
3077 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3078 while ( !dirname
.empty() )
3080 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3082 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3087 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3089 DumpZipDirectory(fs
, dirname
,
3090 indent
+ wxString(_T(' '), 4));
3092 dirname
= fs
.FindNext();
3095 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3096 while ( !filename
.empty() )
3098 if ( !filename
.StartsWith(prefix
, &filename
) )
3100 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3105 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3107 filename
= fs
.FindNext();
3111 static void TestZipFileSystem()
3113 puts("*** Testing ZIP file system ***\n");
3115 wxFileSystem::AddHandler(new wxZipFSHandler
);
3117 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3119 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3124 // ----------------------------------------------------------------------------
3126 // ----------------------------------------------------------------------------
3130 #include "wx/zstream.h"
3131 #include "wx/wfstream.h"
3133 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3134 static const char *TEST_DATA
= "hello and hello again";
3136 static void TestZlibStreamWrite()
3138 puts("*** Testing Zlib stream reading ***\n");
3140 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3141 wxZlibOutputStream
ostr(fileOutStream
, 0);
3142 printf("Compressing the test string... ");
3143 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3146 puts("(ERROR: failed)");
3153 puts("\n----- done ------");
3156 static void TestZlibStreamRead()
3158 puts("*** Testing Zlib stream reading ***\n");
3160 wxFileInputStream
fileInStream(FILENAME_GZ
);
3161 wxZlibInputStream
istr(fileInStream
);
3162 printf("Archive size: %u\n", istr
.GetSize());
3164 puts("Dumping the file:");
3165 while ( !istr
.Eof() )
3167 putchar(istr
.GetC());
3171 puts("\n----- done ------");
3176 // ----------------------------------------------------------------------------
3178 // ----------------------------------------------------------------------------
3180 #ifdef TEST_DATETIME
3184 #include "wx/date.h"
3185 #include "wx/datetime.h"
3190 wxDateTime::wxDateTime_t day
;
3191 wxDateTime::Month month
;
3193 wxDateTime::wxDateTime_t hour
, min
, sec
;
3195 wxDateTime::WeekDay wday
;
3196 time_t gmticks
, ticks
;
3198 void Init(const wxDateTime::Tm
& tm
)
3207 gmticks
= ticks
= -1;
3210 wxDateTime
DT() const
3211 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3213 bool SameDay(const wxDateTime::Tm
& tm
) const
3215 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3218 wxString
Format() const
3221 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3223 wxDateTime::GetMonthName(month
).c_str(),
3225 abs(wxDateTime::ConvertYearToBC(year
)),
3226 year
> 0 ? "AD" : "BC");
3230 wxString
FormatDate() const
3233 s
.Printf("%02d-%s-%4d%s",
3235 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3236 abs(wxDateTime::ConvertYearToBC(year
)),
3237 year
> 0 ? "AD" : "BC");
3242 static const Date testDates
[] =
3244 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3245 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3246 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3247 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3248 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3249 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3250 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3251 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3252 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3253 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3254 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3255 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3256 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3257 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3258 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3261 // this test miscellaneous static wxDateTime functions
3262 static void TestTimeStatic()
3264 puts("\n*** wxDateTime static methods test ***");
3266 // some info about the current date
3267 int year
= wxDateTime::GetCurrentYear();
3268 printf("Current year %d is %sa leap one and has %d days.\n",
3270 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3271 wxDateTime::GetNumberOfDays(year
));
3273 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3274 printf("Current month is '%s' ('%s') and it has %d days\n",
3275 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3276 wxDateTime::GetMonthName(month
).c_str(),
3277 wxDateTime::GetNumberOfDays(month
));
3280 static const size_t nYears
= 5;
3281 static const size_t years
[2][nYears
] =
3283 // first line: the years to test
3284 { 1990, 1976, 2000, 2030, 1984, },
3286 // second line: TRUE if leap, FALSE otherwise
3287 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3290 for ( size_t n
= 0; n
< nYears
; n
++ )
3292 int year
= years
[0][n
];
3293 bool should
= years
[1][n
] != 0,
3294 is
= wxDateTime::IsLeapYear(year
);
3296 printf("Year %d is %sa leap year (%s)\n",
3299 should
== is
? "ok" : "ERROR");
3301 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3305 // test constructing wxDateTime objects
3306 static void TestTimeSet()
3308 puts("\n*** wxDateTime construction test ***");
3310 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3312 const Date
& d1
= testDates
[n
];
3313 wxDateTime dt
= d1
.DT();
3316 d2
.Init(dt
.GetTm());
3318 wxString s1
= d1
.Format(),
3321 printf("Date: %s == %s (%s)\n",
3322 s1
.c_str(), s2
.c_str(),
3323 s1
== s2
? "ok" : "ERROR");
3327 // test time zones stuff
3328 static void TestTimeZones()
3330 puts("\n*** wxDateTime timezone test ***");
3332 wxDateTime now
= wxDateTime::Now();
3334 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3335 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3336 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3337 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3338 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3339 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3341 wxDateTime::Tm tm
= now
.GetTm();
3342 if ( wxDateTime(tm
) != now
)
3344 printf("ERROR: got %s instead of %s\n",
3345 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3349 // test some minimal support for the dates outside the standard range
3350 static void TestTimeRange()
3352 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3354 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3356 printf("Unix epoch:\t%s\n",
3357 wxDateTime(2440587.5).Format(fmt
).c_str());
3358 printf("Feb 29, 0: \t%s\n",
3359 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3360 printf("JDN 0: \t%s\n",
3361 wxDateTime(0.0).Format(fmt
).c_str());
3362 printf("Jan 1, 1AD:\t%s\n",
3363 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3364 printf("May 29, 2099:\t%s\n",
3365 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3368 static void TestTimeTicks()
3370 puts("\n*** wxDateTime ticks test ***");
3372 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3374 const Date
& d
= testDates
[n
];
3375 if ( d
.ticks
== -1 )
3378 wxDateTime dt
= d
.DT();
3379 long ticks
= (dt
.GetValue() / 1000).ToLong();
3380 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3381 if ( ticks
== d
.ticks
)
3387 printf(" (ERROR: should be %ld, delta = %ld)\n",
3388 d
.ticks
, ticks
- d
.ticks
);
3391 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3392 ticks
= (dt
.GetValue() / 1000).ToLong();
3393 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3394 if ( ticks
== d
.gmticks
)
3400 printf(" (ERROR: should be %ld, delta = %ld)\n",
3401 d
.gmticks
, ticks
- d
.gmticks
);
3408 // test conversions to JDN &c
3409 static void TestTimeJDN()
3411 puts("\n*** wxDateTime to JDN test ***");
3413 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3415 const Date
& d
= testDates
[n
];
3416 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3417 double jdn
= dt
.GetJulianDayNumber();
3419 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3426 printf(" (ERROR: should be %f, delta = %f)\n",
3427 d
.jdn
, jdn
- d
.jdn
);
3432 // test week days computation
3433 static void TestTimeWDays()
3435 puts("\n*** wxDateTime weekday test ***");
3437 // test GetWeekDay()
3439 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3441 const Date
& d
= testDates
[n
];
3442 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3444 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3447 wxDateTime::GetWeekDayName(wday
).c_str());
3448 if ( wday
== d
.wday
)
3454 printf(" (ERROR: should be %s)\n",
3455 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3461 // test SetToWeekDay()
3462 struct WeekDateTestData
3464 Date date
; // the real date (precomputed)
3465 int nWeek
; // its week index in the month
3466 wxDateTime::WeekDay wday
; // the weekday
3467 wxDateTime::Month month
; // the month
3468 int year
; // and the year
3470 wxString
Format() const
3473 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3475 case 1: which
= "first"; break;
3476 case 2: which
= "second"; break;
3477 case 3: which
= "third"; break;
3478 case 4: which
= "fourth"; break;
3479 case 5: which
= "fifth"; break;
3481 case -1: which
= "last"; break;
3486 which
+= " from end";
3489 s
.Printf("The %s %s of %s in %d",
3491 wxDateTime::GetWeekDayName(wday
).c_str(),
3492 wxDateTime::GetMonthName(month
).c_str(),
3499 // the array data was generated by the following python program
3501 from DateTime import *
3502 from whrandom import *
3503 from string import *
3505 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3506 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3508 week = DateTimeDelta(7)
3511 year = randint(1900, 2100)
3512 month = randint(1, 12)
3513 day = randint(1, 28)
3514 dt = DateTime(year, month, day)
3515 wday = dt.day_of_week
3517 countFromEnd = choice([-1, 1])
3520 while dt.month is month:
3521 dt = dt - countFromEnd * week
3522 weekNum = weekNum + countFromEnd
3524 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3526 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3527 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3530 static const WeekDateTestData weekDatesTestData
[] =
3532 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3533 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3534 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3535 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3536 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3537 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3538 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3539 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3540 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3541 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3542 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3543 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3544 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3545 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3546 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3547 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3548 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3549 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3550 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3551 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3554 static const char *fmt
= "%d-%b-%Y";
3557 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3559 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3561 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3563 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3565 const Date
& d
= wd
.date
;
3566 if ( d
.SameDay(dt
.GetTm()) )
3572 dt
.Set(d
.day
, d
.month
, d
.year
);
3574 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3579 // test the computation of (ISO) week numbers
3580 static void TestTimeWNumber()
3582 puts("\n*** wxDateTime week number test ***");
3584 struct WeekNumberTestData
3586 Date date
; // the date
3587 wxDateTime::wxDateTime_t week
; // the week number in the year
3588 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3589 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3590 wxDateTime::wxDateTime_t dnum
; // day number in the year
3593 // data generated with the following python script:
3595 from DateTime import *
3596 from whrandom import *
3597 from string import *
3599 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3600 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3602 def GetMonthWeek(dt):
3603 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3604 if weekNumMonth < 0:
3605 weekNumMonth = weekNumMonth + 53
3608 def GetLastSundayBefore(dt):
3609 if dt.iso_week[2] == 7:
3612 return dt - DateTimeDelta(dt.iso_week[2])
3615 year = randint(1900, 2100)
3616 month = randint(1, 12)
3617 day = randint(1, 28)
3618 dt = DateTime(year, month, day)
3619 dayNum = dt.day_of_year
3620 weekNum = dt.iso_week[1]
3621 weekNumMonth = GetMonthWeek(dt)
3624 dtSunday = GetLastSundayBefore(dt)
3626 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3627 weekNumMonth2 = weekNumMonth2 + 1
3628 dtSunday = dtSunday - DateTimeDelta(7)
3630 data = { 'day': rjust(`day`, 2), \
3631 'month': monthNames[month - 1], \
3633 'weekNum': rjust(`weekNum`, 2), \
3634 'weekNumMonth': weekNumMonth, \
3635 'weekNumMonth2': weekNumMonth2, \
3636 'dayNum': rjust(`dayNum`, 3) }
3638 print " { { %(day)s, "\
3639 "wxDateTime::%(month)s, "\
3642 "%(weekNumMonth)s, "\
3643 "%(weekNumMonth2)s, "\
3644 "%(dayNum)s }," % data
3647 static const WeekNumberTestData weekNumberTestDates
[] =
3649 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3650 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3651 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3652 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3653 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3654 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3655 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3656 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3657 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3658 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3659 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3660 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3661 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3662 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3663 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3664 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3665 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3666 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3667 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3668 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3671 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3673 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3674 const Date
& d
= wn
.date
;
3676 wxDateTime dt
= d
.DT();
3678 wxDateTime::wxDateTime_t
3679 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3680 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3681 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3682 dnum
= dt
.GetDayOfYear();
3684 printf("%s: the day number is %d",
3685 d
.FormatDate().c_str(), dnum
);
3686 if ( dnum
== wn
.dnum
)
3692 printf(" (ERROR: should be %d)", wn
.dnum
);
3695 printf(", week in month is %d", wmon
);
3696 if ( wmon
== wn
.wmon
)
3702 printf(" (ERROR: should be %d)", wn
.wmon
);
3705 printf(" or %d", wmon2
);
3706 if ( wmon2
== wn
.wmon2
)
3712 printf(" (ERROR: should be %d)", wn
.wmon2
);
3715 printf(", week in year is %d", week
);
3716 if ( week
== wn
.week
)
3722 printf(" (ERROR: should be %d)\n", wn
.week
);
3727 // test DST calculations
3728 static void TestTimeDST()
3730 puts("\n*** wxDateTime DST test ***");
3732 printf("DST is%s in effect now.\n\n",
3733 wxDateTime::Now().IsDST() ? "" : " not");
3735 // taken from http://www.energy.ca.gov/daylightsaving.html
3736 static const Date datesDST
[2][2004 - 1900 + 1] =
3739 { 1, wxDateTime::Apr
, 1990 },
3740 { 7, wxDateTime::Apr
, 1991 },
3741 { 5, wxDateTime::Apr
, 1992 },
3742 { 4, wxDateTime::Apr
, 1993 },
3743 { 3, wxDateTime::Apr
, 1994 },
3744 { 2, wxDateTime::Apr
, 1995 },
3745 { 7, wxDateTime::Apr
, 1996 },
3746 { 6, wxDateTime::Apr
, 1997 },
3747 { 5, wxDateTime::Apr
, 1998 },
3748 { 4, wxDateTime::Apr
, 1999 },
3749 { 2, wxDateTime::Apr
, 2000 },
3750 { 1, wxDateTime::Apr
, 2001 },
3751 { 7, wxDateTime::Apr
, 2002 },
3752 { 6, wxDateTime::Apr
, 2003 },
3753 { 4, wxDateTime::Apr
, 2004 },
3756 { 28, wxDateTime::Oct
, 1990 },
3757 { 27, wxDateTime::Oct
, 1991 },
3758 { 25, wxDateTime::Oct
, 1992 },
3759 { 31, wxDateTime::Oct
, 1993 },
3760 { 30, wxDateTime::Oct
, 1994 },
3761 { 29, wxDateTime::Oct
, 1995 },
3762 { 27, wxDateTime::Oct
, 1996 },
3763 { 26, wxDateTime::Oct
, 1997 },
3764 { 25, wxDateTime::Oct
, 1998 },
3765 { 31, wxDateTime::Oct
, 1999 },
3766 { 29, wxDateTime::Oct
, 2000 },
3767 { 28, wxDateTime::Oct
, 2001 },
3768 { 27, wxDateTime::Oct
, 2002 },
3769 { 26, wxDateTime::Oct
, 2003 },
3770 { 31, wxDateTime::Oct
, 2004 },
3775 for ( year
= 1990; year
< 2005; year
++ )
3777 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3778 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3780 printf("DST period in the US for year %d: from %s to %s",
3781 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3783 size_t n
= year
- 1990;
3784 const Date
& dBegin
= datesDST
[0][n
];
3785 const Date
& dEnd
= datesDST
[1][n
];
3787 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3793 printf(" (ERROR: should be %s %d to %s %d)\n",
3794 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3795 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3801 for ( year
= 1990; year
< 2005; year
++ )
3803 printf("DST period in Europe for year %d: from %s to %s\n",
3805 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3806 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3810 // test wxDateTime -> text conversion
3811 static void TestTimeFormat()
3813 puts("\n*** wxDateTime formatting test ***");
3815 // some information may be lost during conversion, so store what kind
3816 // of info should we recover after a round trip
3819 CompareNone
, // don't try comparing
3820 CompareBoth
, // dates and times should be identical
3821 CompareDate
, // dates only
3822 CompareTime
// time only
3827 CompareKind compareKind
;
3829 } formatTestFormats
[] =
3831 { CompareBoth
, "---> %c" },
3832 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3833 { CompareBoth
, "Date is %x, time is %X" },
3834 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3835 { CompareNone
, "The day of year: %j, the week of year: %W" },
3836 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3839 static const Date formatTestDates
[] =
3841 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3842 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3844 // this test can't work for other centuries because it uses two digit
3845 // years in formats, so don't even try it
3846 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3847 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3848 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3852 // an extra test (as it doesn't depend on date, don't do it in the loop)
3853 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3855 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3859 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3860 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3862 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3863 printf("%s", s
.c_str());
3865 // what can we recover?
3866 int kind
= formatTestFormats
[n
].compareKind
;
3870 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3873 // converion failed - should it have?
3874 if ( kind
== CompareNone
)
3877 puts(" (ERROR: conversion back failed)");
3881 // should have parsed the entire string
3882 puts(" (ERROR: conversion back stopped too soon)");
3886 bool equal
= FALSE
; // suppress compilaer warning
3894 equal
= dt
.IsSameDate(dt2
);
3898 equal
= dt
.IsSameTime(dt2
);
3904 printf(" (ERROR: got back '%s' instead of '%s')\n",
3905 dt2
.Format().c_str(), dt
.Format().c_str());
3916 // test text -> wxDateTime conversion
3917 static void TestTimeParse()
3919 puts("\n*** wxDateTime parse test ***");
3921 struct ParseTestData
3928 static const ParseTestData parseTestDates
[] =
3930 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3931 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3934 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3936 const char *format
= parseTestDates
[n
].format
;
3938 printf("%s => ", format
);
3941 if ( dt
.ParseRfc822Date(format
) )
3943 printf("%s ", dt
.Format().c_str());
3945 if ( parseTestDates
[n
].good
)
3947 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3954 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3959 puts("(ERROR: bad format)");
3964 printf("bad format (%s)\n",
3965 parseTestDates
[n
].good
? "ERROR" : "ok");
3970 static void TestDateTimeInteractive()
3972 puts("\n*** interactive wxDateTime tests ***");
3978 printf("Enter a date: ");
3979 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3982 // kill the last '\n'
3983 buf
[strlen(buf
) - 1] = 0;
3986 const char *p
= dt
.ParseDate(buf
);
3989 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3995 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3998 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3999 dt
.Format("%b %d, %Y").c_str(),
4001 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4002 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4003 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4006 puts("\n*** done ***");
4009 static void TestTimeMS()
4011 puts("*** testing millisecond-resolution support in wxDateTime ***");
4013 wxDateTime dt1
= wxDateTime::Now(),
4014 dt2
= wxDateTime::UNow();
4016 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4017 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4018 printf("Dummy loop: ");
4019 for ( int i
= 0; i
< 6000; i
++ )
4021 //for ( int j = 0; j < 10; j++ )
4024 s
.Printf("%g", sqrt(i
));
4033 dt2
= wxDateTime::UNow();
4034 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4036 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4038 puts("\n*** done ***");
4041 static void TestTimeArithmetics()
4043 puts("\n*** testing arithmetic operations on wxDateTime ***");
4045 static const struct ArithmData
4047 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4048 : span(sp
), name(nam
) { }
4052 } testArithmData
[] =
4054 ArithmData(wxDateSpan::Day(), "day"),
4055 ArithmData(wxDateSpan::Week(), "week"),
4056 ArithmData(wxDateSpan::Month(), "month"),
4057 ArithmData(wxDateSpan::Year(), "year"),
4058 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4061 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4063 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4065 wxDateSpan span
= testArithmData
[n
].span
;
4069 const char *name
= testArithmData
[n
].name
;
4070 printf("%s + %s = %s, %s - %s = %s\n",
4071 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4072 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4074 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4075 if ( dt1
- span
== dt
)
4081 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4084 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4085 if ( dt2
+ span
== dt
)
4091 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4094 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4095 if ( dt2
+ 2*span
== dt1
)
4101 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4108 static void TestTimeHolidays()
4110 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4112 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4113 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4114 dtEnd
= dtStart
.GetLastMonthDay();
4116 wxDateTimeArray hol
;
4117 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4119 const wxChar
*format
= "%d-%b-%Y (%a)";
4121 printf("All holidays between %s and %s:\n",
4122 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4124 size_t count
= hol
.GetCount();
4125 for ( size_t n
= 0; n
< count
; n
++ )
4127 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4133 static void TestTimeZoneBug()
4135 puts("\n*** testing for DST/timezone bug ***\n");
4137 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4138 for ( int i
= 0; i
< 31; i
++ )
4140 printf("Date %s: week day %s.\n",
4141 date
.Format(_T("%d-%m-%Y")).c_str(),
4142 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4144 date
+= wxDateSpan::Day();
4150 static void TestTimeSpanFormat()
4152 puts("\n*** wxTimeSpan tests ***");
4154 static const char *formats
[] =
4156 _T("(default) %H:%M:%S"),
4157 _T("%E weeks and %D days"),
4158 _T("%l milliseconds"),
4159 _T("(with ms) %H:%M:%S:%l"),
4160 _T("100%% of minutes is %M"), // test "%%"
4161 _T("%D days and %H hours"),
4162 _T("or also %S seconds"),
4165 wxTimeSpan
ts1(1, 2, 3, 4),
4167 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4169 printf("ts1 = %s\tts2 = %s\n",
4170 ts1
.Format(formats
[n
]).c_str(),
4171 ts2
.Format(formats
[n
]).c_str());
4179 // test compatibility with the old wxDate/wxTime classes
4180 static void TestTimeCompatibility()
4182 puts("\n*** wxDateTime compatibility test ***");
4184 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4185 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4187 double jdnNow
= wxDateTime::Now().GetJDN();
4188 long jdnMidnight
= (long)(jdnNow
- 0.5);
4189 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4191 jdnMidnight
= wxDate().Set().GetJulianDate();
4192 printf("wxDateTime for today: %s\n",
4193 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4195 int flags
= wxEUROPEAN
;//wxFULL;
4198 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4199 for ( int n
= 0; n
< 7; n
++ )
4201 printf("Previous %s is %s\n",
4202 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4203 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4209 #endif // TEST_DATETIME
4211 // ----------------------------------------------------------------------------
4213 // ----------------------------------------------------------------------------
4217 #include "wx/thread.h"
4219 static size_t gs_counter
= (size_t)-1;
4220 static wxCriticalSection gs_critsect
;
4221 static wxCondition gs_cond
;
4223 class MyJoinableThread
: public wxThread
4226 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4227 { m_n
= n
; Create(); }
4229 // thread execution starts here
4230 virtual ExitCode
Entry();
4236 wxThread::ExitCode
MyJoinableThread::Entry()
4238 unsigned long res
= 1;
4239 for ( size_t n
= 1; n
< m_n
; n
++ )
4243 // it's a loooong calculation :-)
4247 return (ExitCode
)res
;
4250 class MyDetachedThread
: public wxThread
4253 MyDetachedThread(size_t n
, char ch
)
4257 m_cancelled
= FALSE
;
4262 // thread execution starts here
4263 virtual ExitCode
Entry();
4266 virtual void OnExit();
4269 size_t m_n
; // number of characters to write
4270 char m_ch
; // character to write
4272 bool m_cancelled
; // FALSE if we exit normally
4275 wxThread::ExitCode
MyDetachedThread::Entry()
4278 wxCriticalSectionLocker
lock(gs_critsect
);
4279 if ( gs_counter
== (size_t)-1 )
4285 for ( size_t n
= 0; n
< m_n
; n
++ )
4287 if ( TestDestroy() )
4297 wxThread::Sleep(100);
4303 void MyDetachedThread::OnExit()
4305 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4307 wxCriticalSectionLocker
lock(gs_critsect
);
4308 if ( !--gs_counter
&& !m_cancelled
)
4312 void TestDetachedThreads()
4314 puts("\n*** Testing detached threads ***");
4316 static const size_t nThreads
= 3;
4317 MyDetachedThread
*threads
[nThreads
];
4319 for ( n
= 0; n
< nThreads
; n
++ )
4321 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4324 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4325 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4327 for ( n
= 0; n
< nThreads
; n
++ )
4332 // wait until all threads terminate
4338 void TestJoinableThreads()
4340 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4342 // calc 10! in the background
4343 MyJoinableThread
thread(10);
4346 printf("\nThread terminated with exit code %lu.\n",
4347 (unsigned long)thread
.Wait());
4350 void TestThreadSuspend()
4352 puts("\n*** Testing thread suspend/resume functions ***");
4354 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4358 // this is for this demo only, in a real life program we'd use another
4359 // condition variable which would be signaled from wxThread::Entry() to
4360 // tell us that the thread really started running - but here just wait a
4361 // bit and hope that it will be enough (the problem is, of course, that
4362 // the thread might still not run when we call Pause() which will result
4364 wxThread::Sleep(300);
4366 for ( size_t n
= 0; n
< 3; n
++ )
4370 puts("\nThread suspended");
4373 // don't sleep but resume immediately the first time
4374 wxThread::Sleep(300);
4376 puts("Going to resume the thread");
4381 puts("Waiting until it terminates now");
4383 // wait until the thread terminates
4389 void TestThreadDelete()
4391 // As above, using Sleep() is only for testing here - we must use some
4392 // synchronisation object instead to ensure that the thread is still
4393 // running when we delete it - deleting a detached thread which already
4394 // terminated will lead to a crash!
4396 puts("\n*** Testing thread delete function ***");
4398 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4402 puts("\nDeleted a thread which didn't start to run yet.");
4404 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4408 wxThread::Sleep(300);
4412 puts("\nDeleted a running thread.");
4414 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4418 wxThread::Sleep(300);
4424 puts("\nDeleted a sleeping thread.");
4426 MyJoinableThread
thread3(20);
4431 puts("\nDeleted a joinable thread.");
4433 MyJoinableThread
thread4(2);
4436 wxThread::Sleep(300);
4440 puts("\nDeleted a joinable thread which already terminated.");
4445 #endif // TEST_THREADS
4447 // ----------------------------------------------------------------------------
4449 // ----------------------------------------------------------------------------
4453 static void PrintArray(const char* name
, const wxArrayString
& array
)
4455 printf("Dump of the array '%s'\n", name
);
4457 size_t nCount
= array
.GetCount();
4458 for ( size_t n
= 0; n
< nCount
; n
++ )
4460 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4464 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4466 printf("Dump of the array '%s'\n", name
);
4468 size_t nCount
= array
.GetCount();
4469 for ( size_t n
= 0; n
< nCount
; n
++ )
4471 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4475 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4476 const wxString
& second
)
4478 return first
.length() - second
.length();
4481 int wxCMPFUNC_CONV
IntCompare(int *first
,
4484 return *first
- *second
;
4487 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4490 return *second
- *first
;
4493 static void TestArrayOfInts()
4495 puts("*** Testing wxArrayInt ***\n");
4506 puts("After sort:");
4510 puts("After reverse sort:");
4511 a
.Sort(IntRevCompare
);
4515 #include "wx/dynarray.h"
4517 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4518 #include "wx/arrimpl.cpp"
4519 WX_DEFINE_OBJARRAY(ArrayBars
);
4521 static void TestArrayOfObjects()
4523 puts("*** Testing wxObjArray ***\n");
4527 Bar
bar("second bar");
4529 printf("Initially: %u objects in the array, %u objects total.\n",
4530 bars
.GetCount(), Bar::GetNumber());
4532 bars
.Add(new Bar("first bar"));
4535 printf("Now: %u objects in the array, %u objects total.\n",
4536 bars
.GetCount(), Bar::GetNumber());
4540 printf("After Empty(): %u objects in the array, %u objects total.\n",
4541 bars
.GetCount(), Bar::GetNumber());
4544 printf("Finally: no more objects in the array, %u objects total.\n",
4548 #endif // TEST_ARRAYS
4550 // ----------------------------------------------------------------------------
4552 // ----------------------------------------------------------------------------
4556 #include "wx/timer.h"
4557 #include "wx/tokenzr.h"
4559 static void TestStringConstruction()
4561 puts("*** Testing wxString constructores ***");
4563 #define TEST_CTOR(args, res) \
4566 printf("wxString%s = %s ", #args, s.c_str()); \
4573 printf("(ERROR: should be %s)\n", res); \
4577 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4578 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4579 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4580 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4582 static const wxChar
*s
= _T("?really!");
4583 const wxChar
*start
= wxStrchr(s
, _T('r'));
4584 const wxChar
*end
= wxStrchr(s
, _T('!'));
4585 TEST_CTOR((start
, end
), _T("really"));
4590 static void TestString()
4600 for (int i
= 0; i
< 1000000; ++i
)
4604 c
= "! How'ya doin'?";
4607 c
= "Hello world! What's up?";
4612 printf ("TestString elapsed time: %ld\n", sw
.Time());
4615 static void TestPChar()
4623 for (int i
= 0; i
< 1000000; ++i
)
4625 strcpy (a
, "Hello");
4626 strcpy (b
, " world");
4627 strcpy (c
, "! How'ya doin'?");
4630 strcpy (c
, "Hello world! What's up?");
4631 if (strcmp (c
, a
) == 0)
4635 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4638 static void TestStringSub()
4640 wxString
s("Hello, world!");
4642 puts("*** Testing wxString substring extraction ***");
4644 printf("String = '%s'\n", s
.c_str());
4645 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4646 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4647 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4648 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4649 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4650 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4652 static const wxChar
*prefixes
[] =
4656 _T("Hello, world!"),
4657 _T("Hello, world!!!"),
4663 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4665 wxString prefix
= prefixes
[n
], rest
;
4666 bool rc
= s
.StartsWith(prefix
, &rest
);
4667 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4670 printf(" (the rest is '%s')\n", rest
.c_str());
4681 static void TestStringFormat()
4683 puts("*** Testing wxString formatting ***");
4686 s
.Printf("%03d", 18);
4688 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4689 printf("Number 18: %s\n", s
.c_str());
4694 // returns "not found" for npos, value for all others
4695 static wxString
PosToString(size_t res
)
4697 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4698 : wxString::Format(_T("%u"), res
);
4702 static void TestStringFind()
4704 puts("*** Testing wxString find() functions ***");
4706 static const wxChar
*strToFind
= _T("ell");
4707 static const struct StringFindTest
4711 result
; // of searching "ell" in str
4714 { _T("Well, hello world"), 0, 1 },
4715 { _T("Well, hello world"), 6, 7 },
4716 { _T("Well, hello world"), 9, wxString::npos
},
4719 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4721 const StringFindTest
& ft
= findTestData
[n
];
4722 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4724 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4725 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4727 size_t resTrue
= ft
.result
;
4728 if ( res
== resTrue
)
4734 printf(_T("(ERROR: should be %s)\n"),
4735 PosToString(resTrue
).c_str());
4742 static void TestStringTokenizer()
4744 puts("*** Testing wxStringTokenizer ***");
4746 static const wxChar
*modeNames
[] =
4750 _T("return all empty"),
4755 static const struct StringTokenizerTest
4757 const wxChar
*str
; // string to tokenize
4758 const wxChar
*delims
; // delimiters to use
4759 size_t count
; // count of token
4760 wxStringTokenizerMode mode
; // how should we tokenize it
4761 } tokenizerTestData
[] =
4763 { _T(""), _T(" "), 0 },
4764 { _T("Hello, world"), _T(" "), 2 },
4765 { _T("Hello, world "), _T(" "), 2 },
4766 { _T("Hello, world"), _T(","), 2 },
4767 { _T("Hello, world!"), _T(",!"), 2 },
4768 { _T("Hello,, world!"), _T(",!"), 3 },
4769 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4770 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4771 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4772 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4773 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4774 { _T("01/02/99"), _T("/-"), 3 },
4775 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4778 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4780 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4781 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4783 size_t count
= tkz
.CountTokens();
4784 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4785 MakePrintable(tt
.str
).c_str(),
4787 MakePrintable(tt
.delims
).c_str(),
4788 modeNames
[tkz
.GetMode()]);
4789 if ( count
== tt
.count
)
4795 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4800 // if we emulate strtok(), check that we do it correctly
4801 wxChar
*buf
, *s
= NULL
, *last
;
4803 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4805 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4806 wxStrcpy(buf
, tt
.str
);
4808 s
= wxStrtok(buf
, tt
.delims
, &last
);
4815 // now show the tokens themselves
4817 while ( tkz
.HasMoreTokens() )
4819 wxString token
= tkz
.GetNextToken();
4821 printf(_T("\ttoken %u: '%s'"),
4823 MakePrintable(token
).c_str());
4833 printf(" (ERROR: should be %s)\n", s
);
4836 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4840 // nothing to compare with
4845 if ( count2
!= count
)
4847 puts(_T("\tERROR: token count mismatch"));
4856 static void TestStringReplace()
4858 puts("*** Testing wxString::replace ***");
4860 static const struct StringReplaceTestData
4862 const wxChar
*original
; // original test string
4863 size_t start
, len
; // the part to replace
4864 const wxChar
*replacement
; // the replacement string
4865 const wxChar
*result
; // and the expected result
4866 } stringReplaceTestData
[] =
4868 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4869 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4870 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4871 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4872 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4875 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4877 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4879 wxString original
= data
.original
;
4880 original
.replace(data
.start
, data
.len
, data
.replacement
);
4882 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4883 data
.original
, data
.start
, data
.len
, data
.replacement
,
4886 if ( original
== data
.result
)
4892 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4899 static void TestStringMatch()
4901 wxPuts(_T("*** Testing wxString::Matches() ***"));
4903 static const struct StringMatchTestData
4906 const wxChar
*wildcard
;
4908 } stringMatchTestData
[] =
4910 { _T("foobar"), _T("foo*"), 1 },
4911 { _T("foobar"), _T("*oo*"), 1 },
4912 { _T("foobar"), _T("*bar"), 1 },
4913 { _T("foobar"), _T("??????"), 1 },
4914 { _T("foobar"), _T("f??b*"), 1 },
4915 { _T("foobar"), _T("f?b*"), 0 },
4916 { _T("foobar"), _T("*goo*"), 0 },
4917 { _T("foobar"), _T("*foo"), 0 },
4918 { _T("foobarfoo"), _T("*foo"), 1 },
4919 { _T(""), _T("*"), 1 },
4920 { _T(""), _T("?"), 0 },
4923 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4925 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4926 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4927 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4929 matches
? _T("matches") : _T("doesn't match"),
4931 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4937 #endif // TEST_STRINGS
4939 // ----------------------------------------------------------------------------
4941 // ----------------------------------------------------------------------------
4943 int main(int argc
, char **argv
)
4945 wxInitializer initializer
;
4948 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4953 #ifdef TEST_SNGLINST
4954 wxSingleInstanceChecker checker
;
4955 if ( checker
.Create(_T(".wxconsole.lock")) )
4957 if ( checker
.IsAnotherRunning() )
4959 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4964 // wait some time to give time to launch another instance
4965 wxPrintf(_T("Press \"Enter\" to continue..."));
4968 else // failed to create
4970 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4972 #endif // TEST_SNGLINST
4976 #endif // TEST_CHARSET
4979 TestCmdLineConvert();
4981 #if wxUSE_CMDLINE_PARSER
4982 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4984 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
4985 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4986 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4987 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4989 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4990 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4991 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
4992 wxCMD_LINE_VAL_NUMBER
},
4993 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
4994 wxCMD_LINE_VAL_DATE
},
4996 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4997 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5002 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5004 parser
.AddOption("project_name", "", "full path to project file",
5005 wxCMD_LINE_VAL_STRING
,
5006 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5008 switch ( parser
.Parse() )
5011 wxLogMessage("Help was given, terminating.");
5015 ShowCmdLine(parser
);
5019 wxLogMessage("Syntax error detected, aborting.");
5022 #endif // wxUSE_CMDLINE_PARSER
5024 #endif // TEST_CMDLINE
5032 TestStringConstruction();
5035 TestStringTokenizer();
5036 TestStringReplace();
5039 #endif // TEST_STRINGS
5052 puts("*** Initially:");
5054 PrintArray("a1", a1
);
5056 wxArrayString
a2(a1
);
5057 PrintArray("a2", a2
);
5059 wxSortedArrayString
a3(a1
);
5060 PrintArray("a3", a3
);
5062 puts("*** After deleting a string from a1");
5065 PrintArray("a1", a1
);
5066 PrintArray("a2", a2
);
5067 PrintArray("a3", a3
);
5069 puts("*** After reassigning a1 to a2 and a3");
5071 PrintArray("a2", a2
);
5072 PrintArray("a3", a3
);
5074 puts("*** After sorting a1");
5076 PrintArray("a1", a1
);
5078 puts("*** After sorting a1 in reverse order");
5080 PrintArray("a1", a1
);
5082 puts("*** After sorting a1 by the string length");
5083 a1
.Sort(StringLenCompare
);
5084 PrintArray("a1", a1
);
5086 TestArrayOfObjects();
5089 #endif // TEST_ARRAYS
5097 #ifdef TEST_DLLLOADER
5099 #endif // TEST_DLLLOADER
5103 #endif // TEST_ENVIRON
5107 #endif // TEST_EXECUTE
5109 #ifdef TEST_FILECONF
5111 #endif // TEST_FILECONF
5119 #endif // TEST_LOCALE
5123 for ( size_t n
= 0; n
< 8000; n
++ )
5125 s
<< (char)('A' + (n
% 26));
5129 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5131 // this one shouldn't be truncated
5134 // but this one will because log functions use fixed size buffer
5135 // (note that it doesn't need '\n' at the end neither - will be added
5137 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5149 #ifdef TEST_FILENAME
5150 TestFileNameSplit();
5153 TestFileNameConstruction();
5155 TestFileNameComparison();
5156 TestFileNameOperations();
5158 #endif // TEST_FILENAME
5160 #ifdef TEST_FILETIME
5163 #endif // TEST_FILETIME
5166 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5167 if ( TestFtpConnect() )
5178 TestFtpInteractive();
5180 //else: connecting to the FTP server failed
5187 int nCPUs
= wxThread::GetCPUCount();
5188 printf("This system has %d CPUs\n", nCPUs
);
5190 wxThread::SetConcurrency(nCPUs
);
5192 if ( argc
> 1 && argv
[1][0] == 't' )
5193 wxLog::AddTraceMask("thread");
5196 TestDetachedThreads();
5198 TestJoinableThreads();
5200 TestThreadSuspend();
5204 #endif // TEST_THREADS
5206 #ifdef TEST_LONGLONG
5207 // seed pseudo random generator
5208 srand((unsigned)time(NULL
));
5216 TestMultiplication();
5219 TestLongLongConversion();
5220 TestBitOperations();
5221 TestLongLongComparison();
5223 TestLongLongPrint();
5224 #endif // TEST_LONGLONG
5231 wxLog::AddTraceMask(_T("mime"));
5239 TestMimeAssociate();
5242 #ifdef TEST_INFO_FUNCTIONS
5249 #endif // TEST_INFO_FUNCTIONS
5251 #ifdef TEST_PATHLIST
5253 #endif // TEST_PATHLIST
5257 #endif // TEST_REGCONF
5260 // TODO: write a real test using src/regex/tests file
5265 TestRegExSubmatch();
5266 TestRegExInteractive();
5268 TestRegExReplacement();
5269 #endif // TEST_REGEX
5271 #ifdef TEST_REGISTRY
5274 TestRegistryAssociation();
5275 #endif // TEST_REGISTRY
5283 #endif // TEST_SOCKETS
5289 #endif // TEST_STREAMS
5293 #endif // TEST_TIMER
5295 #ifdef TEST_DATETIME
5308 TestTimeArithmetics();
5315 TestTimeSpanFormat();
5317 TestDateTimeInteractive();
5318 #endif // TEST_DATETIME
5321 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5323 #endif // TEST_USLEEP
5329 #endif // TEST_VCARD
5333 #endif // TEST_WCHAR
5337 TestZipStreamRead();
5338 TestZipFileSystem();
5343 TestZlibStreamWrite();
5344 TestZlibStreamRead();