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 // ----------------------------------------------------------------------------
22 #include <wx/string.h>
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
36 // what to test (in alphabetic order)?
39 //#define TEST_CHARSET
40 //#define TEST_CMDLINE
41 //#define TEST_DATETIME
43 //#define TEST_DLLLOADER
44 //#define TEST_ENVIRON
45 //#define TEST_EXECUTE
47 //#define TEST_FILECONF
48 //#define TEST_FILENAME
51 //#define TEST_INFO_FUNCTIONS
55 //#define TEST_LONGLONG
57 //#define TEST_PATHLIST
58 //#define TEST_REGCONF
59 //#define TEST_REGISTRY
60 //#define TEST_SOCKETS
61 //#define TEST_STREAMS
62 //#define TEST_STRINGS
63 //#define TEST_THREADS
65 //#define TEST_VCARD -- don't enable this (VZ)
70 // ----------------------------------------------------------------------------
71 // test class for container objects
72 // ----------------------------------------------------------------------------
74 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
76 class Bar
// Foo is already taken in the hash test
79 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
82 static size_t GetNumber() { return ms_bars
; }
84 const char *GetName() const { return m_name
; }
89 static size_t ms_bars
;
92 size_t Bar::ms_bars
= 0;
94 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
96 // ============================================================================
98 // ============================================================================
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
106 // replace TABs with \t and CRs with \n
107 static wxString
MakePrintable(const wxChar
*s
)
110 (void)str
.Replace(_T("\t"), _T("\\t"));
111 (void)str
.Replace(_T("\n"), _T("\\n"));
112 (void)str
.Replace(_T("\r"), _T("\\r"));
117 #endif // MakePrintable() is used
119 // ----------------------------------------------------------------------------
120 // wxFontMapper::CharsetToEncoding
121 // ----------------------------------------------------------------------------
125 #include <wx/fontmap.h>
127 static void TestCharset()
129 static const wxChar
*charsets
[] =
131 // some vali charsets
140 // and now some bogus ones
147 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
149 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
150 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
152 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
153 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
157 #endif // TEST_CHARSET
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
165 #include <wx/cmdline.h>
166 #include <wx/datetime.h>
168 static void ShowCmdLine(const wxCmdLineParser
& parser
)
170 wxString s
= "Input files: ";
172 size_t count
= parser
.GetParamCount();
173 for ( size_t param
= 0; param
< count
; param
++ )
175 s
<< parser
.GetParam(param
) << ' ';
179 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
180 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
185 if ( parser
.Found("o", &strVal
) )
186 s
<< "Output file:\t" << strVal
<< '\n';
187 if ( parser
.Found("i", &strVal
) )
188 s
<< "Input dir:\t" << strVal
<< '\n';
189 if ( parser
.Found("s", &lVal
) )
190 s
<< "Size:\t" << lVal
<< '\n';
191 if ( parser
.Found("d", &dt
) )
192 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
193 if ( parser
.Found("project_name", &strVal
) )
194 s
<< "Project:\t" << strVal
<< '\n';
199 #endif // TEST_CMDLINE
201 // ----------------------------------------------------------------------------
203 // ----------------------------------------------------------------------------
210 static const wxChar
*ROOTDIR
= _T("/");
211 static const wxChar
*TESTDIR
= _T("/usr");
212 #elif defined(__WXMSW__)
213 static const wxChar
*ROOTDIR
= _T("c:\\");
214 static const wxChar
*TESTDIR
= _T("d:\\");
216 #error "don't know where the root directory is"
219 static void TestDirEnumHelper(wxDir
& dir
,
220 int flags
= wxDIR_DEFAULT
,
221 const wxString
& filespec
= wxEmptyString
)
225 if ( !dir
.IsOpened() )
228 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
231 printf("\t%s\n", filename
.c_str());
233 cont
= dir
.GetNext(&filename
);
239 static void TestDirEnum()
241 puts("*** Testing wxDir::GetFirst/GetNext ***");
243 wxDir
dir(wxGetCwd());
245 puts("Enumerating everything in current directory:");
246 TestDirEnumHelper(dir
);
248 puts("Enumerating really everything in current directory:");
249 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
251 puts("Enumerating object files in current directory:");
252 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
254 puts("Enumerating directories in current directory:");
255 TestDirEnumHelper(dir
, wxDIR_DIRS
);
257 puts("Enumerating files in current directory:");
258 TestDirEnumHelper(dir
, wxDIR_FILES
);
260 puts("Enumerating files including hidden in current directory:");
261 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
265 puts("Enumerating everything in root directory:");
266 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
268 puts("Enumerating directories in root directory:");
269 TestDirEnumHelper(dir
, wxDIR_DIRS
);
271 puts("Enumerating files in root directory:");
272 TestDirEnumHelper(dir
, wxDIR_FILES
);
274 puts("Enumerating files including hidden in root directory:");
275 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
277 puts("Enumerating files in non existing directory:");
278 wxDir
dirNo("nosuchdir");
279 TestDirEnumHelper(dirNo
);
282 class DirPrintTraverser
: public wxDirTraverser
285 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
287 return wxDIR_CONTINUE
;
290 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
292 wxString path
, name
, ext
;
293 wxSplitPath(dirname
, &path
, &name
, &ext
);
296 name
<< _T('.') << ext
;
299 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
301 if ( wxIsPathSeparator(*p
) )
305 printf("%s%s\n", indent
.c_str(), name
.c_str());
307 return wxDIR_CONTINUE
;
311 static void TestDirTraverse()
313 puts("*** Testing wxDir::Traverse() ***");
317 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
318 printf("There are %u files under '%s'\n", n
, TESTDIR
);
321 printf("First one is '%s'\n", files
[0u]);
322 printf(" last one is '%s'\n", files
[n
- 1]);
325 // enum again with custom traverser
327 DirPrintTraverser traverser
;
328 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
333 // ----------------------------------------------------------------------------
335 // ----------------------------------------------------------------------------
337 #ifdef TEST_DLLLOADER
339 #include <wx/dynlib.h>
341 static void TestDllLoad()
343 #if defined(__WXMSW__)
344 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
345 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
346 #elif defined(__UNIX__)
347 // weird: using just libc.so does *not* work!
348 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
349 static const wxChar
*FUNC_NAME
= _T("strlen");
351 #error "don't know how to test wxDllLoader on this platform"
354 puts("*** testing wxDllLoader ***\n");
356 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
359 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
363 typedef int (*strlenType
)(char *);
364 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
367 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
368 FUNC_NAME
, LIB_NAME
);
372 if ( pfnStrlen("foo") != 3 )
374 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
382 wxDllLoader::UnloadLibrary(dllHandle
);
386 #endif // TEST_DLLLOADER
388 // ----------------------------------------------------------------------------
390 // ----------------------------------------------------------------------------
394 #include <wx/utils.h>
396 static wxString
MyGetEnv(const wxString
& var
)
399 if ( !wxGetEnv(var
, &val
) )
402 val
= wxString(_T('\'')) + val
+ _T('\'');
407 static void TestEnvironment()
409 const wxChar
*var
= _T("wxTestVar");
411 puts("*** testing environment access functions ***");
413 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
414 wxSetEnv(var
, _T("value for wxTestVar"));
415 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
416 wxSetEnv(var
, _T("another value"));
417 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
419 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
420 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
423 #endif // TEST_ENVIRON
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
431 #include <wx/utils.h>
433 static void TestExecute()
435 puts("*** testing wxExecute ***");
438 #define COMMAND "cat -n ../../Makefile" // "echo hi"
439 #define SHELL_COMMAND "echo hi from shell"
440 #define REDIRECT_COMMAND COMMAND // "date"
441 #elif defined(__WXMSW__)
442 #define COMMAND "command.com -c 'echo hi'"
443 #define SHELL_COMMAND "echo hi"
444 #define REDIRECT_COMMAND COMMAND
446 #error "no command to exec"
449 printf("Testing wxShell: ");
451 if ( wxShell(SHELL_COMMAND
) )
456 printf("Testing wxExecute: ");
458 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
463 #if 0 // no, it doesn't work (yet?)
464 printf("Testing async wxExecute: ");
466 if ( wxExecute(COMMAND
) != 0 )
467 puts("Ok (command launched).");
472 printf("Testing wxExecute with redirection:\n");
473 wxArrayString output
;
474 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
480 size_t count
= output
.GetCount();
481 for ( size_t n
= 0; n
< count
; n
++ )
483 printf("\t%s\n", output
[n
].c_str());
490 #endif // TEST_EXECUTE
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
499 #include <wx/ffile.h>
500 #include <wx/textfile.h>
502 static void TestFileRead()
504 puts("*** wxFile read test ***");
506 wxFile
file(_T("testdata.fc"));
507 if ( file
.IsOpened() )
509 printf("File length: %lu\n", file
.Length());
511 puts("File dump:\n----------");
513 static const off_t len
= 1024;
517 off_t nRead
= file
.Read(buf
, len
);
518 if ( nRead
== wxInvalidOffset
)
520 printf("Failed to read the file.");
524 fwrite(buf
, nRead
, 1, stdout
);
534 printf("ERROR: can't open test file.\n");
540 static void TestTextFileRead()
542 puts("*** wxTextFile read test ***");
544 wxTextFile
file(_T("testdata.fc"));
547 printf("Number of lines: %u\n", file
.GetLineCount());
548 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
552 puts("\nDumping the entire file:");
553 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
555 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
557 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
559 puts("\nAnd now backwards:");
560 for ( s
= file
.GetLastLine();
561 file
.GetCurrentLine() != 0;
562 s
= file
.GetPrevLine() )
564 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
566 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
570 printf("ERROR: can't open '%s'\n", file
.GetName());
576 static void TestFileCopy()
578 puts("*** Testing wxCopyFile ***");
580 static const wxChar
*filename1
= _T("testdata.fc");
581 static const wxChar
*filename2
= _T("test2");
582 if ( !wxCopyFile(filename1
, filename2
) )
584 puts("ERROR: failed to copy file");
588 wxFFile
f1(filename1
, "rb"),
591 if ( !f1
.IsOpened() || !f2
.IsOpened() )
593 puts("ERROR: failed to open file(s)");
598 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
600 puts("ERROR: failed to read file(s)");
604 if ( (s1
.length() != s2
.length()) ||
605 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
607 puts("ERROR: copy error!");
611 puts("File was copied ok.");
617 if ( !wxRemoveFile(filename2
) )
619 puts("ERROR: failed to remove the file");
627 // ----------------------------------------------------------------------------
629 // ----------------------------------------------------------------------------
633 #include <wx/confbase.h>
634 #include <wx/fileconf.h>
636 static const struct FileConfTestData
638 const wxChar
*name
; // value name
639 const wxChar
*value
; // the value from the file
642 { _T("value1"), _T("one") },
643 { _T("value2"), _T("two") },
644 { _T("novalue"), _T("default") },
647 static void TestFileConfRead()
649 puts("*** testing wxFileConfig loading/reading ***");
651 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
652 _T("testdata.fc"), wxEmptyString
,
653 wxCONFIG_USE_RELATIVE_PATH
);
655 // test simple reading
656 puts("\nReading config file:");
657 wxString
defValue(_T("default")), value
;
658 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
660 const FileConfTestData
& data
= fcTestData
[n
];
661 value
= fileconf
.Read(data
.name
, defValue
);
662 printf("\t%s = %s ", data
.name
, value
.c_str());
663 if ( value
== data
.value
)
669 printf("(ERROR: should be %s)\n", data
.value
);
673 // test enumerating the entries
674 puts("\nEnumerating all root entries:");
677 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
680 printf("\t%s = %s\n",
682 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
684 cont
= fileconf
.GetNextEntry(name
, dummy
);
688 #endif // TEST_FILECONF
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
696 #include <wx/filename.h>
698 static struct FileNameInfo
700 const wxChar
*fullname
;
706 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
707 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
708 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
709 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
710 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
711 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
712 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
713 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
716 static void TestFileNameConstruction()
718 puts("*** testing wxFileName construction ***");
720 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
722 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
724 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
725 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
727 puts("ERROR (couldn't be normalized)");
731 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
738 static void TestFileNameSplit()
740 puts("*** testing wxFileName splitting ***");
742 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
744 const FileNameInfo
&fni
= filenames
[n
];
745 wxString path
, name
, ext
;
746 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
748 printf("%s -> path = '%s', name = '%s', ext = '%s'",
749 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
750 if ( path
!= fni
.path
)
751 printf(" (ERROR: path = '%s')", fni
.path
);
752 if ( name
!= fni
.name
)
753 printf(" (ERROR: name = '%s')", fni
.name
);
754 if ( ext
!= fni
.ext
)
755 printf(" (ERROR: ext = '%s')", fni
.ext
);
762 static void TestFileNameComparison()
767 static void TestFileNameOperations()
772 static void TestFileNameCwd()
777 #endif // TEST_FILENAME
779 // ----------------------------------------------------------------------------
781 // ----------------------------------------------------------------------------
789 Foo(int n_
) { n
= n_
; count
++; }
797 size_t Foo::count
= 0;
799 WX_DECLARE_LIST(Foo
, wxListFoos
);
800 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
802 #include <wx/listimpl.cpp>
804 WX_DEFINE_LIST(wxListFoos
);
806 static void TestHash()
808 puts("*** Testing wxHashTable ***\n");
812 hash
.DeleteContents(TRUE
);
814 printf("Hash created: %u foos in hash, %u foos totally\n",
815 hash
.GetCount(), Foo::count
);
817 static const int hashTestData
[] =
819 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
823 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
825 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
828 printf("Hash filled: %u foos in hash, %u foos totally\n",
829 hash
.GetCount(), Foo::count
);
831 puts("Hash access test:");
832 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
834 printf("\tGetting element with key %d, value %d: ",
836 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
839 printf("ERROR, not found.\n");
843 printf("%d (%s)\n", foo
->n
,
844 (size_t)foo
->n
== n
? "ok" : "ERROR");
848 printf("\nTrying to get an element not in hash: ");
850 if ( hash
.Get(1234) || hash
.Get(1, 0) )
852 puts("ERROR: found!");
856 puts("ok (not found)");
860 printf("Hash destroyed: %u foos left\n", Foo::count
);
865 // ----------------------------------------------------------------------------
867 // ----------------------------------------------------------------------------
873 WX_DECLARE_LIST(Bar
, wxListBars
);
874 #include <wx/listimpl.cpp>
875 WX_DEFINE_LIST(wxListBars
);
877 static void TestListCtor()
879 puts("*** Testing wxList construction ***\n");
883 list1
.Append(new Bar(_T("first")));
884 list1
.Append(new Bar(_T("second")));
886 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
887 list1
.GetCount(), Bar::GetNumber());
892 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
893 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
895 list1
.DeleteContents(TRUE
);
898 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
903 // ----------------------------------------------------------------------------
905 // ----------------------------------------------------------------------------
910 #include "wx/utils.h" // for wxSetEnv
912 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
914 // find the name of the language from its value
915 static const char *GetLangName(int lang
)
917 static const char *languageNames
[] =
938 "ARABIC_SAUDI_ARABIA",
963 "CHINESE_SIMPLIFIED",
964 "CHINESE_TRADITIONAL",
986 "ENGLISH_NEW_ZEALAND",
987 "ENGLISH_PHILIPPINES",
988 "ENGLISH_SOUTH_AFRICA",
1000 "FRENCH_LUXEMBOURG",
1009 "GERMAN_LIECHTENSTEIN",
1010 "GERMAN_LUXEMBOURG",
1051 "MALAY_BRUNEI_DARUSSALAM",
1063 "NORWEGIAN_NYNORSK",
1070 "PORTUGUESE_BRAZILIAN",
1095 "SPANISH_ARGENTINA",
1099 "SPANISH_COSTA_RICA",
1100 "SPANISH_DOMINICAN_REPUBLIC",
1102 "SPANISH_EL_SALVADOR",
1103 "SPANISH_GUATEMALA",
1107 "SPANISH_NICARAGUA",
1111 "SPANISH_PUERTO_RICO",
1114 "SPANISH_VENEZUELA",
1151 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1152 return languageNames
[lang
];
1157 static void TestDefaultLang()
1159 puts("*** Testing wxLocale::GetSystemLanguage ***");
1161 static const wxChar
*langStrings
[] =
1163 NULL
, // system default
1170 _T("de_DE.iso88591"),
1172 _T("?"), // invalid lang spec
1173 _T("klingonese"), // I bet on some systems it does exist...
1176 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1177 wxLocale::GetSystemEncodingName().c_str(),
1178 wxLocale::GetSystemEncoding());
1180 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1182 const char *langStr
= langStrings
[n
];
1185 // FIXME: this doesn't do anything at all under Windows, we need
1186 // to create a new wxLocale!
1187 wxSetEnv(_T("LC_ALL"), langStr
);
1190 int lang
= gs_localeDefault
.GetSystemLanguage();
1191 printf("Locale for '%s' is %s.\n",
1192 langStr
? langStr
: "system default", GetLangName(lang
));
1196 #endif // TEST_LOCALE
1198 // ----------------------------------------------------------------------------
1200 // ----------------------------------------------------------------------------
1204 #include <wx/mimetype.h>
1206 static void TestMimeEnum()
1208 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1210 wxArrayString mimetypes
;
1212 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1214 printf("*** All %u known filetypes: ***\n", count
);
1219 for ( size_t n
= 0; n
< count
; n
++ )
1221 wxFileType
*filetype
=
1222 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1225 printf("nothing known about the filetype '%s'!\n",
1226 mimetypes
[n
].c_str());
1230 filetype
->GetDescription(&desc
);
1231 filetype
->GetExtensions(exts
);
1233 filetype
->GetIcon(NULL
);
1236 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1239 extsAll
<< _T(", ");
1243 printf("\t%s: %s (%s)\n",
1244 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1250 static void TestMimeOverride()
1252 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1254 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1255 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1257 if ( wxFile::Exists(mailcap
) )
1258 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1260 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1262 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1265 if ( wxFile::Exists(mimetypes
) )
1266 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1268 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1270 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1276 static void TestMimeFilename()
1278 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1280 static const wxChar
*filenames
[] =
1287 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1289 const wxString fname
= filenames
[n
];
1290 wxString ext
= fname
.AfterLast(_T('.'));
1291 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1294 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1299 if ( !ft
->GetDescription(&desc
) )
1300 desc
= _T("<no description>");
1303 if ( !ft
->GetOpenCommand(&cmd
,
1304 wxFileType::MessageParameters(fname
, _T(""))) )
1305 cmd
= _T("<no command available>");
1307 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1308 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1317 static void TestMimeAssociate()
1319 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1321 wxFileTypeInfo
ftInfo(
1322 _T("application/x-xyz"),
1323 _T("xyzview '%s'"), // open cmd
1324 _T(""), // print cmd
1325 _T("XYZ File") // description
1326 _T(".xyz"), // extensions
1327 NULL
// end of extensions
1329 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1331 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1334 wxPuts(_T("ERROR: failed to create association!"));
1338 // TODO: read it back
1347 // ----------------------------------------------------------------------------
1348 // misc information functions
1349 // ----------------------------------------------------------------------------
1351 #ifdef TEST_INFO_FUNCTIONS
1353 #include <wx/utils.h>
1355 static void TestOsInfo()
1357 puts("*** Testing OS info functions ***\n");
1360 wxGetOsVersion(&major
, &minor
);
1361 printf("Running under: %s, version %d.%d\n",
1362 wxGetOsDescription().c_str(), major
, minor
);
1364 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1366 printf("Host name is %s (%s).\n",
1367 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1372 static void TestUserInfo()
1374 puts("*** Testing user info functions ***\n");
1376 printf("User id is:\t%s\n", wxGetUserId().c_str());
1377 printf("User name is:\t%s\n", wxGetUserName().c_str());
1378 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1379 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1384 #endif // TEST_INFO_FUNCTIONS
1386 // ----------------------------------------------------------------------------
1388 // ----------------------------------------------------------------------------
1390 #ifdef TEST_LONGLONG
1392 #include <wx/longlong.h>
1393 #include <wx/timer.h>
1395 // make a 64 bit number from 4 16 bit ones
1396 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1398 // get a random 64 bit number
1399 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1401 #if wxUSE_LONGLONG_WX
1402 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1403 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1404 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1405 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1406 #endif // wxUSE_LONGLONG_WX
1408 static void TestSpeed()
1410 static const long max
= 100000000;
1417 for ( n
= 0; n
< max
; n
++ )
1422 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1425 #if wxUSE_LONGLONG_NATIVE
1430 for ( n
= 0; n
< max
; n
++ )
1435 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1437 #endif // wxUSE_LONGLONG_NATIVE
1443 for ( n
= 0; n
< max
; n
++ )
1448 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1452 static void TestLongLongConversion()
1454 puts("*** Testing wxLongLong conversions ***\n");
1458 for ( size_t n
= 0; n
< 100000; n
++ )
1462 #if wxUSE_LONGLONG_NATIVE
1463 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1465 wxASSERT_MSG( a
== b
, "conversions failure" );
1467 puts("Can't do it without native long long type, test skipped.");
1470 #endif // wxUSE_LONGLONG_NATIVE
1472 if ( !(nTested
% 1000) )
1484 static void TestMultiplication()
1486 puts("*** Testing wxLongLong multiplication ***\n");
1490 for ( size_t n
= 0; n
< 100000; n
++ )
1495 #if wxUSE_LONGLONG_NATIVE
1496 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1497 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1499 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1500 #else // !wxUSE_LONGLONG_NATIVE
1501 puts("Can't do it without native long long type, test skipped.");
1504 #endif // wxUSE_LONGLONG_NATIVE
1506 if ( !(nTested
% 1000) )
1518 static void TestDivision()
1520 puts("*** Testing wxLongLong division ***\n");
1524 for ( size_t n
= 0; n
< 100000; n
++ )
1526 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1527 // multiplication will not overflow)
1528 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1530 // get a random long (not wxLongLong for now) to divide it with
1535 #if wxUSE_LONGLONG_NATIVE
1536 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1538 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1539 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1540 #else // !wxUSE_LONGLONG_NATIVE
1541 // verify the result
1542 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1543 #endif // wxUSE_LONGLONG_NATIVE
1545 if ( !(nTested
% 1000) )
1557 static void TestAddition()
1559 puts("*** Testing wxLongLong addition ***\n");
1563 for ( size_t n
= 0; n
< 100000; n
++ )
1569 #if wxUSE_LONGLONG_NATIVE
1570 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1571 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1572 "addition failure" );
1573 #else // !wxUSE_LONGLONG_NATIVE
1574 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1575 #endif // wxUSE_LONGLONG_NATIVE
1577 if ( !(nTested
% 1000) )
1589 static void TestBitOperations()
1591 puts("*** Testing wxLongLong bit operation ***\n");
1595 for ( size_t n
= 0; n
< 100000; n
++ )
1599 #if wxUSE_LONGLONG_NATIVE
1600 for ( size_t n
= 0; n
< 33; n
++ )
1603 #else // !wxUSE_LONGLONG_NATIVE
1604 puts("Can't do it without native long long type, test skipped.");
1607 #endif // wxUSE_LONGLONG_NATIVE
1609 if ( !(nTested
% 1000) )
1621 static void TestLongLongComparison()
1623 puts("*** Testing wxLongLong comparison ***\n");
1625 static const long testLongs
[] =
1636 static const long ls
[2] =
1642 wxLongLongWx lls
[2];
1646 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1650 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1652 res
= lls
[m
] > testLongs
[n
];
1653 printf("0x%lx > 0x%lx is %s (%s)\n",
1654 ls
[m
], testLongs
[n
], res
? "true" : "false",
1655 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1657 res
= lls
[m
] < testLongs
[n
];
1658 printf("0x%lx < 0x%lx is %s (%s)\n",
1659 ls
[m
], testLongs
[n
], res
? "true" : "false",
1660 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1662 res
= lls
[m
] == testLongs
[n
];
1663 printf("0x%lx == 0x%lx is %s (%s)\n",
1664 ls
[m
], testLongs
[n
], res
? "true" : "false",
1665 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1673 #endif // TEST_LONGLONG
1675 // ----------------------------------------------------------------------------
1677 // ----------------------------------------------------------------------------
1679 #ifdef TEST_PATHLIST
1681 static void TestPathList()
1683 puts("*** Testing wxPathList ***\n");
1685 wxPathList pathlist
;
1686 pathlist
.AddEnvList("PATH");
1687 wxString path
= pathlist
.FindValidPath("ls");
1690 printf("ERROR: command not found in the path.\n");
1694 printf("Command found in the path as '%s'.\n", path
.c_str());
1698 #endif // TEST_PATHLIST
1700 // ----------------------------------------------------------------------------
1701 // registry and related stuff
1702 // ----------------------------------------------------------------------------
1704 // this is for MSW only
1707 #undef TEST_REGISTRY
1712 #include <wx/confbase.h>
1713 #include <wx/msw/regconf.h>
1715 static void TestRegConfWrite()
1717 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1718 regconf
.Write(_T("Hello"), wxString(_T("world")));
1721 #endif // TEST_REGCONF
1723 #ifdef TEST_REGISTRY
1725 #include <wx/msw/registry.h>
1727 // I chose this one because I liked its name, but it probably only exists under
1729 static const wxChar
*TESTKEY
=
1730 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1732 static void TestRegistryRead()
1734 puts("*** testing registry reading ***");
1736 wxRegKey
key(TESTKEY
);
1737 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1740 puts("ERROR: test key can't be opened, aborting test.");
1745 size_t nSubKeys
, nValues
;
1746 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1748 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1751 printf("Enumerating values:\n");
1755 bool cont
= key
.GetFirstValue(value
, dummy
);
1758 printf("Value '%s': type ", value
.c_str());
1759 switch ( key
.GetValueType(value
) )
1761 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1762 case wxRegKey::Type_String
: printf("SZ"); break;
1763 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1764 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1765 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1766 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1767 default: printf("other (unknown)"); break;
1770 printf(", value = ");
1771 if ( key
.IsNumericValue(value
) )
1774 key
.QueryValue(value
, &val
);
1780 key
.QueryValue(value
, val
);
1781 printf("'%s'", val
.c_str());
1783 key
.QueryRawValue(value
, val
);
1784 printf(" (raw value '%s')", val
.c_str());
1789 cont
= key
.GetNextValue(value
, dummy
);
1793 static void TestRegistryAssociation()
1796 The second call to deleteself genertaes an error message, with a
1797 messagebox saying .flo is crucial to system operation, while the .ddf
1798 call also fails, but with no error message
1803 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1805 key
= "ddxf_auto_file" ;
1806 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1808 key
= "ddxf_auto_file" ;
1809 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1812 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1814 key
= "program \"%1\"" ;
1816 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1818 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1820 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1822 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1826 #endif // TEST_REGISTRY
1828 // ----------------------------------------------------------------------------
1830 // ----------------------------------------------------------------------------
1834 #include <wx/socket.h>
1835 #include <wx/protocol/protocol.h>
1836 #include <wx/protocol/http.h>
1838 static void TestSocketServer()
1840 puts("*** Testing wxSocketServer ***\n");
1842 static const int PORT
= 3000;
1847 wxSocketServer
*server
= new wxSocketServer(addr
);
1848 if ( !server
->Ok() )
1850 puts("ERROR: failed to bind");
1857 printf("Server: waiting for connection on port %d...\n", PORT
);
1859 wxSocketBase
*socket
= server
->Accept();
1862 puts("ERROR: wxSocketServer::Accept() failed.");
1866 puts("Server: got a client.");
1868 server
->SetTimeout(60); // 1 min
1870 while ( socket
->IsConnected() )
1876 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1878 // don't log error if the client just close the connection
1879 if ( socket
->IsConnected() )
1881 puts("ERROR: in wxSocket::Read.");
1901 printf("Server: got '%s'.\n", s
.c_str());
1902 if ( s
== _T("bye") )
1909 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1910 socket
->Write("\r\n", 2);
1911 printf("Server: wrote '%s'.\n", s
.c_str());
1914 puts("Server: lost a client.");
1919 // same as "delete server" but is consistent with GUI programs
1923 static void TestSocketClient()
1925 puts("*** Testing wxSocketClient ***\n");
1927 static const char *hostname
= "www.wxwindows.org";
1930 addr
.Hostname(hostname
);
1933 printf("--- Attempting to connect to %s:80...\n", hostname
);
1935 wxSocketClient client
;
1936 if ( !client
.Connect(addr
) )
1938 printf("ERROR: failed to connect to %s\n", hostname
);
1942 printf("--- Connected to %s:%u...\n",
1943 addr
.Hostname().c_str(), addr
.Service());
1947 // could use simply "GET" here I suppose
1949 wxString::Format("GET http://%s/\r\n", hostname
);
1950 client
.Write(cmdGet
, cmdGet
.length());
1951 printf("--- Sent command '%s' to the server\n",
1952 MakePrintable(cmdGet
).c_str());
1953 client
.Read(buf
, WXSIZEOF(buf
));
1954 printf("--- Server replied:\n%s", buf
);
1958 #endif // TEST_SOCKETS
1960 // ----------------------------------------------------------------------------
1962 // ----------------------------------------------------------------------------
1966 #include <wx/protocol/ftp.h>
1970 #define FTP_ANONYMOUS
1972 #ifdef FTP_ANONYMOUS
1973 static const char *directory
= "/pub";
1974 static const char *filename
= "welcome.msg";
1976 static const char *directory
= "/etc";
1977 static const char *filename
= "issue";
1980 static bool TestFtpConnect()
1982 puts("*** Testing FTP connect ***");
1984 #ifdef FTP_ANONYMOUS
1985 static const char *hostname
= "ftp.wxwindows.org";
1987 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1988 #else // !FTP_ANONYMOUS
1989 static const char *hostname
= "localhost";
1992 fgets(user
, WXSIZEOF(user
), stdin
);
1993 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1997 printf("Password for %s: ", password
);
1998 fgets(password
, WXSIZEOF(password
), stdin
);
1999 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2000 ftp
.SetPassword(password
);
2002 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2003 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2005 if ( !ftp
.Connect(hostname
) )
2007 printf("ERROR: failed to connect to %s\n", hostname
);
2013 printf("--- Connected to %s, current directory is '%s'\n",
2014 hostname
, ftp
.Pwd().c_str());
2020 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2021 static void TestFtpWuFtpd()
2024 static const char *hostname
= "ftp.eudora.com";
2025 if ( !ftp
.Connect(hostname
) )
2027 printf("ERROR: failed to connect to %s\n", hostname
);
2031 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2032 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2035 printf("ERROR: couldn't get input stream for %s\n", filename
);
2039 size_t size
= in
->StreamSize();
2040 printf("Reading file %s (%u bytes)...", filename
, size
);
2042 char *data
= new char[size
];
2043 if ( !in
->Read(data
, size
) )
2045 puts("ERROR: read error");
2049 printf("Successfully retrieved the file.\n");
2058 static void TestFtpList()
2060 puts("*** Testing wxFTP file listing ***\n");
2063 if ( !ftp
.ChDir(directory
) )
2065 printf("ERROR: failed to cd to %s\n", directory
);
2068 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2070 // test NLIST and LIST
2071 wxArrayString files
;
2072 if ( !ftp
.GetFilesList(files
) )
2074 puts("ERROR: failed to get NLIST of files");
2078 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2079 size_t count
= files
.GetCount();
2080 for ( size_t n
= 0; n
< count
; n
++ )
2082 printf("\t%s\n", files
[n
].c_str());
2084 puts("End of the file list");
2087 if ( !ftp
.GetDirList(files
) )
2089 puts("ERROR: failed to get LIST of files");
2093 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2094 size_t count
= files
.GetCount();
2095 for ( size_t n
= 0; n
< count
; n
++ )
2097 printf("\t%s\n", files
[n
].c_str());
2099 puts("End of the file list");
2102 if ( !ftp
.ChDir(_T("..")) )
2104 puts("ERROR: failed to cd to ..");
2107 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2110 static void TestFtpDownload()
2112 puts("*** Testing wxFTP download ***\n");
2115 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2118 printf("ERROR: couldn't get input stream for %s\n", filename
);
2122 size_t size
= in
->StreamSize();
2123 printf("Reading file %s (%u bytes)...", filename
, size
);
2126 char *data
= new char[size
];
2127 if ( !in
->Read(data
, size
) )
2129 puts("ERROR: read error");
2133 printf("\nContents of %s:\n%s\n", filename
, data
);
2141 static void TestFtpFileSize()
2143 puts("*** Testing FTP SIZE command ***");
2145 if ( !ftp
.ChDir(directory
) )
2147 printf("ERROR: failed to cd to %s\n", directory
);
2150 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2152 if ( ftp
.FileExists(filename
) )
2154 int size
= ftp
.GetFileSize(filename
);
2156 printf("ERROR: couldn't get size of '%s'\n", filename
);
2158 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2162 printf("ERROR: '%s' doesn't exist\n", filename
);
2166 static void TestFtpMisc()
2168 puts("*** Testing miscellaneous wxFTP functions ***");
2170 if ( ftp
.SendCommand("STAT") != '2' )
2172 puts("ERROR: STAT failed");
2176 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2179 if ( ftp
.SendCommand("HELP SITE") != '2' )
2181 puts("ERROR: HELP SITE failed");
2185 printf("The list of site-specific commands:\n\n%s\n",
2186 ftp
.GetLastResult().c_str());
2190 static void TestFtpInteractive()
2192 puts("\n*** Interactive wxFTP test ***");
2198 printf("Enter FTP command: ");
2199 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2202 // kill the last '\n'
2203 buf
[strlen(buf
) - 1] = 0;
2205 // special handling of LIST and NLST as they require data connection
2206 wxString
start(buf
, 4);
2208 if ( start
== "LIST" || start
== "NLST" )
2211 if ( strlen(buf
) > 4 )
2214 wxArrayString files
;
2215 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2217 printf("ERROR: failed to get %s of files\n", start
.c_str());
2221 printf("--- %s of '%s' under '%s':\n",
2222 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2223 size_t count
= files
.GetCount();
2224 for ( size_t n
= 0; n
< count
; n
++ )
2226 printf("\t%s\n", files
[n
].c_str());
2228 puts("--- End of the file list");
2233 char ch
= ftp
.SendCommand(buf
);
2234 printf("Command %s", ch
? "succeeded" : "failed");
2237 printf(" (return code %c)", ch
);
2240 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2244 puts("\n*** done ***");
2247 static void TestFtpUpload()
2249 puts("*** Testing wxFTP uploading ***\n");
2252 static const char *file1
= "test1";
2253 static const char *file2
= "test2";
2254 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2257 printf("--- Uploading to %s ---\n", file1
);
2258 out
->Write("First hello", 11);
2262 // send a command to check the remote file
2263 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2265 printf("ERROR: STAT %s failed\n", file1
);
2269 printf("STAT %s returned:\n\n%s\n",
2270 file1
, ftp
.GetLastResult().c_str());
2273 out
= ftp
.GetOutputStream(file2
);
2276 printf("--- Uploading to %s ---\n", file1
);
2277 out
->Write("Second hello", 12);
2284 // ----------------------------------------------------------------------------
2286 // ----------------------------------------------------------------------------
2290 #include <wx/wfstream.h>
2291 #include <wx/mstream.h>
2293 static void TestFileStream()
2295 puts("*** Testing wxFileInputStream ***");
2297 static const wxChar
*filename
= _T("testdata.fs");
2299 wxFileOutputStream
fsOut(filename
);
2300 fsOut
.Write("foo", 3);
2303 wxFileInputStream
fsIn(filename
);
2304 printf("File stream size: %u\n", fsIn
.GetSize());
2305 while ( !fsIn
.Eof() )
2307 putchar(fsIn
.GetC());
2310 if ( !wxRemoveFile(filename
) )
2312 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2315 puts("\n*** wxFileInputStream test done ***");
2318 static void TestMemoryStream()
2320 puts("*** Testing wxMemoryInputStream ***");
2323 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2325 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2326 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2327 while ( !memInpStream
.Eof() )
2329 putchar(memInpStream
.GetC());
2332 puts("\n*** wxMemoryInputStream test done ***");
2335 #endif // TEST_STREAMS
2337 // ----------------------------------------------------------------------------
2339 // ----------------------------------------------------------------------------
2343 #include <wx/timer.h>
2344 #include <wx/utils.h>
2346 static void TestStopWatch()
2348 puts("*** Testing wxStopWatch ***\n");
2351 printf("Sleeping 3 seconds...");
2353 printf("\telapsed time: %ldms\n", sw
.Time());
2356 printf("Sleeping 2 more seconds...");
2358 printf("\telapsed time: %ldms\n", sw
.Time());
2361 printf("And 3 more seconds...");
2363 printf("\telapsed time: %ldms\n", sw
.Time());
2366 puts("\nChecking for 'backwards clock' bug...");
2367 for ( size_t n
= 0; n
< 70; n
++ )
2371 for ( size_t m
= 0; m
< 100000; m
++ )
2373 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2375 puts("\ntime is negative - ERROR!");
2385 #endif // TEST_TIMER
2387 // ----------------------------------------------------------------------------
2389 // ----------------------------------------------------------------------------
2393 #include <wx/vcard.h>
2395 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2398 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2402 wxString(_T('\t'), level
).c_str(),
2403 vcObj
->GetName().c_str());
2406 switch ( vcObj
->GetType() )
2408 case wxVCardObject::String
:
2409 case wxVCardObject::UString
:
2412 vcObj
->GetValue(&val
);
2413 value
<< _T('"') << val
<< _T('"');
2417 case wxVCardObject::Int
:
2420 vcObj
->GetValue(&i
);
2421 value
.Printf(_T("%u"), i
);
2425 case wxVCardObject::Long
:
2428 vcObj
->GetValue(&l
);
2429 value
.Printf(_T("%lu"), l
);
2433 case wxVCardObject::None
:
2436 case wxVCardObject::Object
:
2437 value
= _T("<node>");
2441 value
= _T("<unknown value type>");
2445 printf(" = %s", value
.c_str());
2448 DumpVObject(level
+ 1, *vcObj
);
2451 vcObj
= vcard
.GetNextProp(&cookie
);
2455 static void DumpVCardAddresses(const wxVCard
& vcard
)
2457 puts("\nShowing all addresses from vCard:\n");
2461 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2465 int flags
= addr
->GetFlags();
2466 if ( flags
& wxVCardAddress::Domestic
)
2468 flagsStr
<< _T("domestic ");
2470 if ( flags
& wxVCardAddress::Intl
)
2472 flagsStr
<< _T("international ");
2474 if ( flags
& wxVCardAddress::Postal
)
2476 flagsStr
<< _T("postal ");
2478 if ( flags
& wxVCardAddress::Parcel
)
2480 flagsStr
<< _T("parcel ");
2482 if ( flags
& wxVCardAddress::Home
)
2484 flagsStr
<< _T("home ");
2486 if ( flags
& wxVCardAddress::Work
)
2488 flagsStr
<< _T("work ");
2491 printf("Address %u:\n"
2493 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2496 addr
->GetPostOffice().c_str(),
2497 addr
->GetExtAddress().c_str(),
2498 addr
->GetStreet().c_str(),
2499 addr
->GetLocality().c_str(),
2500 addr
->GetRegion().c_str(),
2501 addr
->GetPostalCode().c_str(),
2502 addr
->GetCountry().c_str()
2506 addr
= vcard
.GetNextAddress(&cookie
);
2510 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2512 puts("\nShowing all phone numbers from vCard:\n");
2516 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2520 int flags
= phone
->GetFlags();
2521 if ( flags
& wxVCardPhoneNumber::Voice
)
2523 flagsStr
<< _T("voice ");
2525 if ( flags
& wxVCardPhoneNumber::Fax
)
2527 flagsStr
<< _T("fax ");
2529 if ( flags
& wxVCardPhoneNumber::Cellular
)
2531 flagsStr
<< _T("cellular ");
2533 if ( flags
& wxVCardPhoneNumber::Modem
)
2535 flagsStr
<< _T("modem ");
2537 if ( flags
& wxVCardPhoneNumber::Home
)
2539 flagsStr
<< _T("home ");
2541 if ( flags
& wxVCardPhoneNumber::Work
)
2543 flagsStr
<< _T("work ");
2546 printf("Phone number %u:\n"
2551 phone
->GetNumber().c_str()
2555 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2559 static void TestVCardRead()
2561 puts("*** Testing wxVCard reading ***\n");
2563 wxVCard
vcard(_T("vcard.vcf"));
2564 if ( !vcard
.IsOk() )
2566 puts("ERROR: couldn't load vCard.");
2570 // read individual vCard properties
2571 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2575 vcObj
->GetValue(&value
);
2580 value
= _T("<none>");
2583 printf("Full name retrieved directly: %s\n", value
.c_str());
2586 if ( !vcard
.GetFullName(&value
) )
2588 value
= _T("<none>");
2591 printf("Full name from wxVCard API: %s\n", value
.c_str());
2593 // now show how to deal with multiply occuring properties
2594 DumpVCardAddresses(vcard
);
2595 DumpVCardPhoneNumbers(vcard
);
2597 // and finally show all
2598 puts("\nNow dumping the entire vCard:\n"
2599 "-----------------------------\n");
2601 DumpVObject(0, vcard
);
2605 static void TestVCardWrite()
2607 puts("*** Testing wxVCard writing ***\n");
2610 if ( !vcard
.IsOk() )
2612 puts("ERROR: couldn't create vCard.");
2617 vcard
.SetName("Zeitlin", "Vadim");
2618 vcard
.SetFullName("Vadim Zeitlin");
2619 vcard
.SetOrganization("wxWindows", "R&D");
2621 // just dump the vCard back
2622 puts("Entire vCard follows:\n");
2623 puts(vcard
.Write());
2627 #endif // TEST_VCARD
2629 // ----------------------------------------------------------------------------
2630 // wide char (Unicode) support
2631 // ----------------------------------------------------------------------------
2635 #include <wx/strconv.h>
2636 #include <wx/fontenc.h>
2637 #include <wx/encconv.h>
2638 #include <wx/buffer.h>
2640 static void TestUtf8()
2642 puts("*** Testing UTF8 support ***\n");
2644 static const char textInUtf8
[] =
2646 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2647 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2648 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2649 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2650 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2651 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2652 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2657 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2659 puts("ERROR: UTF-8 decoding failed.");
2663 // using wxEncodingConverter
2665 wxEncodingConverter ec
;
2666 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2667 ec
.Convert(wbuf
, buf
);
2668 #else // using wxCSConv
2669 wxCSConv
conv(_T("koi8-r"));
2670 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2672 puts("ERROR: conversion to KOI8-R failed.");
2677 printf("The resulting string (in koi8-r): %s\n", buf
);
2681 #endif // TEST_WCHAR
2683 // ----------------------------------------------------------------------------
2685 // ----------------------------------------------------------------------------
2689 #include "wx/filesys.h"
2690 #include "wx/fs_zip.h"
2691 #include "wx/zipstrm.h"
2693 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2695 static void TestZipStreamRead()
2697 puts("*** Testing ZIP reading ***\n");
2699 static const wxChar
*filename
= _T("foo");
2700 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2701 printf("Archive size: %u\n", istr
.GetSize());
2703 printf("Dumping the file '%s':\n", filename
);
2704 while ( !istr
.Eof() )
2706 putchar(istr
.GetC());
2710 puts("\n----- done ------");
2713 static void DumpZipDirectory(wxFileSystem
& fs
,
2714 const wxString
& dir
,
2715 const wxString
& indent
)
2717 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2718 TESTFILE_ZIP
, dir
.c_str());
2719 wxString wildcard
= prefix
+ _T("/*");
2721 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2722 while ( !dirname
.empty() )
2724 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2726 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2731 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2733 DumpZipDirectory(fs
, dirname
,
2734 indent
+ wxString(_T(' '), 4));
2736 dirname
= fs
.FindNext();
2739 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2740 while ( !filename
.empty() )
2742 if ( !filename
.StartsWith(prefix
, &filename
) )
2744 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2749 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2751 filename
= fs
.FindNext();
2755 static void TestZipFileSystem()
2757 puts("*** Testing ZIP file system ***\n");
2759 wxFileSystem::AddHandler(new wxZipFSHandler
);
2761 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2763 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2768 // ----------------------------------------------------------------------------
2770 // ----------------------------------------------------------------------------
2774 #include <wx/zstream.h>
2775 #include <wx/wfstream.h>
2777 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2778 static const char *TEST_DATA
= "hello and hello again";
2780 static void TestZlibStreamWrite()
2782 puts("*** Testing Zlib stream reading ***\n");
2784 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2785 wxZlibOutputStream
ostr(fileOutStream
, 0);
2786 printf("Compressing the test string... ");
2787 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2790 puts("(ERROR: failed)");
2797 puts("\n----- done ------");
2800 static void TestZlibStreamRead()
2802 puts("*** Testing Zlib stream reading ***\n");
2804 wxFileInputStream
fileInStream(FILENAME_GZ
);
2805 wxZlibInputStream
istr(fileInStream
);
2806 printf("Archive size: %u\n", istr
.GetSize());
2808 puts("Dumping the file:");
2809 while ( !istr
.Eof() )
2811 putchar(istr
.GetC());
2815 puts("\n----- done ------");
2820 // ----------------------------------------------------------------------------
2822 // ----------------------------------------------------------------------------
2824 #ifdef TEST_DATETIME
2828 #include <wx/date.h>
2830 #include <wx/datetime.h>
2835 wxDateTime::wxDateTime_t day
;
2836 wxDateTime::Month month
;
2838 wxDateTime::wxDateTime_t hour
, min
, sec
;
2840 wxDateTime::WeekDay wday
;
2841 time_t gmticks
, ticks
;
2843 void Init(const wxDateTime::Tm
& tm
)
2852 gmticks
= ticks
= -1;
2855 wxDateTime
DT() const
2856 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2858 bool SameDay(const wxDateTime::Tm
& tm
) const
2860 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2863 wxString
Format() const
2866 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2868 wxDateTime::GetMonthName(month
).c_str(),
2870 abs(wxDateTime::ConvertYearToBC(year
)),
2871 year
> 0 ? "AD" : "BC");
2875 wxString
FormatDate() const
2878 s
.Printf("%02d-%s-%4d%s",
2880 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2881 abs(wxDateTime::ConvertYearToBC(year
)),
2882 year
> 0 ? "AD" : "BC");
2887 static const Date testDates
[] =
2889 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2890 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2891 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2892 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2893 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2894 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2895 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2896 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2897 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2898 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2899 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2900 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2901 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2902 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2903 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2906 // this test miscellaneous static wxDateTime functions
2907 static void TestTimeStatic()
2909 puts("\n*** wxDateTime static methods test ***");
2911 // some info about the current date
2912 int year
= wxDateTime::GetCurrentYear();
2913 printf("Current year %d is %sa leap one and has %d days.\n",
2915 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2916 wxDateTime::GetNumberOfDays(year
));
2918 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2919 printf("Current month is '%s' ('%s') and it has %d days\n",
2920 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2921 wxDateTime::GetMonthName(month
).c_str(),
2922 wxDateTime::GetNumberOfDays(month
));
2925 static const size_t nYears
= 5;
2926 static const size_t years
[2][nYears
] =
2928 // first line: the years to test
2929 { 1990, 1976, 2000, 2030, 1984, },
2931 // second line: TRUE if leap, FALSE otherwise
2932 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2935 for ( size_t n
= 0; n
< nYears
; n
++ )
2937 int year
= years
[0][n
];
2938 bool should
= years
[1][n
] != 0,
2939 is
= wxDateTime::IsLeapYear(year
);
2941 printf("Year %d is %sa leap year (%s)\n",
2944 should
== is
? "ok" : "ERROR");
2946 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2950 // test constructing wxDateTime objects
2951 static void TestTimeSet()
2953 puts("\n*** wxDateTime construction test ***");
2955 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2957 const Date
& d1
= testDates
[n
];
2958 wxDateTime dt
= d1
.DT();
2961 d2
.Init(dt
.GetTm());
2963 wxString s1
= d1
.Format(),
2966 printf("Date: %s == %s (%s)\n",
2967 s1
.c_str(), s2
.c_str(),
2968 s1
== s2
? "ok" : "ERROR");
2972 // test time zones stuff
2973 static void TestTimeZones()
2975 puts("\n*** wxDateTime timezone test ***");
2977 wxDateTime now
= wxDateTime::Now();
2979 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2980 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2981 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2982 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2983 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2984 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2986 wxDateTime::Tm tm
= now
.GetTm();
2987 if ( wxDateTime(tm
) != now
)
2989 printf("ERROR: got %s instead of %s\n",
2990 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2994 // test some minimal support for the dates outside the standard range
2995 static void TestTimeRange()
2997 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2999 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3001 printf("Unix epoch:\t%s\n",
3002 wxDateTime(2440587.5).Format(fmt
).c_str());
3003 printf("Feb 29, 0: \t%s\n",
3004 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3005 printf("JDN 0: \t%s\n",
3006 wxDateTime(0.0).Format(fmt
).c_str());
3007 printf("Jan 1, 1AD:\t%s\n",
3008 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3009 printf("May 29, 2099:\t%s\n",
3010 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3013 static void TestTimeTicks()
3015 puts("\n*** wxDateTime ticks test ***");
3017 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3019 const Date
& d
= testDates
[n
];
3020 if ( d
.ticks
== -1 )
3023 wxDateTime dt
= d
.DT();
3024 long ticks
= (dt
.GetValue() / 1000).ToLong();
3025 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3026 if ( ticks
== d
.ticks
)
3032 printf(" (ERROR: should be %ld, delta = %ld)\n",
3033 d
.ticks
, ticks
- d
.ticks
);
3036 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3037 ticks
= (dt
.GetValue() / 1000).ToLong();
3038 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3039 if ( ticks
== d
.gmticks
)
3045 printf(" (ERROR: should be %ld, delta = %ld)\n",
3046 d
.gmticks
, ticks
- d
.gmticks
);
3053 // test conversions to JDN &c
3054 static void TestTimeJDN()
3056 puts("\n*** wxDateTime to JDN test ***");
3058 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3060 const Date
& d
= testDates
[n
];
3061 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3062 double jdn
= dt
.GetJulianDayNumber();
3064 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3071 printf(" (ERROR: should be %f, delta = %f)\n",
3072 d
.jdn
, jdn
- d
.jdn
);
3077 // test week days computation
3078 static void TestTimeWDays()
3080 puts("\n*** wxDateTime weekday test ***");
3082 // test GetWeekDay()
3084 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3086 const Date
& d
= testDates
[n
];
3087 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3089 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3092 wxDateTime::GetWeekDayName(wday
).c_str());
3093 if ( wday
== d
.wday
)
3099 printf(" (ERROR: should be %s)\n",
3100 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3106 // test SetToWeekDay()
3107 struct WeekDateTestData
3109 Date date
; // the real date (precomputed)
3110 int nWeek
; // its week index in the month
3111 wxDateTime::WeekDay wday
; // the weekday
3112 wxDateTime::Month month
; // the month
3113 int year
; // and the year
3115 wxString
Format() const
3118 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3120 case 1: which
= "first"; break;
3121 case 2: which
= "second"; break;
3122 case 3: which
= "third"; break;
3123 case 4: which
= "fourth"; break;
3124 case 5: which
= "fifth"; break;
3126 case -1: which
= "last"; break;
3131 which
+= " from end";
3134 s
.Printf("The %s %s of %s in %d",
3136 wxDateTime::GetWeekDayName(wday
).c_str(),
3137 wxDateTime::GetMonthName(month
).c_str(),
3144 // the array data was generated by the following python program
3146 from DateTime import *
3147 from whrandom import *
3148 from string import *
3150 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3151 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3153 week = DateTimeDelta(7)
3156 year = randint(1900, 2100)
3157 month = randint(1, 12)
3158 day = randint(1, 28)
3159 dt = DateTime(year, month, day)
3160 wday = dt.day_of_week
3162 countFromEnd = choice([-1, 1])
3165 while dt.month is month:
3166 dt = dt - countFromEnd * week
3167 weekNum = weekNum + countFromEnd
3169 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3171 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3172 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3175 static const WeekDateTestData weekDatesTestData
[] =
3177 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3178 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3179 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3180 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3181 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3182 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3183 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3184 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3185 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3186 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3187 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3188 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3189 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3190 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3191 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3192 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3193 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3194 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3195 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3196 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3199 static const char *fmt
= "%d-%b-%Y";
3202 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3204 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3206 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3208 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3210 const Date
& d
= wd
.date
;
3211 if ( d
.SameDay(dt
.GetTm()) )
3217 dt
.Set(d
.day
, d
.month
, d
.year
);
3219 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3224 // test the computation of (ISO) week numbers
3225 static void TestTimeWNumber()
3227 puts("\n*** wxDateTime week number test ***");
3229 struct WeekNumberTestData
3231 Date date
; // the date
3232 wxDateTime::wxDateTime_t week
; // the week number in the year
3233 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3234 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3235 wxDateTime::wxDateTime_t dnum
; // day number in the year
3238 // data generated with the following python script:
3240 from DateTime import *
3241 from whrandom import *
3242 from string import *
3244 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3245 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3247 def GetMonthWeek(dt):
3248 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3249 if weekNumMonth < 0:
3250 weekNumMonth = weekNumMonth + 53
3253 def GetLastSundayBefore(dt):
3254 if dt.iso_week[2] == 7:
3257 return dt - DateTimeDelta(dt.iso_week[2])
3260 year = randint(1900, 2100)
3261 month = randint(1, 12)
3262 day = randint(1, 28)
3263 dt = DateTime(year, month, day)
3264 dayNum = dt.day_of_year
3265 weekNum = dt.iso_week[1]
3266 weekNumMonth = GetMonthWeek(dt)
3269 dtSunday = GetLastSundayBefore(dt)
3271 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3272 weekNumMonth2 = weekNumMonth2 + 1
3273 dtSunday = dtSunday - DateTimeDelta(7)
3275 data = { 'day': rjust(`day`, 2), \
3276 'month': monthNames[month - 1], \
3278 'weekNum': rjust(`weekNum`, 2), \
3279 'weekNumMonth': weekNumMonth, \
3280 'weekNumMonth2': weekNumMonth2, \
3281 'dayNum': rjust(`dayNum`, 3) }
3283 print " { { %(day)s, "\
3284 "wxDateTime::%(month)s, "\
3287 "%(weekNumMonth)s, "\
3288 "%(weekNumMonth2)s, "\
3289 "%(dayNum)s }," % data
3292 static const WeekNumberTestData weekNumberTestDates
[] =
3294 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3295 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3296 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3297 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3298 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3299 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3300 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3301 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3302 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3303 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3304 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3305 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3306 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3307 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3308 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3309 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3310 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3311 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3312 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3313 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3316 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3318 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3319 const Date
& d
= wn
.date
;
3321 wxDateTime dt
= d
.DT();
3323 wxDateTime::wxDateTime_t
3324 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3325 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3326 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3327 dnum
= dt
.GetDayOfYear();
3329 printf("%s: the day number is %d",
3330 d
.FormatDate().c_str(), dnum
);
3331 if ( dnum
== wn
.dnum
)
3337 printf(" (ERROR: should be %d)", wn
.dnum
);
3340 printf(", week in month is %d", wmon
);
3341 if ( wmon
== wn
.wmon
)
3347 printf(" (ERROR: should be %d)", wn
.wmon
);
3350 printf(" or %d", wmon2
);
3351 if ( wmon2
== wn
.wmon2
)
3357 printf(" (ERROR: should be %d)", wn
.wmon2
);
3360 printf(", week in year is %d", week
);
3361 if ( week
== wn
.week
)
3367 printf(" (ERROR: should be %d)\n", wn
.week
);
3372 // test DST calculations
3373 static void TestTimeDST()
3375 puts("\n*** wxDateTime DST test ***");
3377 printf("DST is%s in effect now.\n\n",
3378 wxDateTime::Now().IsDST() ? "" : " not");
3380 // taken from http://www.energy.ca.gov/daylightsaving.html
3381 static const Date datesDST
[2][2004 - 1900 + 1] =
3384 { 1, wxDateTime::Apr
, 1990 },
3385 { 7, wxDateTime::Apr
, 1991 },
3386 { 5, wxDateTime::Apr
, 1992 },
3387 { 4, wxDateTime::Apr
, 1993 },
3388 { 3, wxDateTime::Apr
, 1994 },
3389 { 2, wxDateTime::Apr
, 1995 },
3390 { 7, wxDateTime::Apr
, 1996 },
3391 { 6, wxDateTime::Apr
, 1997 },
3392 { 5, wxDateTime::Apr
, 1998 },
3393 { 4, wxDateTime::Apr
, 1999 },
3394 { 2, wxDateTime::Apr
, 2000 },
3395 { 1, wxDateTime::Apr
, 2001 },
3396 { 7, wxDateTime::Apr
, 2002 },
3397 { 6, wxDateTime::Apr
, 2003 },
3398 { 4, wxDateTime::Apr
, 2004 },
3401 { 28, wxDateTime::Oct
, 1990 },
3402 { 27, wxDateTime::Oct
, 1991 },
3403 { 25, wxDateTime::Oct
, 1992 },
3404 { 31, wxDateTime::Oct
, 1993 },
3405 { 30, wxDateTime::Oct
, 1994 },
3406 { 29, wxDateTime::Oct
, 1995 },
3407 { 27, wxDateTime::Oct
, 1996 },
3408 { 26, wxDateTime::Oct
, 1997 },
3409 { 25, wxDateTime::Oct
, 1998 },
3410 { 31, wxDateTime::Oct
, 1999 },
3411 { 29, wxDateTime::Oct
, 2000 },
3412 { 28, wxDateTime::Oct
, 2001 },
3413 { 27, wxDateTime::Oct
, 2002 },
3414 { 26, wxDateTime::Oct
, 2003 },
3415 { 31, wxDateTime::Oct
, 2004 },
3420 for ( year
= 1990; year
< 2005; year
++ )
3422 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3423 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3425 printf("DST period in the US for year %d: from %s to %s",
3426 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3428 size_t n
= year
- 1990;
3429 const Date
& dBegin
= datesDST
[0][n
];
3430 const Date
& dEnd
= datesDST
[1][n
];
3432 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3438 printf(" (ERROR: should be %s %d to %s %d)\n",
3439 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3440 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3446 for ( year
= 1990; year
< 2005; year
++ )
3448 printf("DST period in Europe for year %d: from %s to %s\n",
3450 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3451 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3455 // test wxDateTime -> text conversion
3456 static void TestTimeFormat()
3458 puts("\n*** wxDateTime formatting test ***");
3460 // some information may be lost during conversion, so store what kind
3461 // of info should we recover after a round trip
3464 CompareNone
, // don't try comparing
3465 CompareBoth
, // dates and times should be identical
3466 CompareDate
, // dates only
3467 CompareTime
// time only
3472 CompareKind compareKind
;
3474 } formatTestFormats
[] =
3476 { CompareBoth
, "---> %c" },
3477 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3478 { CompareBoth
, "Date is %x, time is %X" },
3479 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3480 { CompareNone
, "The day of year: %j, the week of year: %W" },
3481 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3484 static const Date formatTestDates
[] =
3486 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3487 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3489 // this test can't work for other centuries because it uses two digit
3490 // years in formats, so don't even try it
3491 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3492 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3493 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3497 // an extra test (as it doesn't depend on date, don't do it in the loop)
3498 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3500 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3504 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3505 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3507 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3508 printf("%s", s
.c_str());
3510 // what can we recover?
3511 int kind
= formatTestFormats
[n
].compareKind
;
3515 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3518 // converion failed - should it have?
3519 if ( kind
== CompareNone
)
3522 puts(" (ERROR: conversion back failed)");
3526 // should have parsed the entire string
3527 puts(" (ERROR: conversion back stopped too soon)");
3531 bool equal
= FALSE
; // suppress compilaer warning
3539 equal
= dt
.IsSameDate(dt2
);
3543 equal
= dt
.IsSameTime(dt2
);
3549 printf(" (ERROR: got back '%s' instead of '%s')\n",
3550 dt2
.Format().c_str(), dt
.Format().c_str());
3561 // test text -> wxDateTime conversion
3562 static void TestTimeParse()
3564 puts("\n*** wxDateTime parse test ***");
3566 struct ParseTestData
3573 static const ParseTestData parseTestDates
[] =
3575 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3576 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3579 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3581 const char *format
= parseTestDates
[n
].format
;
3583 printf("%s => ", format
);
3586 if ( dt
.ParseRfc822Date(format
) )
3588 printf("%s ", dt
.Format().c_str());
3590 if ( parseTestDates
[n
].good
)
3592 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3599 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3604 puts("(ERROR: bad format)");
3609 printf("bad format (%s)\n",
3610 parseTestDates
[n
].good
? "ERROR" : "ok");
3615 static void TestDateTimeInteractive()
3617 puts("\n*** interactive wxDateTime tests ***");
3623 printf("Enter a date: ");
3624 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3627 // kill the last '\n'
3628 buf
[strlen(buf
) - 1] = 0;
3631 const char *p
= dt
.ParseDate(buf
);
3634 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3640 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3643 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3644 dt
.Format("%b %d, %Y").c_str(),
3646 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3647 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3648 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3651 puts("\n*** done ***");
3654 static void TestTimeMS()
3656 puts("*** testing millisecond-resolution support in wxDateTime ***");
3658 wxDateTime dt1
= wxDateTime::Now(),
3659 dt2
= wxDateTime::UNow();
3661 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3662 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3663 printf("Dummy loop: ");
3664 for ( int i
= 0; i
< 6000; i
++ )
3666 //for ( int j = 0; j < 10; j++ )
3669 s
.Printf("%g", sqrt(i
));
3678 dt2
= wxDateTime::UNow();
3679 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3681 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3683 puts("\n*** done ***");
3686 static void TestTimeArithmetics()
3688 puts("\n*** testing arithmetic operations on wxDateTime ***");
3690 static const struct ArithmData
3692 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3693 : span(sp
), name(nam
) { }
3697 } testArithmData
[] =
3699 ArithmData(wxDateSpan::Day(), "day"),
3700 ArithmData(wxDateSpan::Week(), "week"),
3701 ArithmData(wxDateSpan::Month(), "month"),
3702 ArithmData(wxDateSpan::Year(), "year"),
3703 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3706 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3708 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3710 wxDateSpan span
= testArithmData
[n
].span
;
3714 const char *name
= testArithmData
[n
].name
;
3715 printf("%s + %s = %s, %s - %s = %s\n",
3716 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3717 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3719 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3720 if ( dt1
- span
== dt
)
3726 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3729 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3730 if ( dt2
+ span
== dt
)
3736 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3739 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3740 if ( dt2
+ 2*span
== dt1
)
3746 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3753 static void TestTimeHolidays()
3755 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3757 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3758 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3759 dtEnd
= dtStart
.GetLastMonthDay();
3761 wxDateTimeArray hol
;
3762 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3764 const wxChar
*format
= "%d-%b-%Y (%a)";
3766 printf("All holidays between %s and %s:\n",
3767 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3769 size_t count
= hol
.GetCount();
3770 for ( size_t n
= 0; n
< count
; n
++ )
3772 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3778 static void TestTimeZoneBug()
3780 puts("\n*** testing for DST/timezone bug ***\n");
3782 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3783 for ( int i
= 0; i
< 31; i
++ )
3785 printf("Date %s: week day %s.\n",
3786 date
.Format(_T("%d-%m-%Y")).c_str(),
3787 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3789 date
+= wxDateSpan::Day();
3795 static void TestTimeSpanFormat()
3797 puts("\n*** wxTimeSpan tests ***");
3799 static const char *formats
[] =
3801 _T("(default) %H:%M:%S"),
3802 _T("%E weeks and %D days"),
3803 _T("%l milliseconds"),
3804 _T("(with ms) %H:%M:%S:%l"),
3805 _T("100%% of minutes is %M"), // test "%%"
3806 _T("%D days and %H hours"),
3809 wxTimeSpan
ts1(1, 2, 3, 4),
3811 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3813 printf("ts1 = %s\tts2 = %s\n",
3814 ts1
.Format(formats
[n
]).c_str(),
3815 ts2
.Format(formats
[n
]).c_str());
3823 // test compatibility with the old wxDate/wxTime classes
3824 static void TestTimeCompatibility()
3826 puts("\n*** wxDateTime compatibility test ***");
3828 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3829 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3831 double jdnNow
= wxDateTime::Now().GetJDN();
3832 long jdnMidnight
= (long)(jdnNow
- 0.5);
3833 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3835 jdnMidnight
= wxDate().Set().GetJulianDate();
3836 printf("wxDateTime for today: %s\n",
3837 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3839 int flags
= wxEUROPEAN
;//wxFULL;
3842 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3843 for ( int n
= 0; n
< 7; n
++ )
3845 printf("Previous %s is %s\n",
3846 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3847 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3853 #endif // TEST_DATETIME
3855 // ----------------------------------------------------------------------------
3857 // ----------------------------------------------------------------------------
3861 #include <wx/thread.h>
3863 static size_t gs_counter
= (size_t)-1;
3864 static wxCriticalSection gs_critsect
;
3865 static wxCondition gs_cond
;
3867 class MyJoinableThread
: public wxThread
3870 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3871 { m_n
= n
; Create(); }
3873 // thread execution starts here
3874 virtual ExitCode
Entry();
3880 wxThread::ExitCode
MyJoinableThread::Entry()
3882 unsigned long res
= 1;
3883 for ( size_t n
= 1; n
< m_n
; n
++ )
3887 // it's a loooong calculation :-)
3891 return (ExitCode
)res
;
3894 class MyDetachedThread
: public wxThread
3897 MyDetachedThread(size_t n
, char ch
)
3901 m_cancelled
= FALSE
;
3906 // thread execution starts here
3907 virtual ExitCode
Entry();
3910 virtual void OnExit();
3913 size_t m_n
; // number of characters to write
3914 char m_ch
; // character to write
3916 bool m_cancelled
; // FALSE if we exit normally
3919 wxThread::ExitCode
MyDetachedThread::Entry()
3922 wxCriticalSectionLocker
lock(gs_critsect
);
3923 if ( gs_counter
== (size_t)-1 )
3929 for ( size_t n
= 0; n
< m_n
; n
++ )
3931 if ( TestDestroy() )
3941 wxThread::Sleep(100);
3947 void MyDetachedThread::OnExit()
3949 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3951 wxCriticalSectionLocker
lock(gs_critsect
);
3952 if ( !--gs_counter
&& !m_cancelled
)
3956 void TestDetachedThreads()
3958 puts("\n*** Testing detached threads ***");
3960 static const size_t nThreads
= 3;
3961 MyDetachedThread
*threads
[nThreads
];
3963 for ( n
= 0; n
< nThreads
; n
++ )
3965 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3968 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3969 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3971 for ( n
= 0; n
< nThreads
; n
++ )
3976 // wait until all threads terminate
3982 void TestJoinableThreads()
3984 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3986 // calc 10! in the background
3987 MyJoinableThread
thread(10);
3990 printf("\nThread terminated with exit code %lu.\n",
3991 (unsigned long)thread
.Wait());
3994 void TestThreadSuspend()
3996 puts("\n*** Testing thread suspend/resume functions ***");
3998 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4002 // this is for this demo only, in a real life program we'd use another
4003 // condition variable which would be signaled from wxThread::Entry() to
4004 // tell us that the thread really started running - but here just wait a
4005 // bit and hope that it will be enough (the problem is, of course, that
4006 // the thread might still not run when we call Pause() which will result
4008 wxThread::Sleep(300);
4010 for ( size_t n
= 0; n
< 3; n
++ )
4014 puts("\nThread suspended");
4017 // don't sleep but resume immediately the first time
4018 wxThread::Sleep(300);
4020 puts("Going to resume the thread");
4025 puts("Waiting until it terminates now");
4027 // wait until the thread terminates
4033 void TestThreadDelete()
4035 // As above, using Sleep() is only for testing here - we must use some
4036 // synchronisation object instead to ensure that the thread is still
4037 // running when we delete it - deleting a detached thread which already
4038 // terminated will lead to a crash!
4040 puts("\n*** Testing thread delete function ***");
4042 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4046 puts("\nDeleted a thread which didn't start to run yet.");
4048 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4052 wxThread::Sleep(300);
4056 puts("\nDeleted a running thread.");
4058 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4062 wxThread::Sleep(300);
4068 puts("\nDeleted a sleeping thread.");
4070 MyJoinableThread
thread3(20);
4075 puts("\nDeleted a joinable thread.");
4077 MyJoinableThread
thread4(2);
4080 wxThread::Sleep(300);
4084 puts("\nDeleted a joinable thread which already terminated.");
4089 #endif // TEST_THREADS
4091 // ----------------------------------------------------------------------------
4093 // ----------------------------------------------------------------------------
4097 static void PrintArray(const char* name
, const wxArrayString
& array
)
4099 printf("Dump of the array '%s'\n", name
);
4101 size_t nCount
= array
.GetCount();
4102 for ( size_t n
= 0; n
< nCount
; n
++ )
4104 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4108 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4110 printf("Dump of the array '%s'\n", name
);
4112 size_t nCount
= array
.GetCount();
4113 for ( size_t n
= 0; n
< nCount
; n
++ )
4115 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4119 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4120 const wxString
& second
)
4122 return first
.length() - second
.length();
4125 int wxCMPFUNC_CONV
IntCompare(int *first
,
4128 return *first
- *second
;
4131 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4134 return *second
- *first
;
4137 static void TestArrayOfInts()
4139 puts("*** Testing wxArrayInt ***\n");
4150 puts("After sort:");
4154 puts("After reverse sort:");
4155 a
.Sort(IntRevCompare
);
4159 #include "wx/dynarray.h"
4161 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4162 #include "wx/arrimpl.cpp"
4163 WX_DEFINE_OBJARRAY(ArrayBars
);
4165 static void TestArrayOfObjects()
4167 puts("*** Testing wxObjArray ***\n");
4171 Bar
bar("second bar");
4173 printf("Initially: %u objects in the array, %u objects total.\n",
4174 bars
.GetCount(), Bar::GetNumber());
4176 bars
.Add(new Bar("first bar"));
4179 printf("Now: %u objects in the array, %u objects total.\n",
4180 bars
.GetCount(), Bar::GetNumber());
4184 printf("After Empty(): %u objects in the array, %u objects total.\n",
4185 bars
.GetCount(), Bar::GetNumber());
4188 printf("Finally: no more objects in the array, %u objects total.\n",
4192 #endif // TEST_ARRAYS
4194 // ----------------------------------------------------------------------------
4196 // ----------------------------------------------------------------------------
4200 #include "wx/timer.h"
4201 #include "wx/tokenzr.h"
4203 static void TestStringConstruction()
4205 puts("*** Testing wxString constructores ***");
4207 #define TEST_CTOR(args, res) \
4210 printf("wxString%s = %s ", #args, s.c_str()); \
4217 printf("(ERROR: should be %s)\n", res); \
4221 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4222 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4223 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4224 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4226 static const wxChar
*s
= _T("?really!");
4227 const wxChar
*start
= wxStrchr(s
, _T('r'));
4228 const wxChar
*end
= wxStrchr(s
, _T('!'));
4229 TEST_CTOR((start
, end
), _T("really"));
4234 static void TestString()
4244 for (int i
= 0; i
< 1000000; ++i
)
4248 c
= "! How'ya doin'?";
4251 c
= "Hello world! What's up?";
4256 printf ("TestString elapsed time: %ld\n", sw
.Time());
4259 static void TestPChar()
4267 for (int i
= 0; i
< 1000000; ++i
)
4269 strcpy (a
, "Hello");
4270 strcpy (b
, " world");
4271 strcpy (c
, "! How'ya doin'?");
4274 strcpy (c
, "Hello world! What's up?");
4275 if (strcmp (c
, a
) == 0)
4279 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4282 static void TestStringSub()
4284 wxString
s("Hello, world!");
4286 puts("*** Testing wxString substring extraction ***");
4288 printf("String = '%s'\n", s
.c_str());
4289 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4290 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4291 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4292 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4293 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4294 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4296 static const wxChar
*prefixes
[] =
4300 _T("Hello, world!"),
4301 _T("Hello, world!!!"),
4307 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4309 wxString prefix
= prefixes
[n
], rest
;
4310 bool rc
= s
.StartsWith(prefix
, &rest
);
4311 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4314 printf(" (the rest is '%s')\n", rest
.c_str());
4325 static void TestStringFormat()
4327 puts("*** Testing wxString formatting ***");
4330 s
.Printf("%03d", 18);
4332 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4333 printf("Number 18: %s\n", s
.c_str());
4338 // returns "not found" for npos, value for all others
4339 static wxString
PosToString(size_t res
)
4341 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4342 : wxString::Format(_T("%u"), res
);
4346 static void TestStringFind()
4348 puts("*** Testing wxString find() functions ***");
4350 static const wxChar
*strToFind
= _T("ell");
4351 static const struct StringFindTest
4355 result
; // of searching "ell" in str
4358 { _T("Well, hello world"), 0, 1 },
4359 { _T("Well, hello world"), 6, 7 },
4360 { _T("Well, hello world"), 9, wxString::npos
},
4363 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4365 const StringFindTest
& ft
= findTestData
[n
];
4366 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4368 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4369 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4371 size_t resTrue
= ft
.result
;
4372 if ( res
== resTrue
)
4378 printf(_T("(ERROR: should be %s)\n"),
4379 PosToString(resTrue
).c_str());
4386 static void TestStringTokenizer()
4388 puts("*** Testing wxStringTokenizer ***");
4390 static const wxChar
*modeNames
[] =
4394 _T("return all empty"),
4399 static const struct StringTokenizerTest
4401 const wxChar
*str
; // string to tokenize
4402 const wxChar
*delims
; // delimiters to use
4403 size_t count
; // count of token
4404 wxStringTokenizerMode mode
; // how should we tokenize it
4405 } tokenizerTestData
[] =
4407 { _T(""), _T(" "), 0 },
4408 { _T("Hello, world"), _T(" "), 2 },
4409 { _T("Hello, world "), _T(" "), 2 },
4410 { _T("Hello, world"), _T(","), 2 },
4411 { _T("Hello, world!"), _T(",!"), 2 },
4412 { _T("Hello,, world!"), _T(",!"), 3 },
4413 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4414 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4415 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4416 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4417 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4418 { _T("01/02/99"), _T("/-"), 3 },
4419 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4422 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4424 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4425 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4427 size_t count
= tkz
.CountTokens();
4428 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4429 MakePrintable(tt
.str
).c_str(),
4431 MakePrintable(tt
.delims
).c_str(),
4432 modeNames
[tkz
.GetMode()]);
4433 if ( count
== tt
.count
)
4439 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4444 // if we emulate strtok(), check that we do it correctly
4445 wxChar
*buf
, *s
= NULL
, *last
;
4447 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4449 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4450 wxStrcpy(buf
, tt
.str
);
4452 s
= wxStrtok(buf
, tt
.delims
, &last
);
4459 // now show the tokens themselves
4461 while ( tkz
.HasMoreTokens() )
4463 wxString token
= tkz
.GetNextToken();
4465 printf(_T("\ttoken %u: '%s'"),
4467 MakePrintable(token
).c_str());
4477 printf(" (ERROR: should be %s)\n", s
);
4480 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4484 // nothing to compare with
4489 if ( count2
!= count
)
4491 puts(_T("\tERROR: token count mismatch"));
4500 static void TestStringReplace()
4502 puts("*** Testing wxString::replace ***");
4504 static const struct StringReplaceTestData
4506 const wxChar
*original
; // original test string
4507 size_t start
, len
; // the part to replace
4508 const wxChar
*replacement
; // the replacement string
4509 const wxChar
*result
; // and the expected result
4510 } stringReplaceTestData
[] =
4512 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4513 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4514 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4515 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4516 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4519 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4521 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4523 wxString original
= data
.original
;
4524 original
.replace(data
.start
, data
.len
, data
.replacement
);
4526 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4527 data
.original
, data
.start
, data
.len
, data
.replacement
,
4530 if ( original
== data
.result
)
4536 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4543 #endif // TEST_STRINGS
4545 // ----------------------------------------------------------------------------
4547 // ----------------------------------------------------------------------------
4549 int main(int argc
, char **argv
)
4551 if ( !wxInitialize() )
4553 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4558 #endif // TEST_CHARSET
4561 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4563 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4564 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4566 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4567 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4568 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4569 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4571 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4572 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4577 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4579 parser
.AddOption("project_name", "", "full path to project file",
4580 wxCMD_LINE_VAL_STRING
,
4581 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4583 switch ( parser
.Parse() )
4586 wxLogMessage("Help was given, terminating.");
4590 ShowCmdLine(parser
);
4594 wxLogMessage("Syntax error detected, aborting.");
4597 #endif // TEST_CMDLINE
4608 TestStringConstruction();
4611 TestStringTokenizer();
4612 TestStringReplace();
4614 #endif // TEST_STRINGS
4627 puts("*** Initially:");
4629 PrintArray("a1", a1
);
4631 wxArrayString
a2(a1
);
4632 PrintArray("a2", a2
);
4634 wxSortedArrayString
a3(a1
);
4635 PrintArray("a3", a3
);
4637 puts("*** After deleting a string from a1");
4640 PrintArray("a1", a1
);
4641 PrintArray("a2", a2
);
4642 PrintArray("a3", a3
);
4644 puts("*** After reassigning a1 to a2 and a3");
4646 PrintArray("a2", a2
);
4647 PrintArray("a3", a3
);
4649 puts("*** After sorting a1");
4651 PrintArray("a1", a1
);
4653 puts("*** After sorting a1 in reverse order");
4655 PrintArray("a1", a1
);
4657 puts("*** After sorting a1 by the string length");
4658 a1
.Sort(StringLenCompare
);
4659 PrintArray("a1", a1
);
4661 TestArrayOfObjects();
4664 #endif // TEST_ARRAYS
4672 #ifdef TEST_DLLLOADER
4674 #endif // TEST_DLLLOADER
4678 #endif // TEST_ENVIRON
4682 #endif // TEST_EXECUTE
4684 #ifdef TEST_FILECONF
4686 #endif // TEST_FILECONF
4694 #endif // TEST_LOCALE
4698 for ( size_t n
= 0; n
< 8000; n
++ )
4700 s
<< (char)('A' + (n
% 26));
4704 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4706 // this one shouldn't be truncated
4709 // but this one will because log functions use fixed size buffer
4710 // (note that it doesn't need '\n' at the end neither - will be added
4712 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4724 #ifdef TEST_FILENAME
4725 TestFileNameSplit();
4728 TestFileNameConstruction();
4730 TestFileNameComparison();
4731 TestFileNameOperations();
4733 #endif // TEST_FILENAME
4736 int nCPUs
= wxThread::GetCPUCount();
4737 printf("This system has %d CPUs\n", nCPUs
);
4739 wxThread::SetConcurrency(nCPUs
);
4741 if ( argc
> 1 && argv
[1][0] == 't' )
4742 wxLog::AddTraceMask("thread");
4745 TestDetachedThreads();
4747 TestJoinableThreads();
4749 TestThreadSuspend();
4753 #endif // TEST_THREADS
4755 #ifdef TEST_LONGLONG
4756 // seed pseudo random generator
4757 srand((unsigned)time(NULL
));
4765 TestMultiplication();
4768 TestLongLongConversion();
4769 TestBitOperations();
4771 TestLongLongComparison();
4772 #endif // TEST_LONGLONG
4779 wxLog::AddTraceMask(_T("mime"));
4787 TestMimeAssociate();
4790 #ifdef TEST_INFO_FUNCTIONS
4793 #endif // TEST_INFO_FUNCTIONS
4795 #ifdef TEST_PATHLIST
4797 #endif // TEST_PATHLIST
4801 #endif // TEST_REGCONF
4803 #ifdef TEST_REGISTRY
4806 TestRegistryAssociation();
4807 #endif // TEST_REGISTRY
4815 #endif // TEST_SOCKETS
4818 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4819 if ( TestFtpConnect() )
4830 TestFtpInteractive();
4832 //else: connecting to the FTP server failed
4842 #endif // TEST_STREAMS
4846 #endif // TEST_TIMER
4848 #ifdef TEST_DATETIME
4861 TestTimeArithmetics();
4868 TestTimeSpanFormat();
4870 TestDateTimeInteractive();
4871 #endif // TEST_DATETIME
4874 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4876 #endif // TEST_USLEEP
4882 #endif // TEST_VCARD
4886 #endif // TEST_WCHAR
4890 TestZipStreamRead();
4891 TestZipFileSystem();
4896 TestZlibStreamWrite();
4897 TestZlibStreamRead();