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
61 //#define TEST_SOCKETS
62 //#define TEST_STREAMS
63 //#define TEST_STRINGS
64 //#define TEST_THREADS
66 //#define TEST_VCARD -- don't enable this (VZ)
72 #include <wx/snglinst.h>
73 #endif // TEST_SNGLINST
75 // ----------------------------------------------------------------------------
76 // test class for container objects
77 // ----------------------------------------------------------------------------
79 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
81 class Bar
// Foo is already taken in the hash test
84 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
87 static size_t GetNumber() { return ms_bars
; }
89 const char *GetName() const { return m_name
; }
94 static size_t ms_bars
;
97 size_t Bar::ms_bars
= 0;
99 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
101 // ============================================================================
103 // ============================================================================
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
111 // replace TABs with \t and CRs with \n
112 static wxString
MakePrintable(const wxChar
*s
)
115 (void)str
.Replace(_T("\t"), _T("\\t"));
116 (void)str
.Replace(_T("\n"), _T("\\n"));
117 (void)str
.Replace(_T("\r"), _T("\\r"));
122 #endif // MakePrintable() is used
124 // ----------------------------------------------------------------------------
125 // wxFontMapper::CharsetToEncoding
126 // ----------------------------------------------------------------------------
130 #include <wx/fontmap.h>
132 static void TestCharset()
134 static const wxChar
*charsets
[] =
136 // some vali charsets
145 // and now some bogus ones
152 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
154 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
155 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
157 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
158 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
162 #endif // TEST_CHARSET
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
170 #include <wx/cmdline.h>
171 #include <wx/datetime.h>
173 static void ShowCmdLine(const wxCmdLineParser
& parser
)
175 wxString s
= "Input files: ";
177 size_t count
= parser
.GetParamCount();
178 for ( size_t param
= 0; param
< count
; param
++ )
180 s
<< parser
.GetParam(param
) << ' ';
184 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
185 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
190 if ( parser
.Found("o", &strVal
) )
191 s
<< "Output file:\t" << strVal
<< '\n';
192 if ( parser
.Found("i", &strVal
) )
193 s
<< "Input dir:\t" << strVal
<< '\n';
194 if ( parser
.Found("s", &lVal
) )
195 s
<< "Size:\t" << lVal
<< '\n';
196 if ( parser
.Found("d", &dt
) )
197 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
198 if ( parser
.Found("project_name", &strVal
) )
199 s
<< "Project:\t" << strVal
<< '\n';
204 #endif // TEST_CMDLINE
206 // ----------------------------------------------------------------------------
208 // ----------------------------------------------------------------------------
215 static const wxChar
*ROOTDIR
= _T("/");
216 static const wxChar
*TESTDIR
= _T("/usr");
217 #elif defined(__WXMSW__)
218 static const wxChar
*ROOTDIR
= _T("c:\\");
219 static const wxChar
*TESTDIR
= _T("d:\\");
221 #error "don't know where the root directory is"
224 static void TestDirEnumHelper(wxDir
& dir
,
225 int flags
= wxDIR_DEFAULT
,
226 const wxString
& filespec
= wxEmptyString
)
230 if ( !dir
.IsOpened() )
233 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
236 printf("\t%s\n", filename
.c_str());
238 cont
= dir
.GetNext(&filename
);
244 static void TestDirEnum()
246 puts("*** Testing wxDir::GetFirst/GetNext ***");
248 wxDir
dir(wxGetCwd());
250 puts("Enumerating everything in current directory:");
251 TestDirEnumHelper(dir
);
253 puts("Enumerating really everything in current directory:");
254 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
256 puts("Enumerating object files in current directory:");
257 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
259 puts("Enumerating directories in current directory:");
260 TestDirEnumHelper(dir
, wxDIR_DIRS
);
262 puts("Enumerating files in current directory:");
263 TestDirEnumHelper(dir
, wxDIR_FILES
);
265 puts("Enumerating files including hidden in current directory:");
266 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
270 puts("Enumerating everything in root directory:");
271 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
273 puts("Enumerating directories in root directory:");
274 TestDirEnumHelper(dir
, wxDIR_DIRS
);
276 puts("Enumerating files in root directory:");
277 TestDirEnumHelper(dir
, wxDIR_FILES
);
279 puts("Enumerating files including hidden in root directory:");
280 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
282 puts("Enumerating files in non existing directory:");
283 wxDir
dirNo("nosuchdir");
284 TestDirEnumHelper(dirNo
);
287 class DirPrintTraverser
: public wxDirTraverser
290 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
292 return wxDIR_CONTINUE
;
295 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
297 wxString path
, name
, ext
;
298 wxSplitPath(dirname
, &path
, &name
, &ext
);
301 name
<< _T('.') << ext
;
304 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
306 if ( wxIsPathSeparator(*p
) )
310 printf("%s%s\n", indent
.c_str(), name
.c_str());
312 return wxDIR_CONTINUE
;
316 static void TestDirTraverse()
318 puts("*** Testing wxDir::Traverse() ***");
322 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
323 printf("There are %u files under '%s'\n", n
, TESTDIR
);
326 printf("First one is '%s'\n", files
[0u]);
327 printf(" last one is '%s'\n", files
[n
- 1]);
330 // enum again with custom traverser
332 DirPrintTraverser traverser
;
333 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
338 // ----------------------------------------------------------------------------
340 // ----------------------------------------------------------------------------
342 #ifdef TEST_DLLLOADER
344 #include <wx/dynlib.h>
346 static void TestDllLoad()
348 #if defined(__WXMSW__)
349 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
350 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
351 #elif defined(__UNIX__)
352 // weird: using just libc.so does *not* work!
353 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
354 static const wxChar
*FUNC_NAME
= _T("strlen");
356 #error "don't know how to test wxDllLoader on this platform"
359 puts("*** testing wxDllLoader ***\n");
361 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
364 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
368 typedef int (*strlenType
)(char *);
369 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
372 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
373 FUNC_NAME
, LIB_NAME
);
377 if ( pfnStrlen("foo") != 3 )
379 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
387 wxDllLoader::UnloadLibrary(dllHandle
);
391 #endif // TEST_DLLLOADER
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
399 #include <wx/utils.h>
401 static wxString
MyGetEnv(const wxString
& var
)
404 if ( !wxGetEnv(var
, &val
) )
407 val
= wxString(_T('\'')) + val
+ _T('\'');
412 static void TestEnvironment()
414 const wxChar
*var
= _T("wxTestVar");
416 puts("*** testing environment access functions ***");
418 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
419 wxSetEnv(var
, _T("value for wxTestVar"));
420 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
421 wxSetEnv(var
, _T("another value"));
422 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
424 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
425 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
428 #endif // TEST_ENVIRON
430 // ----------------------------------------------------------------------------
432 // ----------------------------------------------------------------------------
436 #include <wx/utils.h>
438 static void TestExecute()
440 puts("*** testing wxExecute ***");
443 #define COMMAND "cat -n ../../Makefile" // "echo hi"
444 #define SHELL_COMMAND "echo hi from shell"
445 #define REDIRECT_COMMAND COMMAND // "date"
446 #elif defined(__WXMSW__)
447 #define COMMAND "command.com -c 'echo hi'"
448 #define SHELL_COMMAND "echo hi"
449 #define REDIRECT_COMMAND COMMAND
451 #error "no command to exec"
454 printf("Testing wxShell: ");
456 if ( wxShell(SHELL_COMMAND
) )
461 printf("Testing wxExecute: ");
463 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
468 #if 0 // no, it doesn't work (yet?)
469 printf("Testing async wxExecute: ");
471 if ( wxExecute(COMMAND
) != 0 )
472 puts("Ok (command launched).");
477 printf("Testing wxExecute with redirection:\n");
478 wxArrayString output
;
479 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
485 size_t count
= output
.GetCount();
486 for ( size_t n
= 0; n
< count
; n
++ )
488 printf("\t%s\n", output
[n
].c_str());
495 #endif // TEST_EXECUTE
497 // ----------------------------------------------------------------------------
499 // ----------------------------------------------------------------------------
504 #include <wx/ffile.h>
505 #include <wx/textfile.h>
507 static void TestFileRead()
509 puts("*** wxFile read test ***");
511 wxFile
file(_T("testdata.fc"));
512 if ( file
.IsOpened() )
514 printf("File length: %lu\n", file
.Length());
516 puts("File dump:\n----------");
518 static const off_t len
= 1024;
522 off_t nRead
= file
.Read(buf
, len
);
523 if ( nRead
== wxInvalidOffset
)
525 printf("Failed to read the file.");
529 fwrite(buf
, nRead
, 1, stdout
);
539 printf("ERROR: can't open test file.\n");
545 static void TestTextFileRead()
547 puts("*** wxTextFile read test ***");
549 wxTextFile
file(_T("testdata.fc"));
552 printf("Number of lines: %u\n", file
.GetLineCount());
553 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
557 puts("\nDumping the entire file:");
558 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
560 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
562 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
564 puts("\nAnd now backwards:");
565 for ( s
= file
.GetLastLine();
566 file
.GetCurrentLine() != 0;
567 s
= file
.GetPrevLine() )
569 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
571 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
575 printf("ERROR: can't open '%s'\n", file
.GetName());
581 static void TestFileCopy()
583 puts("*** Testing wxCopyFile ***");
585 static const wxChar
*filename1
= _T("testdata.fc");
586 static const wxChar
*filename2
= _T("test2");
587 if ( !wxCopyFile(filename1
, filename2
) )
589 puts("ERROR: failed to copy file");
593 wxFFile
f1(filename1
, "rb"),
596 if ( !f1
.IsOpened() || !f2
.IsOpened() )
598 puts("ERROR: failed to open file(s)");
603 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
605 puts("ERROR: failed to read file(s)");
609 if ( (s1
.length() != s2
.length()) ||
610 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
612 puts("ERROR: copy error!");
616 puts("File was copied ok.");
622 if ( !wxRemoveFile(filename2
) )
624 puts("ERROR: failed to remove the file");
632 // ----------------------------------------------------------------------------
634 // ----------------------------------------------------------------------------
638 #include <wx/confbase.h>
639 #include <wx/fileconf.h>
641 static const struct FileConfTestData
643 const wxChar
*name
; // value name
644 const wxChar
*value
; // the value from the file
647 { _T("value1"), _T("one") },
648 { _T("value2"), _T("two") },
649 { _T("novalue"), _T("default") },
652 static void TestFileConfRead()
654 puts("*** testing wxFileConfig loading/reading ***");
656 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
657 _T("testdata.fc"), wxEmptyString
,
658 wxCONFIG_USE_RELATIVE_PATH
);
660 // test simple reading
661 puts("\nReading config file:");
662 wxString
defValue(_T("default")), value
;
663 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
665 const FileConfTestData
& data
= fcTestData
[n
];
666 value
= fileconf
.Read(data
.name
, defValue
);
667 printf("\t%s = %s ", data
.name
, value
.c_str());
668 if ( value
== data
.value
)
674 printf("(ERROR: should be %s)\n", data
.value
);
678 // test enumerating the entries
679 puts("\nEnumerating all root entries:");
682 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
685 printf("\t%s = %s\n",
687 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
689 cont
= fileconf
.GetNextEntry(name
, dummy
);
693 #endif // TEST_FILECONF
695 // ----------------------------------------------------------------------------
697 // ----------------------------------------------------------------------------
701 #include <wx/filename.h>
703 static struct FileNameInfo
705 const wxChar
*fullname
;
711 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
712 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
713 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
714 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
715 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
716 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
717 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
718 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
721 static void TestFileNameConstruction()
723 puts("*** testing wxFileName construction ***");
725 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
727 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
729 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
730 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
732 puts("ERROR (couldn't be normalized)");
736 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
743 static void TestFileNameSplit()
745 puts("*** testing wxFileName splitting ***");
747 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
749 const FileNameInfo
&fni
= filenames
[n
];
750 wxString path
, name
, ext
;
751 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
753 printf("%s -> path = '%s', name = '%s', ext = '%s'",
754 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
755 if ( path
!= fni
.path
)
756 printf(" (ERROR: path = '%s')", fni
.path
);
757 if ( name
!= fni
.name
)
758 printf(" (ERROR: name = '%s')", fni
.name
);
759 if ( ext
!= fni
.ext
)
760 printf(" (ERROR: ext = '%s')", fni
.ext
);
767 static void TestFileNameComparison()
772 static void TestFileNameOperations()
777 static void TestFileNameCwd()
782 #endif // TEST_FILENAME
784 // ----------------------------------------------------------------------------
786 // ----------------------------------------------------------------------------
794 Foo(int n_
) { n
= n_
; count
++; }
802 size_t Foo::count
= 0;
804 WX_DECLARE_LIST(Foo
, wxListFoos
);
805 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
807 #include <wx/listimpl.cpp>
809 WX_DEFINE_LIST(wxListFoos
);
811 static void TestHash()
813 puts("*** Testing wxHashTable ***\n");
817 hash
.DeleteContents(TRUE
);
819 printf("Hash created: %u foos in hash, %u foos totally\n",
820 hash
.GetCount(), Foo::count
);
822 static const int hashTestData
[] =
824 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
828 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
830 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
833 printf("Hash filled: %u foos in hash, %u foos totally\n",
834 hash
.GetCount(), Foo::count
);
836 puts("Hash access test:");
837 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
839 printf("\tGetting element with key %d, value %d: ",
841 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
844 printf("ERROR, not found.\n");
848 printf("%d (%s)\n", foo
->n
,
849 (size_t)foo
->n
== n
? "ok" : "ERROR");
853 printf("\nTrying to get an element not in hash: ");
855 if ( hash
.Get(1234) || hash
.Get(1, 0) )
857 puts("ERROR: found!");
861 puts("ok (not found)");
865 printf("Hash destroyed: %u foos left\n", Foo::count
);
870 // ----------------------------------------------------------------------------
872 // ----------------------------------------------------------------------------
878 WX_DECLARE_LIST(Bar
, wxListBars
);
879 #include <wx/listimpl.cpp>
880 WX_DEFINE_LIST(wxListBars
);
882 static void TestListCtor()
884 puts("*** Testing wxList construction ***\n");
888 list1
.Append(new Bar(_T("first")));
889 list1
.Append(new Bar(_T("second")));
891 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
892 list1
.GetCount(), Bar::GetNumber());
897 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
898 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
900 list1
.DeleteContents(TRUE
);
903 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
908 // ----------------------------------------------------------------------------
910 // ----------------------------------------------------------------------------
915 #include "wx/utils.h" // for wxSetEnv
917 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
919 // find the name of the language from its value
920 static const char *GetLangName(int lang
)
922 static const char *languageNames
[] =
943 "ARABIC_SAUDI_ARABIA",
968 "CHINESE_SIMPLIFIED",
969 "CHINESE_TRADITIONAL",
991 "ENGLISH_NEW_ZEALAND",
992 "ENGLISH_PHILIPPINES",
993 "ENGLISH_SOUTH_AFRICA",
1005 "FRENCH_LUXEMBOURG",
1014 "GERMAN_LIECHTENSTEIN",
1015 "GERMAN_LUXEMBOURG",
1056 "MALAY_BRUNEI_DARUSSALAM",
1068 "NORWEGIAN_NYNORSK",
1075 "PORTUGUESE_BRAZILIAN",
1100 "SPANISH_ARGENTINA",
1104 "SPANISH_COSTA_RICA",
1105 "SPANISH_DOMINICAN_REPUBLIC",
1107 "SPANISH_EL_SALVADOR",
1108 "SPANISH_GUATEMALA",
1112 "SPANISH_NICARAGUA",
1116 "SPANISH_PUERTO_RICO",
1119 "SPANISH_VENEZUELA",
1156 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1157 return languageNames
[lang
];
1162 static void TestDefaultLang()
1164 puts("*** Testing wxLocale::GetSystemLanguage ***");
1166 static const wxChar
*langStrings
[] =
1168 NULL
, // system default
1175 _T("de_DE.iso88591"),
1177 _T("?"), // invalid lang spec
1178 _T("klingonese"), // I bet on some systems it does exist...
1181 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1182 wxLocale::GetSystemEncodingName().c_str(),
1183 wxLocale::GetSystemEncoding());
1185 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1187 const char *langStr
= langStrings
[n
];
1190 // FIXME: this doesn't do anything at all under Windows, we need
1191 // to create a new wxLocale!
1192 wxSetEnv(_T("LC_ALL"), langStr
);
1195 int lang
= gs_localeDefault
.GetSystemLanguage();
1196 printf("Locale for '%s' is %s.\n",
1197 langStr
? langStr
: "system default", GetLangName(lang
));
1201 #endif // TEST_LOCALE
1203 // ----------------------------------------------------------------------------
1205 // ----------------------------------------------------------------------------
1209 #include <wx/mimetype.h>
1211 static void TestMimeEnum()
1213 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1215 wxArrayString mimetypes
;
1217 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1219 printf("*** All %u known filetypes: ***\n", count
);
1224 for ( size_t n
= 0; n
< count
; n
++ )
1226 wxFileType
*filetype
=
1227 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1230 printf("nothing known about the filetype '%s'!\n",
1231 mimetypes
[n
].c_str());
1235 filetype
->GetDescription(&desc
);
1236 filetype
->GetExtensions(exts
);
1238 filetype
->GetIcon(NULL
);
1241 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1244 extsAll
<< _T(", ");
1248 printf("\t%s: %s (%s)\n",
1249 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1255 static void TestMimeOverride()
1257 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1259 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1260 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1262 if ( wxFile::Exists(mailcap
) )
1263 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1265 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1267 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1270 if ( wxFile::Exists(mimetypes
) )
1271 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1273 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1275 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1281 static void TestMimeFilename()
1283 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1285 static const wxChar
*filenames
[] =
1292 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1294 const wxString fname
= filenames
[n
];
1295 wxString ext
= fname
.AfterLast(_T('.'));
1296 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1299 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1304 if ( !ft
->GetDescription(&desc
) )
1305 desc
= _T("<no description>");
1308 if ( !ft
->GetOpenCommand(&cmd
,
1309 wxFileType::MessageParameters(fname
, _T(""))) )
1310 cmd
= _T("<no command available>");
1312 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1313 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1322 static void TestMimeAssociate()
1324 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1326 wxFileTypeInfo
ftInfo(
1327 _T("application/x-xyz"),
1328 _T("xyzview '%s'"), // open cmd
1329 _T(""), // print cmd
1330 _T("XYZ File") // description
1331 _T(".xyz"), // extensions
1332 NULL
// end of extensions
1334 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1336 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1339 wxPuts(_T("ERROR: failed to create association!"));
1343 // TODO: read it back
1352 // ----------------------------------------------------------------------------
1353 // misc information functions
1354 // ----------------------------------------------------------------------------
1356 #ifdef TEST_INFO_FUNCTIONS
1358 #include <wx/utils.h>
1360 static void TestOsInfo()
1362 puts("*** Testing OS info functions ***\n");
1365 wxGetOsVersion(&major
, &minor
);
1366 printf("Running under: %s, version %d.%d\n",
1367 wxGetOsDescription().c_str(), major
, minor
);
1369 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1371 printf("Host name is %s (%s).\n",
1372 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1377 static void TestUserInfo()
1379 puts("*** Testing user info functions ***\n");
1381 printf("User id is:\t%s\n", wxGetUserId().c_str());
1382 printf("User name is:\t%s\n", wxGetUserName().c_str());
1383 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1384 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1389 #endif // TEST_INFO_FUNCTIONS
1391 // ----------------------------------------------------------------------------
1393 // ----------------------------------------------------------------------------
1395 #ifdef TEST_LONGLONG
1397 #include <wx/longlong.h>
1398 #include <wx/timer.h>
1400 // make a 64 bit number from 4 16 bit ones
1401 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1403 // get a random 64 bit number
1404 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1406 #if wxUSE_LONGLONG_WX
1407 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1408 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1409 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1410 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1411 #endif // wxUSE_LONGLONG_WX
1413 static void TestSpeed()
1415 static const long max
= 100000000;
1422 for ( n
= 0; n
< max
; n
++ )
1427 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1430 #if wxUSE_LONGLONG_NATIVE
1435 for ( n
= 0; n
< max
; n
++ )
1440 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1442 #endif // wxUSE_LONGLONG_NATIVE
1448 for ( n
= 0; n
< max
; n
++ )
1453 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1457 static void TestLongLongConversion()
1459 puts("*** Testing wxLongLong conversions ***\n");
1463 for ( size_t n
= 0; n
< 100000; n
++ )
1467 #if wxUSE_LONGLONG_NATIVE
1468 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1470 wxASSERT_MSG( a
== b
, "conversions failure" );
1472 puts("Can't do it without native long long type, test skipped.");
1475 #endif // wxUSE_LONGLONG_NATIVE
1477 if ( !(nTested
% 1000) )
1489 static void TestMultiplication()
1491 puts("*** Testing wxLongLong multiplication ***\n");
1495 for ( size_t n
= 0; n
< 100000; n
++ )
1500 #if wxUSE_LONGLONG_NATIVE
1501 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1502 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1504 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1505 #else // !wxUSE_LONGLONG_NATIVE
1506 puts("Can't do it without native long long type, test skipped.");
1509 #endif // wxUSE_LONGLONG_NATIVE
1511 if ( !(nTested
% 1000) )
1523 static void TestDivision()
1525 puts("*** Testing wxLongLong division ***\n");
1529 for ( size_t n
= 0; n
< 100000; n
++ )
1531 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1532 // multiplication will not overflow)
1533 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1535 // get a random long (not wxLongLong for now) to divide it with
1540 #if wxUSE_LONGLONG_NATIVE
1541 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1543 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1544 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1545 #else // !wxUSE_LONGLONG_NATIVE
1546 // verify the result
1547 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1548 #endif // wxUSE_LONGLONG_NATIVE
1550 if ( !(nTested
% 1000) )
1562 static void TestAddition()
1564 puts("*** Testing wxLongLong addition ***\n");
1568 for ( size_t n
= 0; n
< 100000; n
++ )
1574 #if wxUSE_LONGLONG_NATIVE
1575 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1576 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1577 "addition failure" );
1578 #else // !wxUSE_LONGLONG_NATIVE
1579 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1580 #endif // wxUSE_LONGLONG_NATIVE
1582 if ( !(nTested
% 1000) )
1594 static void TestBitOperations()
1596 puts("*** Testing wxLongLong bit operation ***\n");
1600 for ( size_t n
= 0; n
< 100000; n
++ )
1604 #if wxUSE_LONGLONG_NATIVE
1605 for ( size_t n
= 0; n
< 33; n
++ )
1608 #else // !wxUSE_LONGLONG_NATIVE
1609 puts("Can't do it without native long long type, test skipped.");
1612 #endif // wxUSE_LONGLONG_NATIVE
1614 if ( !(nTested
% 1000) )
1626 static void TestLongLongComparison()
1628 puts("*** Testing wxLongLong comparison ***\n");
1630 static const long testLongs
[] =
1641 static const long ls
[2] =
1647 wxLongLongWx lls
[2];
1651 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1655 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
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");
1667 res
= lls
[m
] == testLongs
[n
];
1668 printf("0x%lx == 0x%lx is %s (%s)\n",
1669 ls
[m
], testLongs
[n
], res
? "true" : "false",
1670 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1678 #endif // TEST_LONGLONG
1680 // ----------------------------------------------------------------------------
1682 // ----------------------------------------------------------------------------
1684 #ifdef TEST_PATHLIST
1686 static void TestPathList()
1688 puts("*** Testing wxPathList ***\n");
1690 wxPathList pathlist
;
1691 pathlist
.AddEnvList("PATH");
1692 wxString path
= pathlist
.FindValidPath("ls");
1695 printf("ERROR: command not found in the path.\n");
1699 printf("Command found in the path as '%s'.\n", path
.c_str());
1703 #endif // TEST_PATHLIST
1705 // ----------------------------------------------------------------------------
1706 // registry and related stuff
1707 // ----------------------------------------------------------------------------
1709 // this is for MSW only
1712 #undef TEST_REGISTRY
1717 #include <wx/confbase.h>
1718 #include <wx/msw/regconf.h>
1720 static void TestRegConfWrite()
1722 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1723 regconf
.Write(_T("Hello"), wxString(_T("world")));
1726 #endif // TEST_REGCONF
1728 #ifdef TEST_REGISTRY
1730 #include <wx/msw/registry.h>
1732 // I chose this one because I liked its name, but it probably only exists under
1734 static const wxChar
*TESTKEY
=
1735 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1737 static void TestRegistryRead()
1739 puts("*** testing registry reading ***");
1741 wxRegKey
key(TESTKEY
);
1742 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1745 puts("ERROR: test key can't be opened, aborting test.");
1750 size_t nSubKeys
, nValues
;
1751 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1753 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1756 printf("Enumerating values:\n");
1760 bool cont
= key
.GetFirstValue(value
, dummy
);
1763 printf("Value '%s': type ", value
.c_str());
1764 switch ( key
.GetValueType(value
) )
1766 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1767 case wxRegKey::Type_String
: printf("SZ"); break;
1768 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1769 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1770 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1771 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1772 default: printf("other (unknown)"); break;
1775 printf(", value = ");
1776 if ( key
.IsNumericValue(value
) )
1779 key
.QueryValue(value
, &val
);
1785 key
.QueryValue(value
, val
);
1786 printf("'%s'", val
.c_str());
1788 key
.QueryRawValue(value
, val
);
1789 printf(" (raw value '%s')", val
.c_str());
1794 cont
= key
.GetNextValue(value
, dummy
);
1798 static void TestRegistryAssociation()
1801 The second call to deleteself genertaes an error message, with a
1802 messagebox saying .flo is crucial to system operation, while the .ddf
1803 call also fails, but with no error message
1808 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1810 key
= "ddxf_auto_file" ;
1811 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1813 key
= "ddxf_auto_file" ;
1814 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1817 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1819 key
= "program \"%1\"" ;
1821 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1823 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1825 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1827 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1831 #endif // TEST_REGISTRY
1833 // ----------------------------------------------------------------------------
1835 // ----------------------------------------------------------------------------
1839 #include <wx/socket.h>
1840 #include <wx/protocol/protocol.h>
1841 #include <wx/protocol/http.h>
1843 static void TestSocketServer()
1845 puts("*** Testing wxSocketServer ***\n");
1847 static const int PORT
= 3000;
1852 wxSocketServer
*server
= new wxSocketServer(addr
);
1853 if ( !server
->Ok() )
1855 puts("ERROR: failed to bind");
1862 printf("Server: waiting for connection on port %d...\n", PORT
);
1864 wxSocketBase
*socket
= server
->Accept();
1867 puts("ERROR: wxSocketServer::Accept() failed.");
1871 puts("Server: got a client.");
1873 server
->SetTimeout(60); // 1 min
1875 while ( socket
->IsConnected() )
1881 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1883 // don't log error if the client just close the connection
1884 if ( socket
->IsConnected() )
1886 puts("ERROR: in wxSocket::Read.");
1906 printf("Server: got '%s'.\n", s
.c_str());
1907 if ( s
== _T("bye") )
1914 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1915 socket
->Write("\r\n", 2);
1916 printf("Server: wrote '%s'.\n", s
.c_str());
1919 puts("Server: lost a client.");
1924 // same as "delete server" but is consistent with GUI programs
1928 static void TestSocketClient()
1930 puts("*** Testing wxSocketClient ***\n");
1932 static const char *hostname
= "www.wxwindows.org";
1935 addr
.Hostname(hostname
);
1938 printf("--- Attempting to connect to %s:80...\n", hostname
);
1940 wxSocketClient client
;
1941 if ( !client
.Connect(addr
) )
1943 printf("ERROR: failed to connect to %s\n", hostname
);
1947 printf("--- Connected to %s:%u...\n",
1948 addr
.Hostname().c_str(), addr
.Service());
1952 // could use simply "GET" here I suppose
1954 wxString::Format("GET http://%s/\r\n", hostname
);
1955 client
.Write(cmdGet
, cmdGet
.length());
1956 printf("--- Sent command '%s' to the server\n",
1957 MakePrintable(cmdGet
).c_str());
1958 client
.Read(buf
, WXSIZEOF(buf
));
1959 printf("--- Server replied:\n%s", buf
);
1963 #endif // TEST_SOCKETS
1965 // ----------------------------------------------------------------------------
1967 // ----------------------------------------------------------------------------
1971 #include <wx/protocol/ftp.h>
1975 #define FTP_ANONYMOUS
1977 #ifdef FTP_ANONYMOUS
1978 static const char *directory
= "/pub";
1979 static const char *filename
= "welcome.msg";
1981 static const char *directory
= "/etc";
1982 static const char *filename
= "issue";
1985 static bool TestFtpConnect()
1987 puts("*** Testing FTP connect ***");
1989 #ifdef FTP_ANONYMOUS
1990 static const char *hostname
= "ftp.wxwindows.org";
1992 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1993 #else // !FTP_ANONYMOUS
1994 static const char *hostname
= "localhost";
1997 fgets(user
, WXSIZEOF(user
), stdin
);
1998 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2002 printf("Password for %s: ", password
);
2003 fgets(password
, WXSIZEOF(password
), stdin
);
2004 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2005 ftp
.SetPassword(password
);
2007 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2008 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2010 if ( !ftp
.Connect(hostname
) )
2012 printf("ERROR: failed to connect to %s\n", hostname
);
2018 printf("--- Connected to %s, current directory is '%s'\n",
2019 hostname
, ftp
.Pwd().c_str());
2025 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2026 static void TestFtpWuFtpd()
2029 static const char *hostname
= "ftp.eudora.com";
2030 if ( !ftp
.Connect(hostname
) )
2032 printf("ERROR: failed to connect to %s\n", hostname
);
2036 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2037 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2040 printf("ERROR: couldn't get input stream for %s\n", filename
);
2044 size_t size
= in
->StreamSize();
2045 printf("Reading file %s (%u bytes)...", filename
, size
);
2047 char *data
= new char[size
];
2048 if ( !in
->Read(data
, size
) )
2050 puts("ERROR: read error");
2054 printf("Successfully retrieved the file.\n");
2063 static void TestFtpList()
2065 puts("*** Testing wxFTP file listing ***\n");
2068 if ( !ftp
.ChDir(directory
) )
2070 printf("ERROR: failed to cd to %s\n", directory
);
2073 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2075 // test NLIST and LIST
2076 wxArrayString files
;
2077 if ( !ftp
.GetFilesList(files
) )
2079 puts("ERROR: failed to get NLIST of files");
2083 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2084 size_t count
= files
.GetCount();
2085 for ( size_t n
= 0; n
< count
; n
++ )
2087 printf("\t%s\n", files
[n
].c_str());
2089 puts("End of the file list");
2092 if ( !ftp
.GetDirList(files
) )
2094 puts("ERROR: failed to get LIST of files");
2098 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2099 size_t count
= files
.GetCount();
2100 for ( size_t n
= 0; n
< count
; n
++ )
2102 printf("\t%s\n", files
[n
].c_str());
2104 puts("End of the file list");
2107 if ( !ftp
.ChDir(_T("..")) )
2109 puts("ERROR: failed to cd to ..");
2112 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2115 static void TestFtpDownload()
2117 puts("*** Testing wxFTP download ***\n");
2120 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2123 printf("ERROR: couldn't get input stream for %s\n", filename
);
2127 size_t size
= in
->StreamSize();
2128 printf("Reading file %s (%u bytes)...", filename
, size
);
2131 char *data
= new char[size
];
2132 if ( !in
->Read(data
, size
) )
2134 puts("ERROR: read error");
2138 printf("\nContents of %s:\n%s\n", filename
, data
);
2146 static void TestFtpFileSize()
2148 puts("*** Testing FTP SIZE command ***");
2150 if ( !ftp
.ChDir(directory
) )
2152 printf("ERROR: failed to cd to %s\n", directory
);
2155 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2157 if ( ftp
.FileExists(filename
) )
2159 int size
= ftp
.GetFileSize(filename
);
2161 printf("ERROR: couldn't get size of '%s'\n", filename
);
2163 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2167 printf("ERROR: '%s' doesn't exist\n", filename
);
2171 static void TestFtpMisc()
2173 puts("*** Testing miscellaneous wxFTP functions ***");
2175 if ( ftp
.SendCommand("STAT") != '2' )
2177 puts("ERROR: STAT failed");
2181 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2184 if ( ftp
.SendCommand("HELP SITE") != '2' )
2186 puts("ERROR: HELP SITE failed");
2190 printf("The list of site-specific commands:\n\n%s\n",
2191 ftp
.GetLastResult().c_str());
2195 static void TestFtpInteractive()
2197 puts("\n*** Interactive wxFTP test ***");
2203 printf("Enter FTP command: ");
2204 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2207 // kill the last '\n'
2208 buf
[strlen(buf
) - 1] = 0;
2210 // special handling of LIST and NLST as they require data connection
2211 wxString
start(buf
, 4);
2213 if ( start
== "LIST" || start
== "NLST" )
2216 if ( strlen(buf
) > 4 )
2219 wxArrayString files
;
2220 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2222 printf("ERROR: failed to get %s of files\n", start
.c_str());
2226 printf("--- %s of '%s' under '%s':\n",
2227 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2228 size_t count
= files
.GetCount();
2229 for ( size_t n
= 0; n
< count
; n
++ )
2231 printf("\t%s\n", files
[n
].c_str());
2233 puts("--- End of the file list");
2238 char ch
= ftp
.SendCommand(buf
);
2239 printf("Command %s", ch
? "succeeded" : "failed");
2242 printf(" (return code %c)", ch
);
2245 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2249 puts("\n*** done ***");
2252 static void TestFtpUpload()
2254 puts("*** Testing wxFTP uploading ***\n");
2257 static const char *file1
= "test1";
2258 static const char *file2
= "test2";
2259 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2262 printf("--- Uploading to %s ---\n", file1
);
2263 out
->Write("First hello", 11);
2267 // send a command to check the remote file
2268 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2270 printf("ERROR: STAT %s failed\n", file1
);
2274 printf("STAT %s returned:\n\n%s\n",
2275 file1
, ftp
.GetLastResult().c_str());
2278 out
= ftp
.GetOutputStream(file2
);
2281 printf("--- Uploading to %s ---\n", file1
);
2282 out
->Write("Second hello", 12);
2289 // ----------------------------------------------------------------------------
2291 // ----------------------------------------------------------------------------
2295 #include <wx/wfstream.h>
2296 #include <wx/mstream.h>
2298 static void TestFileStream()
2300 puts("*** Testing wxFileInputStream ***");
2302 static const wxChar
*filename
= _T("testdata.fs");
2304 wxFileOutputStream
fsOut(filename
);
2305 fsOut
.Write("foo", 3);
2308 wxFileInputStream
fsIn(filename
);
2309 printf("File stream size: %u\n", fsIn
.GetSize());
2310 while ( !fsIn
.Eof() )
2312 putchar(fsIn
.GetC());
2315 if ( !wxRemoveFile(filename
) )
2317 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2320 puts("\n*** wxFileInputStream test done ***");
2323 static void TestMemoryStream()
2325 puts("*** Testing wxMemoryInputStream ***");
2328 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2330 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2331 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2332 while ( !memInpStream
.Eof() )
2334 putchar(memInpStream
.GetC());
2337 puts("\n*** wxMemoryInputStream test done ***");
2340 #endif // TEST_STREAMS
2342 // ----------------------------------------------------------------------------
2344 // ----------------------------------------------------------------------------
2348 #include <wx/timer.h>
2349 #include <wx/utils.h>
2351 static void TestStopWatch()
2353 puts("*** Testing wxStopWatch ***\n");
2356 printf("Sleeping 3 seconds...");
2358 printf("\telapsed time: %ldms\n", sw
.Time());
2361 printf("Sleeping 2 more seconds...");
2363 printf("\telapsed time: %ldms\n", sw
.Time());
2366 printf("And 3 more seconds...");
2368 printf("\telapsed time: %ldms\n", sw
.Time());
2371 puts("\nChecking for 'backwards clock' bug...");
2372 for ( size_t n
= 0; n
< 70; n
++ )
2376 for ( size_t m
= 0; m
< 100000; m
++ )
2378 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2380 puts("\ntime is negative - ERROR!");
2390 #endif // TEST_TIMER
2392 // ----------------------------------------------------------------------------
2394 // ----------------------------------------------------------------------------
2398 #include <wx/vcard.h>
2400 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2403 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2407 wxString(_T('\t'), level
).c_str(),
2408 vcObj
->GetName().c_str());
2411 switch ( vcObj
->GetType() )
2413 case wxVCardObject::String
:
2414 case wxVCardObject::UString
:
2417 vcObj
->GetValue(&val
);
2418 value
<< _T('"') << val
<< _T('"');
2422 case wxVCardObject::Int
:
2425 vcObj
->GetValue(&i
);
2426 value
.Printf(_T("%u"), i
);
2430 case wxVCardObject::Long
:
2433 vcObj
->GetValue(&l
);
2434 value
.Printf(_T("%lu"), l
);
2438 case wxVCardObject::None
:
2441 case wxVCardObject::Object
:
2442 value
= _T("<node>");
2446 value
= _T("<unknown value type>");
2450 printf(" = %s", value
.c_str());
2453 DumpVObject(level
+ 1, *vcObj
);
2456 vcObj
= vcard
.GetNextProp(&cookie
);
2460 static void DumpVCardAddresses(const wxVCard
& vcard
)
2462 puts("\nShowing all addresses from vCard:\n");
2466 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2470 int flags
= addr
->GetFlags();
2471 if ( flags
& wxVCardAddress::Domestic
)
2473 flagsStr
<< _T("domestic ");
2475 if ( flags
& wxVCardAddress::Intl
)
2477 flagsStr
<< _T("international ");
2479 if ( flags
& wxVCardAddress::Postal
)
2481 flagsStr
<< _T("postal ");
2483 if ( flags
& wxVCardAddress::Parcel
)
2485 flagsStr
<< _T("parcel ");
2487 if ( flags
& wxVCardAddress::Home
)
2489 flagsStr
<< _T("home ");
2491 if ( flags
& wxVCardAddress::Work
)
2493 flagsStr
<< _T("work ");
2496 printf("Address %u:\n"
2498 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2501 addr
->GetPostOffice().c_str(),
2502 addr
->GetExtAddress().c_str(),
2503 addr
->GetStreet().c_str(),
2504 addr
->GetLocality().c_str(),
2505 addr
->GetRegion().c_str(),
2506 addr
->GetPostalCode().c_str(),
2507 addr
->GetCountry().c_str()
2511 addr
= vcard
.GetNextAddress(&cookie
);
2515 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2517 puts("\nShowing all phone numbers from vCard:\n");
2521 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2525 int flags
= phone
->GetFlags();
2526 if ( flags
& wxVCardPhoneNumber::Voice
)
2528 flagsStr
<< _T("voice ");
2530 if ( flags
& wxVCardPhoneNumber::Fax
)
2532 flagsStr
<< _T("fax ");
2534 if ( flags
& wxVCardPhoneNumber::Cellular
)
2536 flagsStr
<< _T("cellular ");
2538 if ( flags
& wxVCardPhoneNumber::Modem
)
2540 flagsStr
<< _T("modem ");
2542 if ( flags
& wxVCardPhoneNumber::Home
)
2544 flagsStr
<< _T("home ");
2546 if ( flags
& wxVCardPhoneNumber::Work
)
2548 flagsStr
<< _T("work ");
2551 printf("Phone number %u:\n"
2556 phone
->GetNumber().c_str()
2560 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2564 static void TestVCardRead()
2566 puts("*** Testing wxVCard reading ***\n");
2568 wxVCard
vcard(_T("vcard.vcf"));
2569 if ( !vcard
.IsOk() )
2571 puts("ERROR: couldn't load vCard.");
2575 // read individual vCard properties
2576 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2580 vcObj
->GetValue(&value
);
2585 value
= _T("<none>");
2588 printf("Full name retrieved directly: %s\n", value
.c_str());
2591 if ( !vcard
.GetFullName(&value
) )
2593 value
= _T("<none>");
2596 printf("Full name from wxVCard API: %s\n", value
.c_str());
2598 // now show how to deal with multiply occuring properties
2599 DumpVCardAddresses(vcard
);
2600 DumpVCardPhoneNumbers(vcard
);
2602 // and finally show all
2603 puts("\nNow dumping the entire vCard:\n"
2604 "-----------------------------\n");
2606 DumpVObject(0, vcard
);
2610 static void TestVCardWrite()
2612 puts("*** Testing wxVCard writing ***\n");
2615 if ( !vcard
.IsOk() )
2617 puts("ERROR: couldn't create vCard.");
2622 vcard
.SetName("Zeitlin", "Vadim");
2623 vcard
.SetFullName("Vadim Zeitlin");
2624 vcard
.SetOrganization("wxWindows", "R&D");
2626 // just dump the vCard back
2627 puts("Entire vCard follows:\n");
2628 puts(vcard
.Write());
2632 #endif // TEST_VCARD
2634 // ----------------------------------------------------------------------------
2635 // wide char (Unicode) support
2636 // ----------------------------------------------------------------------------
2640 #include <wx/strconv.h>
2641 #include <wx/fontenc.h>
2642 #include <wx/encconv.h>
2643 #include <wx/buffer.h>
2645 static void TestUtf8()
2647 puts("*** Testing UTF8 support ***\n");
2649 static const char textInUtf8
[] =
2651 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2652 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2653 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2654 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2655 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2656 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2657 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2662 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2664 puts("ERROR: UTF-8 decoding failed.");
2668 // using wxEncodingConverter
2670 wxEncodingConverter ec
;
2671 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2672 ec
.Convert(wbuf
, buf
);
2673 #else // using wxCSConv
2674 wxCSConv
conv(_T("koi8-r"));
2675 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2677 puts("ERROR: conversion to KOI8-R failed.");
2682 printf("The resulting string (in koi8-r): %s\n", buf
);
2686 #endif // TEST_WCHAR
2688 // ----------------------------------------------------------------------------
2690 // ----------------------------------------------------------------------------
2694 #include "wx/filesys.h"
2695 #include "wx/fs_zip.h"
2696 #include "wx/zipstrm.h"
2698 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2700 static void TestZipStreamRead()
2702 puts("*** Testing ZIP reading ***\n");
2704 static const wxChar
*filename
= _T("foo");
2705 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2706 printf("Archive size: %u\n", istr
.GetSize());
2708 printf("Dumping the file '%s':\n", filename
);
2709 while ( !istr
.Eof() )
2711 putchar(istr
.GetC());
2715 puts("\n----- done ------");
2718 static void DumpZipDirectory(wxFileSystem
& fs
,
2719 const wxString
& dir
,
2720 const wxString
& indent
)
2722 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2723 TESTFILE_ZIP
, dir
.c_str());
2724 wxString wildcard
= prefix
+ _T("/*");
2726 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2727 while ( !dirname
.empty() )
2729 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2731 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2736 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2738 DumpZipDirectory(fs
, dirname
,
2739 indent
+ wxString(_T(' '), 4));
2741 dirname
= fs
.FindNext();
2744 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2745 while ( !filename
.empty() )
2747 if ( !filename
.StartsWith(prefix
, &filename
) )
2749 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2754 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2756 filename
= fs
.FindNext();
2760 static void TestZipFileSystem()
2762 puts("*** Testing ZIP file system ***\n");
2764 wxFileSystem::AddHandler(new wxZipFSHandler
);
2766 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2768 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2773 // ----------------------------------------------------------------------------
2775 // ----------------------------------------------------------------------------
2779 #include <wx/zstream.h>
2780 #include <wx/wfstream.h>
2782 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2783 static const char *TEST_DATA
= "hello and hello again";
2785 static void TestZlibStreamWrite()
2787 puts("*** Testing Zlib stream reading ***\n");
2789 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2790 wxZlibOutputStream
ostr(fileOutStream
, 0);
2791 printf("Compressing the test string... ");
2792 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2795 puts("(ERROR: failed)");
2802 puts("\n----- done ------");
2805 static void TestZlibStreamRead()
2807 puts("*** Testing Zlib stream reading ***\n");
2809 wxFileInputStream
fileInStream(FILENAME_GZ
);
2810 wxZlibInputStream
istr(fileInStream
);
2811 printf("Archive size: %u\n", istr
.GetSize());
2813 puts("Dumping the file:");
2814 while ( !istr
.Eof() )
2816 putchar(istr
.GetC());
2820 puts("\n----- done ------");
2825 // ----------------------------------------------------------------------------
2827 // ----------------------------------------------------------------------------
2829 #ifdef TEST_DATETIME
2833 #include <wx/date.h>
2835 #include <wx/datetime.h>
2840 wxDateTime::wxDateTime_t day
;
2841 wxDateTime::Month month
;
2843 wxDateTime::wxDateTime_t hour
, min
, sec
;
2845 wxDateTime::WeekDay wday
;
2846 time_t gmticks
, ticks
;
2848 void Init(const wxDateTime::Tm
& tm
)
2857 gmticks
= ticks
= -1;
2860 wxDateTime
DT() const
2861 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2863 bool SameDay(const wxDateTime::Tm
& tm
) const
2865 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2868 wxString
Format() const
2871 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2873 wxDateTime::GetMonthName(month
).c_str(),
2875 abs(wxDateTime::ConvertYearToBC(year
)),
2876 year
> 0 ? "AD" : "BC");
2880 wxString
FormatDate() const
2883 s
.Printf("%02d-%s-%4d%s",
2885 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2886 abs(wxDateTime::ConvertYearToBC(year
)),
2887 year
> 0 ? "AD" : "BC");
2892 static const Date testDates
[] =
2894 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2895 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2896 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2897 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2898 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2899 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2900 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2901 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2902 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2903 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2904 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2905 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2906 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2907 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2908 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2911 // this test miscellaneous static wxDateTime functions
2912 static void TestTimeStatic()
2914 puts("\n*** wxDateTime static methods test ***");
2916 // some info about the current date
2917 int year
= wxDateTime::GetCurrentYear();
2918 printf("Current year %d is %sa leap one and has %d days.\n",
2920 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2921 wxDateTime::GetNumberOfDays(year
));
2923 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2924 printf("Current month is '%s' ('%s') and it has %d days\n",
2925 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2926 wxDateTime::GetMonthName(month
).c_str(),
2927 wxDateTime::GetNumberOfDays(month
));
2930 static const size_t nYears
= 5;
2931 static const size_t years
[2][nYears
] =
2933 // first line: the years to test
2934 { 1990, 1976, 2000, 2030, 1984, },
2936 // second line: TRUE if leap, FALSE otherwise
2937 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2940 for ( size_t n
= 0; n
< nYears
; n
++ )
2942 int year
= years
[0][n
];
2943 bool should
= years
[1][n
] != 0,
2944 is
= wxDateTime::IsLeapYear(year
);
2946 printf("Year %d is %sa leap year (%s)\n",
2949 should
== is
? "ok" : "ERROR");
2951 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2955 // test constructing wxDateTime objects
2956 static void TestTimeSet()
2958 puts("\n*** wxDateTime construction test ***");
2960 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2962 const Date
& d1
= testDates
[n
];
2963 wxDateTime dt
= d1
.DT();
2966 d2
.Init(dt
.GetTm());
2968 wxString s1
= d1
.Format(),
2971 printf("Date: %s == %s (%s)\n",
2972 s1
.c_str(), s2
.c_str(),
2973 s1
== s2
? "ok" : "ERROR");
2977 // test time zones stuff
2978 static void TestTimeZones()
2980 puts("\n*** wxDateTime timezone test ***");
2982 wxDateTime now
= wxDateTime::Now();
2984 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2985 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2986 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2987 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2988 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2989 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2991 wxDateTime::Tm tm
= now
.GetTm();
2992 if ( wxDateTime(tm
) != now
)
2994 printf("ERROR: got %s instead of %s\n",
2995 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2999 // test some minimal support for the dates outside the standard range
3000 static void TestTimeRange()
3002 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3004 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3006 printf("Unix epoch:\t%s\n",
3007 wxDateTime(2440587.5).Format(fmt
).c_str());
3008 printf("Feb 29, 0: \t%s\n",
3009 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3010 printf("JDN 0: \t%s\n",
3011 wxDateTime(0.0).Format(fmt
).c_str());
3012 printf("Jan 1, 1AD:\t%s\n",
3013 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3014 printf("May 29, 2099:\t%s\n",
3015 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3018 static void TestTimeTicks()
3020 puts("\n*** wxDateTime ticks test ***");
3022 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3024 const Date
& d
= testDates
[n
];
3025 if ( d
.ticks
== -1 )
3028 wxDateTime dt
= d
.DT();
3029 long ticks
= (dt
.GetValue() / 1000).ToLong();
3030 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3031 if ( ticks
== d
.ticks
)
3037 printf(" (ERROR: should be %ld, delta = %ld)\n",
3038 d
.ticks
, ticks
- d
.ticks
);
3041 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3042 ticks
= (dt
.GetValue() / 1000).ToLong();
3043 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3044 if ( ticks
== d
.gmticks
)
3050 printf(" (ERROR: should be %ld, delta = %ld)\n",
3051 d
.gmticks
, ticks
- d
.gmticks
);
3058 // test conversions to JDN &c
3059 static void TestTimeJDN()
3061 puts("\n*** wxDateTime to JDN test ***");
3063 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3065 const Date
& d
= testDates
[n
];
3066 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3067 double jdn
= dt
.GetJulianDayNumber();
3069 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3076 printf(" (ERROR: should be %f, delta = %f)\n",
3077 d
.jdn
, jdn
- d
.jdn
);
3082 // test week days computation
3083 static void TestTimeWDays()
3085 puts("\n*** wxDateTime weekday test ***");
3087 // test GetWeekDay()
3089 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3091 const Date
& d
= testDates
[n
];
3092 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3094 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3097 wxDateTime::GetWeekDayName(wday
).c_str());
3098 if ( wday
== d
.wday
)
3104 printf(" (ERROR: should be %s)\n",
3105 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3111 // test SetToWeekDay()
3112 struct WeekDateTestData
3114 Date date
; // the real date (precomputed)
3115 int nWeek
; // its week index in the month
3116 wxDateTime::WeekDay wday
; // the weekday
3117 wxDateTime::Month month
; // the month
3118 int year
; // and the year
3120 wxString
Format() const
3123 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3125 case 1: which
= "first"; break;
3126 case 2: which
= "second"; break;
3127 case 3: which
= "third"; break;
3128 case 4: which
= "fourth"; break;
3129 case 5: which
= "fifth"; break;
3131 case -1: which
= "last"; break;
3136 which
+= " from end";
3139 s
.Printf("The %s %s of %s in %d",
3141 wxDateTime::GetWeekDayName(wday
).c_str(),
3142 wxDateTime::GetMonthName(month
).c_str(),
3149 // the array data was generated by the following python program
3151 from DateTime import *
3152 from whrandom import *
3153 from string import *
3155 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3156 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3158 week = DateTimeDelta(7)
3161 year = randint(1900, 2100)
3162 month = randint(1, 12)
3163 day = randint(1, 28)
3164 dt = DateTime(year, month, day)
3165 wday = dt.day_of_week
3167 countFromEnd = choice([-1, 1])
3170 while dt.month is month:
3171 dt = dt - countFromEnd * week
3172 weekNum = weekNum + countFromEnd
3174 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3176 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3177 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3180 static const WeekDateTestData weekDatesTestData
[] =
3182 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3183 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3184 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3185 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3186 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3187 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3188 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3189 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3190 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3191 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3192 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3193 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3194 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3195 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3196 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3197 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3198 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3199 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3200 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3201 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3204 static const char *fmt
= "%d-%b-%Y";
3207 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3209 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3211 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3213 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3215 const Date
& d
= wd
.date
;
3216 if ( d
.SameDay(dt
.GetTm()) )
3222 dt
.Set(d
.day
, d
.month
, d
.year
);
3224 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3229 // test the computation of (ISO) week numbers
3230 static void TestTimeWNumber()
3232 puts("\n*** wxDateTime week number test ***");
3234 struct WeekNumberTestData
3236 Date date
; // the date
3237 wxDateTime::wxDateTime_t week
; // the week number in the year
3238 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3239 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3240 wxDateTime::wxDateTime_t dnum
; // day number in the year
3243 // data generated with the following python script:
3245 from DateTime import *
3246 from whrandom import *
3247 from string import *
3249 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3250 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3252 def GetMonthWeek(dt):
3253 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3254 if weekNumMonth < 0:
3255 weekNumMonth = weekNumMonth + 53
3258 def GetLastSundayBefore(dt):
3259 if dt.iso_week[2] == 7:
3262 return dt - DateTimeDelta(dt.iso_week[2])
3265 year = randint(1900, 2100)
3266 month = randint(1, 12)
3267 day = randint(1, 28)
3268 dt = DateTime(year, month, day)
3269 dayNum = dt.day_of_year
3270 weekNum = dt.iso_week[1]
3271 weekNumMonth = GetMonthWeek(dt)
3274 dtSunday = GetLastSundayBefore(dt)
3276 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3277 weekNumMonth2 = weekNumMonth2 + 1
3278 dtSunday = dtSunday - DateTimeDelta(7)
3280 data = { 'day': rjust(`day`, 2), \
3281 'month': monthNames[month - 1], \
3283 'weekNum': rjust(`weekNum`, 2), \
3284 'weekNumMonth': weekNumMonth, \
3285 'weekNumMonth2': weekNumMonth2, \
3286 'dayNum': rjust(`dayNum`, 3) }
3288 print " { { %(day)s, "\
3289 "wxDateTime::%(month)s, "\
3292 "%(weekNumMonth)s, "\
3293 "%(weekNumMonth2)s, "\
3294 "%(dayNum)s }," % data
3297 static const WeekNumberTestData weekNumberTestDates
[] =
3299 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3300 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3301 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3302 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3303 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3304 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3305 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3306 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3307 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3308 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3309 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3310 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3311 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3312 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3313 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3314 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3315 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3316 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3317 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3318 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3321 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3323 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3324 const Date
& d
= wn
.date
;
3326 wxDateTime dt
= d
.DT();
3328 wxDateTime::wxDateTime_t
3329 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3330 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3331 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3332 dnum
= dt
.GetDayOfYear();
3334 printf("%s: the day number is %d",
3335 d
.FormatDate().c_str(), dnum
);
3336 if ( dnum
== wn
.dnum
)
3342 printf(" (ERROR: should be %d)", wn
.dnum
);
3345 printf(", week in month is %d", wmon
);
3346 if ( wmon
== wn
.wmon
)
3352 printf(" (ERROR: should be %d)", wn
.wmon
);
3355 printf(" or %d", wmon2
);
3356 if ( wmon2
== wn
.wmon2
)
3362 printf(" (ERROR: should be %d)", wn
.wmon2
);
3365 printf(", week in year is %d", week
);
3366 if ( week
== wn
.week
)
3372 printf(" (ERROR: should be %d)\n", wn
.week
);
3377 // test DST calculations
3378 static void TestTimeDST()
3380 puts("\n*** wxDateTime DST test ***");
3382 printf("DST is%s in effect now.\n\n",
3383 wxDateTime::Now().IsDST() ? "" : " not");
3385 // taken from http://www.energy.ca.gov/daylightsaving.html
3386 static const Date datesDST
[2][2004 - 1900 + 1] =
3389 { 1, wxDateTime::Apr
, 1990 },
3390 { 7, wxDateTime::Apr
, 1991 },
3391 { 5, wxDateTime::Apr
, 1992 },
3392 { 4, wxDateTime::Apr
, 1993 },
3393 { 3, wxDateTime::Apr
, 1994 },
3394 { 2, wxDateTime::Apr
, 1995 },
3395 { 7, wxDateTime::Apr
, 1996 },
3396 { 6, wxDateTime::Apr
, 1997 },
3397 { 5, wxDateTime::Apr
, 1998 },
3398 { 4, wxDateTime::Apr
, 1999 },
3399 { 2, wxDateTime::Apr
, 2000 },
3400 { 1, wxDateTime::Apr
, 2001 },
3401 { 7, wxDateTime::Apr
, 2002 },
3402 { 6, wxDateTime::Apr
, 2003 },
3403 { 4, wxDateTime::Apr
, 2004 },
3406 { 28, wxDateTime::Oct
, 1990 },
3407 { 27, wxDateTime::Oct
, 1991 },
3408 { 25, wxDateTime::Oct
, 1992 },
3409 { 31, wxDateTime::Oct
, 1993 },
3410 { 30, wxDateTime::Oct
, 1994 },
3411 { 29, wxDateTime::Oct
, 1995 },
3412 { 27, wxDateTime::Oct
, 1996 },
3413 { 26, wxDateTime::Oct
, 1997 },
3414 { 25, wxDateTime::Oct
, 1998 },
3415 { 31, wxDateTime::Oct
, 1999 },
3416 { 29, wxDateTime::Oct
, 2000 },
3417 { 28, wxDateTime::Oct
, 2001 },
3418 { 27, wxDateTime::Oct
, 2002 },
3419 { 26, wxDateTime::Oct
, 2003 },
3420 { 31, wxDateTime::Oct
, 2004 },
3425 for ( year
= 1990; year
< 2005; year
++ )
3427 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3428 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3430 printf("DST period in the US for year %d: from %s to %s",
3431 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3433 size_t n
= year
- 1990;
3434 const Date
& dBegin
= datesDST
[0][n
];
3435 const Date
& dEnd
= datesDST
[1][n
];
3437 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3443 printf(" (ERROR: should be %s %d to %s %d)\n",
3444 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3445 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3451 for ( year
= 1990; year
< 2005; year
++ )
3453 printf("DST period in Europe for year %d: from %s to %s\n",
3455 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3456 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3460 // test wxDateTime -> text conversion
3461 static void TestTimeFormat()
3463 puts("\n*** wxDateTime formatting test ***");
3465 // some information may be lost during conversion, so store what kind
3466 // of info should we recover after a round trip
3469 CompareNone
, // don't try comparing
3470 CompareBoth
, // dates and times should be identical
3471 CompareDate
, // dates only
3472 CompareTime
// time only
3477 CompareKind compareKind
;
3479 } formatTestFormats
[] =
3481 { CompareBoth
, "---> %c" },
3482 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3483 { CompareBoth
, "Date is %x, time is %X" },
3484 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3485 { CompareNone
, "The day of year: %j, the week of year: %W" },
3486 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3489 static const Date formatTestDates
[] =
3491 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3492 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3494 // this test can't work for other centuries because it uses two digit
3495 // years in formats, so don't even try it
3496 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3497 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3498 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3502 // an extra test (as it doesn't depend on date, don't do it in the loop)
3503 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3505 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3509 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3510 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3512 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3513 printf("%s", s
.c_str());
3515 // what can we recover?
3516 int kind
= formatTestFormats
[n
].compareKind
;
3520 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3523 // converion failed - should it have?
3524 if ( kind
== CompareNone
)
3527 puts(" (ERROR: conversion back failed)");
3531 // should have parsed the entire string
3532 puts(" (ERROR: conversion back stopped too soon)");
3536 bool equal
= FALSE
; // suppress compilaer warning
3544 equal
= dt
.IsSameDate(dt2
);
3548 equal
= dt
.IsSameTime(dt2
);
3554 printf(" (ERROR: got back '%s' instead of '%s')\n",
3555 dt2
.Format().c_str(), dt
.Format().c_str());
3566 // test text -> wxDateTime conversion
3567 static void TestTimeParse()
3569 puts("\n*** wxDateTime parse test ***");
3571 struct ParseTestData
3578 static const ParseTestData parseTestDates
[] =
3580 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3581 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3584 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3586 const char *format
= parseTestDates
[n
].format
;
3588 printf("%s => ", format
);
3591 if ( dt
.ParseRfc822Date(format
) )
3593 printf("%s ", dt
.Format().c_str());
3595 if ( parseTestDates
[n
].good
)
3597 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3604 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3609 puts("(ERROR: bad format)");
3614 printf("bad format (%s)\n",
3615 parseTestDates
[n
].good
? "ERROR" : "ok");
3620 static void TestDateTimeInteractive()
3622 puts("\n*** interactive wxDateTime tests ***");
3628 printf("Enter a date: ");
3629 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3632 // kill the last '\n'
3633 buf
[strlen(buf
) - 1] = 0;
3636 const char *p
= dt
.ParseDate(buf
);
3639 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3645 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3648 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3649 dt
.Format("%b %d, %Y").c_str(),
3651 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3652 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3653 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3656 puts("\n*** done ***");
3659 static void TestTimeMS()
3661 puts("*** testing millisecond-resolution support in wxDateTime ***");
3663 wxDateTime dt1
= wxDateTime::Now(),
3664 dt2
= wxDateTime::UNow();
3666 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3667 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3668 printf("Dummy loop: ");
3669 for ( int i
= 0; i
< 6000; i
++ )
3671 //for ( int j = 0; j < 10; j++ )
3674 s
.Printf("%g", sqrt(i
));
3683 dt2
= wxDateTime::UNow();
3684 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3686 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3688 puts("\n*** done ***");
3691 static void TestTimeArithmetics()
3693 puts("\n*** testing arithmetic operations on wxDateTime ***");
3695 static const struct ArithmData
3697 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3698 : span(sp
), name(nam
) { }
3702 } testArithmData
[] =
3704 ArithmData(wxDateSpan::Day(), "day"),
3705 ArithmData(wxDateSpan::Week(), "week"),
3706 ArithmData(wxDateSpan::Month(), "month"),
3707 ArithmData(wxDateSpan::Year(), "year"),
3708 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3711 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3713 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3715 wxDateSpan span
= testArithmData
[n
].span
;
3719 const char *name
= testArithmData
[n
].name
;
3720 printf("%s + %s = %s, %s - %s = %s\n",
3721 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3722 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3724 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3725 if ( dt1
- span
== dt
)
3731 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3734 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3735 if ( dt2
+ span
== dt
)
3741 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3744 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3745 if ( dt2
+ 2*span
== dt1
)
3751 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3758 static void TestTimeHolidays()
3760 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3762 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3763 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3764 dtEnd
= dtStart
.GetLastMonthDay();
3766 wxDateTimeArray hol
;
3767 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3769 const wxChar
*format
= "%d-%b-%Y (%a)";
3771 printf("All holidays between %s and %s:\n",
3772 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3774 size_t count
= hol
.GetCount();
3775 for ( size_t n
= 0; n
< count
; n
++ )
3777 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3783 static void TestTimeZoneBug()
3785 puts("\n*** testing for DST/timezone bug ***\n");
3787 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3788 for ( int i
= 0; i
< 31; i
++ )
3790 printf("Date %s: week day %s.\n",
3791 date
.Format(_T("%d-%m-%Y")).c_str(),
3792 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3794 date
+= wxDateSpan::Day();
3800 static void TestTimeSpanFormat()
3802 puts("\n*** wxTimeSpan tests ***");
3804 static const char *formats
[] =
3806 _T("(default) %H:%M:%S"),
3807 _T("%E weeks and %D days"),
3808 _T("%l milliseconds"),
3809 _T("(with ms) %H:%M:%S:%l"),
3810 _T("100%% of minutes is %M"), // test "%%"
3811 _T("%D days and %H hours"),
3814 wxTimeSpan
ts1(1, 2, 3, 4),
3816 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3818 printf("ts1 = %s\tts2 = %s\n",
3819 ts1
.Format(formats
[n
]).c_str(),
3820 ts2
.Format(formats
[n
]).c_str());
3828 // test compatibility with the old wxDate/wxTime classes
3829 static void TestTimeCompatibility()
3831 puts("\n*** wxDateTime compatibility test ***");
3833 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3834 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3836 double jdnNow
= wxDateTime::Now().GetJDN();
3837 long jdnMidnight
= (long)(jdnNow
- 0.5);
3838 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3840 jdnMidnight
= wxDate().Set().GetJulianDate();
3841 printf("wxDateTime for today: %s\n",
3842 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3844 int flags
= wxEUROPEAN
;//wxFULL;
3847 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3848 for ( int n
= 0; n
< 7; n
++ )
3850 printf("Previous %s is %s\n",
3851 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3852 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3858 #endif // TEST_DATETIME
3860 // ----------------------------------------------------------------------------
3862 // ----------------------------------------------------------------------------
3866 #include <wx/thread.h>
3868 static size_t gs_counter
= (size_t)-1;
3869 static wxCriticalSection gs_critsect
;
3870 static wxCondition gs_cond
;
3872 class MyJoinableThread
: public wxThread
3875 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3876 { m_n
= n
; Create(); }
3878 // thread execution starts here
3879 virtual ExitCode
Entry();
3885 wxThread::ExitCode
MyJoinableThread::Entry()
3887 unsigned long res
= 1;
3888 for ( size_t n
= 1; n
< m_n
; n
++ )
3892 // it's a loooong calculation :-)
3896 return (ExitCode
)res
;
3899 class MyDetachedThread
: public wxThread
3902 MyDetachedThread(size_t n
, char ch
)
3906 m_cancelled
= FALSE
;
3911 // thread execution starts here
3912 virtual ExitCode
Entry();
3915 virtual void OnExit();
3918 size_t m_n
; // number of characters to write
3919 char m_ch
; // character to write
3921 bool m_cancelled
; // FALSE if we exit normally
3924 wxThread::ExitCode
MyDetachedThread::Entry()
3927 wxCriticalSectionLocker
lock(gs_critsect
);
3928 if ( gs_counter
== (size_t)-1 )
3934 for ( size_t n
= 0; n
< m_n
; n
++ )
3936 if ( TestDestroy() )
3946 wxThread::Sleep(100);
3952 void MyDetachedThread::OnExit()
3954 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3956 wxCriticalSectionLocker
lock(gs_critsect
);
3957 if ( !--gs_counter
&& !m_cancelled
)
3961 void TestDetachedThreads()
3963 puts("\n*** Testing detached threads ***");
3965 static const size_t nThreads
= 3;
3966 MyDetachedThread
*threads
[nThreads
];
3968 for ( n
= 0; n
< nThreads
; n
++ )
3970 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3973 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3974 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3976 for ( n
= 0; n
< nThreads
; n
++ )
3981 // wait until all threads terminate
3987 void TestJoinableThreads()
3989 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3991 // calc 10! in the background
3992 MyJoinableThread
thread(10);
3995 printf("\nThread terminated with exit code %lu.\n",
3996 (unsigned long)thread
.Wait());
3999 void TestThreadSuspend()
4001 puts("\n*** Testing thread suspend/resume functions ***");
4003 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4007 // this is for this demo only, in a real life program we'd use another
4008 // condition variable which would be signaled from wxThread::Entry() to
4009 // tell us that the thread really started running - but here just wait a
4010 // bit and hope that it will be enough (the problem is, of course, that
4011 // the thread might still not run when we call Pause() which will result
4013 wxThread::Sleep(300);
4015 for ( size_t n
= 0; n
< 3; n
++ )
4019 puts("\nThread suspended");
4022 // don't sleep but resume immediately the first time
4023 wxThread::Sleep(300);
4025 puts("Going to resume the thread");
4030 puts("Waiting until it terminates now");
4032 // wait until the thread terminates
4038 void TestThreadDelete()
4040 // As above, using Sleep() is only for testing here - we must use some
4041 // synchronisation object instead to ensure that the thread is still
4042 // running when we delete it - deleting a detached thread which already
4043 // terminated will lead to a crash!
4045 puts("\n*** Testing thread delete function ***");
4047 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4051 puts("\nDeleted a thread which didn't start to run yet.");
4053 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4057 wxThread::Sleep(300);
4061 puts("\nDeleted a running thread.");
4063 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4067 wxThread::Sleep(300);
4073 puts("\nDeleted a sleeping thread.");
4075 MyJoinableThread
thread3(20);
4080 puts("\nDeleted a joinable thread.");
4082 MyJoinableThread
thread4(2);
4085 wxThread::Sleep(300);
4089 puts("\nDeleted a joinable thread which already terminated.");
4094 #endif // TEST_THREADS
4096 // ----------------------------------------------------------------------------
4098 // ----------------------------------------------------------------------------
4102 static void PrintArray(const char* name
, const wxArrayString
& array
)
4104 printf("Dump of the array '%s'\n", name
);
4106 size_t nCount
= array
.GetCount();
4107 for ( size_t n
= 0; n
< nCount
; n
++ )
4109 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4113 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4115 printf("Dump of the array '%s'\n", name
);
4117 size_t nCount
= array
.GetCount();
4118 for ( size_t n
= 0; n
< nCount
; n
++ )
4120 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4124 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4125 const wxString
& second
)
4127 return first
.length() - second
.length();
4130 int wxCMPFUNC_CONV
IntCompare(int *first
,
4133 return *first
- *second
;
4136 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4139 return *second
- *first
;
4142 static void TestArrayOfInts()
4144 puts("*** Testing wxArrayInt ***\n");
4155 puts("After sort:");
4159 puts("After reverse sort:");
4160 a
.Sort(IntRevCompare
);
4164 #include "wx/dynarray.h"
4166 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4167 #include "wx/arrimpl.cpp"
4168 WX_DEFINE_OBJARRAY(ArrayBars
);
4170 static void TestArrayOfObjects()
4172 puts("*** Testing wxObjArray ***\n");
4176 Bar
bar("second bar");
4178 printf("Initially: %u objects in the array, %u objects total.\n",
4179 bars
.GetCount(), Bar::GetNumber());
4181 bars
.Add(new Bar("first bar"));
4184 printf("Now: %u objects in the array, %u objects total.\n",
4185 bars
.GetCount(), Bar::GetNumber());
4189 printf("After Empty(): %u objects in the array, %u objects total.\n",
4190 bars
.GetCount(), Bar::GetNumber());
4193 printf("Finally: no more objects in the array, %u objects total.\n",
4197 #endif // TEST_ARRAYS
4199 // ----------------------------------------------------------------------------
4201 // ----------------------------------------------------------------------------
4205 #include "wx/timer.h"
4206 #include "wx/tokenzr.h"
4208 static void TestStringConstruction()
4210 puts("*** Testing wxString constructores ***");
4212 #define TEST_CTOR(args, res) \
4215 printf("wxString%s = %s ", #args, s.c_str()); \
4222 printf("(ERROR: should be %s)\n", res); \
4226 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4227 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4228 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4229 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4231 static const wxChar
*s
= _T("?really!");
4232 const wxChar
*start
= wxStrchr(s
, _T('r'));
4233 const wxChar
*end
= wxStrchr(s
, _T('!'));
4234 TEST_CTOR((start
, end
), _T("really"));
4239 static void TestString()
4249 for (int i
= 0; i
< 1000000; ++i
)
4253 c
= "! How'ya doin'?";
4256 c
= "Hello world! What's up?";
4261 printf ("TestString elapsed time: %ld\n", sw
.Time());
4264 static void TestPChar()
4272 for (int i
= 0; i
< 1000000; ++i
)
4274 strcpy (a
, "Hello");
4275 strcpy (b
, " world");
4276 strcpy (c
, "! How'ya doin'?");
4279 strcpy (c
, "Hello world! What's up?");
4280 if (strcmp (c
, a
) == 0)
4284 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4287 static void TestStringSub()
4289 wxString
s("Hello, world!");
4291 puts("*** Testing wxString substring extraction ***");
4293 printf("String = '%s'\n", s
.c_str());
4294 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4295 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4296 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4297 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4298 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4299 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4301 static const wxChar
*prefixes
[] =
4305 _T("Hello, world!"),
4306 _T("Hello, world!!!"),
4312 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4314 wxString prefix
= prefixes
[n
], rest
;
4315 bool rc
= s
.StartsWith(prefix
, &rest
);
4316 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4319 printf(" (the rest is '%s')\n", rest
.c_str());
4330 static void TestStringFormat()
4332 puts("*** Testing wxString formatting ***");
4335 s
.Printf("%03d", 18);
4337 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4338 printf("Number 18: %s\n", s
.c_str());
4343 // returns "not found" for npos, value for all others
4344 static wxString
PosToString(size_t res
)
4346 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4347 : wxString::Format(_T("%u"), res
);
4351 static void TestStringFind()
4353 puts("*** Testing wxString find() functions ***");
4355 static const wxChar
*strToFind
= _T("ell");
4356 static const struct StringFindTest
4360 result
; // of searching "ell" in str
4363 { _T("Well, hello world"), 0, 1 },
4364 { _T("Well, hello world"), 6, 7 },
4365 { _T("Well, hello world"), 9, wxString::npos
},
4368 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4370 const StringFindTest
& ft
= findTestData
[n
];
4371 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4373 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4374 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4376 size_t resTrue
= ft
.result
;
4377 if ( res
== resTrue
)
4383 printf(_T("(ERROR: should be %s)\n"),
4384 PosToString(resTrue
).c_str());
4391 static void TestStringTokenizer()
4393 puts("*** Testing wxStringTokenizer ***");
4395 static const wxChar
*modeNames
[] =
4399 _T("return all empty"),
4404 static const struct StringTokenizerTest
4406 const wxChar
*str
; // string to tokenize
4407 const wxChar
*delims
; // delimiters to use
4408 size_t count
; // count of token
4409 wxStringTokenizerMode mode
; // how should we tokenize it
4410 } tokenizerTestData
[] =
4412 { _T(""), _T(" "), 0 },
4413 { _T("Hello, world"), _T(" "), 2 },
4414 { _T("Hello, world "), _T(" "), 2 },
4415 { _T("Hello, world"), _T(","), 2 },
4416 { _T("Hello, world!"), _T(",!"), 2 },
4417 { _T("Hello,, world!"), _T(",!"), 3 },
4418 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4419 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4420 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4421 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4422 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4423 { _T("01/02/99"), _T("/-"), 3 },
4424 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4427 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4429 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4430 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4432 size_t count
= tkz
.CountTokens();
4433 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4434 MakePrintable(tt
.str
).c_str(),
4436 MakePrintable(tt
.delims
).c_str(),
4437 modeNames
[tkz
.GetMode()]);
4438 if ( count
== tt
.count
)
4444 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4449 // if we emulate strtok(), check that we do it correctly
4450 wxChar
*buf
, *s
= NULL
, *last
;
4452 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4454 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4455 wxStrcpy(buf
, tt
.str
);
4457 s
= wxStrtok(buf
, tt
.delims
, &last
);
4464 // now show the tokens themselves
4466 while ( tkz
.HasMoreTokens() )
4468 wxString token
= tkz
.GetNextToken();
4470 printf(_T("\ttoken %u: '%s'"),
4472 MakePrintable(token
).c_str());
4482 printf(" (ERROR: should be %s)\n", s
);
4485 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4489 // nothing to compare with
4494 if ( count2
!= count
)
4496 puts(_T("\tERROR: token count mismatch"));
4505 static void TestStringReplace()
4507 puts("*** Testing wxString::replace ***");
4509 static const struct StringReplaceTestData
4511 const wxChar
*original
; // original test string
4512 size_t start
, len
; // the part to replace
4513 const wxChar
*replacement
; // the replacement string
4514 const wxChar
*result
; // and the expected result
4515 } stringReplaceTestData
[] =
4517 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4518 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4519 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4520 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4521 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4524 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4526 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4528 wxString original
= data
.original
;
4529 original
.replace(data
.start
, data
.len
, data
.replacement
);
4531 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4532 data
.original
, data
.start
, data
.len
, data
.replacement
,
4535 if ( original
== data
.result
)
4541 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4548 #endif // TEST_STRINGS
4550 // ----------------------------------------------------------------------------
4552 // ----------------------------------------------------------------------------
4554 int main(int argc
, char **argv
)
4556 wxInitializer initializer
;
4559 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4564 #ifdef TEST_SNGLINST
4565 wxSingleInstanceChecker
checker(_T(".wxconsole.lock"));
4566 if ( checker
.IsAnotherRunning() )
4568 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4573 // wait some time to give time to launch another instance
4574 wxPrintf(_T("Press \"Enter\" to continue..."));
4576 #endif // TEST_SNGLINST
4580 #endif // TEST_CHARSET
4583 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4585 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4586 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4588 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4589 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4590 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4591 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4593 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4594 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4599 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4601 parser
.AddOption("project_name", "", "full path to project file",
4602 wxCMD_LINE_VAL_STRING
,
4603 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4605 switch ( parser
.Parse() )
4608 wxLogMessage("Help was given, terminating.");
4612 ShowCmdLine(parser
);
4616 wxLogMessage("Syntax error detected, aborting.");
4619 #endif // TEST_CMDLINE
4630 TestStringConstruction();
4633 TestStringTokenizer();
4634 TestStringReplace();
4636 #endif // TEST_STRINGS
4649 puts("*** Initially:");
4651 PrintArray("a1", a1
);
4653 wxArrayString
a2(a1
);
4654 PrintArray("a2", a2
);
4656 wxSortedArrayString
a3(a1
);
4657 PrintArray("a3", a3
);
4659 puts("*** After deleting a string from a1");
4662 PrintArray("a1", a1
);
4663 PrintArray("a2", a2
);
4664 PrintArray("a3", a3
);
4666 puts("*** After reassigning a1 to a2 and a3");
4668 PrintArray("a2", a2
);
4669 PrintArray("a3", a3
);
4671 puts("*** After sorting a1");
4673 PrintArray("a1", a1
);
4675 puts("*** After sorting a1 in reverse order");
4677 PrintArray("a1", a1
);
4679 puts("*** After sorting a1 by the string length");
4680 a1
.Sort(StringLenCompare
);
4681 PrintArray("a1", a1
);
4683 TestArrayOfObjects();
4686 #endif // TEST_ARRAYS
4694 #ifdef TEST_DLLLOADER
4696 #endif // TEST_DLLLOADER
4700 #endif // TEST_ENVIRON
4704 #endif // TEST_EXECUTE
4706 #ifdef TEST_FILECONF
4708 #endif // TEST_FILECONF
4716 #endif // TEST_LOCALE
4720 for ( size_t n
= 0; n
< 8000; n
++ )
4722 s
<< (char)('A' + (n
% 26));
4726 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4728 // this one shouldn't be truncated
4731 // but this one will because log functions use fixed size buffer
4732 // (note that it doesn't need '\n' at the end neither - will be added
4734 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4746 #ifdef TEST_FILENAME
4747 TestFileNameSplit();
4750 TestFileNameConstruction();
4752 TestFileNameComparison();
4753 TestFileNameOperations();
4755 #endif // TEST_FILENAME
4758 int nCPUs
= wxThread::GetCPUCount();
4759 printf("This system has %d CPUs\n", nCPUs
);
4761 wxThread::SetConcurrency(nCPUs
);
4763 if ( argc
> 1 && argv
[1][0] == 't' )
4764 wxLog::AddTraceMask("thread");
4767 TestDetachedThreads();
4769 TestJoinableThreads();
4771 TestThreadSuspend();
4775 #endif // TEST_THREADS
4777 #ifdef TEST_LONGLONG
4778 // seed pseudo random generator
4779 srand((unsigned)time(NULL
));
4787 TestMultiplication();
4790 TestLongLongConversion();
4791 TestBitOperations();
4793 TestLongLongComparison();
4794 #endif // TEST_LONGLONG
4801 wxLog::AddTraceMask(_T("mime"));
4809 TestMimeAssociate();
4812 #ifdef TEST_INFO_FUNCTIONS
4815 #endif // TEST_INFO_FUNCTIONS
4817 #ifdef TEST_PATHLIST
4819 #endif // TEST_PATHLIST
4823 #endif // TEST_REGCONF
4825 #ifdef TEST_REGISTRY
4828 TestRegistryAssociation();
4829 #endif // TEST_REGISTRY
4837 #endif // TEST_SOCKETS
4840 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4841 if ( TestFtpConnect() )
4852 TestFtpInteractive();
4854 //else: connecting to the FTP server failed
4864 #endif // TEST_STREAMS
4868 #endif // TEST_TIMER
4870 #ifdef TEST_DATETIME
4883 TestTimeArithmetics();
4890 TestTimeSpanFormat();
4892 TestDateTimeInteractive();
4893 #endif // TEST_DATETIME
4896 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4898 #endif // TEST_USLEEP
4904 #endif // TEST_VCARD
4908 #endif // TEST_WCHAR
4912 TestZipStreamRead();
4913 TestZipFileSystem();
4918 TestZlibStreamWrite();
4919 TestZlibStreamRead();