1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
22 #include <wx/string.h>
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
36 // what to test (in alphabetic order)?
39 //#define TEST_CHARSET
40 //#define TEST_CMDLINE
41 //#define TEST_DATETIME
43 //#define TEST_DLLLOADER
44 //#define TEST_ENVIRON
45 //#define TEST_EXECUTE
47 //#define TEST_FILECONF
48 //#define TEST_FILENAME
51 //#define TEST_INFO_FUNCTIONS
55 //#define TEST_LONGLONG
57 //#define TEST_PATHLIST
58 //#define TEST_REGCONF
59 //#define TEST_REGISTRY
60 //#define TEST_SOCKETS
61 //#define TEST_STREAMS
62 //#define TEST_STRINGS
63 //#define TEST_THREADS
65 //#define TEST_VCARD -- don't enable this (VZ)
70 // ----------------------------------------------------------------------------
71 // test class for container objects
72 // ----------------------------------------------------------------------------
74 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
76 class Bar
// Foo is already taken in the hash test
79 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
82 static size_t GetNumber() { return ms_bars
; }
84 const char *GetName() const { return m_name
; }
89 static size_t ms_bars
;
92 size_t Bar::ms_bars
= 0;
94 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
96 // ============================================================================
98 // ============================================================================
100 // ----------------------------------------------------------------------------
102 // ----------------------------------------------------------------------------
104 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
106 // replace TABs with \t and CRs with \n
107 static wxString
MakePrintable(const wxChar
*s
)
110 (void)str
.Replace(_T("\t"), _T("\\t"));
111 (void)str
.Replace(_T("\n"), _T("\\n"));
112 (void)str
.Replace(_T("\r"), _T("\\r"));
117 #endif // MakePrintable() is used
119 // ----------------------------------------------------------------------------
120 // wxFontMapper::CharsetToEncoding
121 // ----------------------------------------------------------------------------
125 #include <wx/fontmap.h>
127 static void TestCharset()
129 static const wxChar
*charsets
[] =
131 // some vali charsets
140 // and now some bogus ones
147 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
149 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
150 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
152 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
153 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
157 #endif // TEST_CHARSET
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
165 #include <wx/cmdline.h>
166 #include <wx/datetime.h>
168 static void ShowCmdLine(const wxCmdLineParser
& parser
)
170 wxString s
= "Input files: ";
172 size_t count
= parser
.GetParamCount();
173 for ( size_t param
= 0; param
< count
; param
++ )
175 s
<< parser
.GetParam(param
) << ' ';
179 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
180 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
185 if ( parser
.Found("o", &strVal
) )
186 s
<< "Output file:\t" << strVal
<< '\n';
187 if ( parser
.Found("i", &strVal
) )
188 s
<< "Input dir:\t" << strVal
<< '\n';
189 if ( parser
.Found("s", &lVal
) )
190 s
<< "Size:\t" << lVal
<< '\n';
191 if ( parser
.Found("d", &dt
) )
192 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
193 if ( parser
.Found("project_name", &strVal
) )
194 s
<< "Project:\t" << strVal
<< '\n';
199 #endif // TEST_CMDLINE
201 // ----------------------------------------------------------------------------
203 // ----------------------------------------------------------------------------
210 static const wxChar
*ROOTDIR
= _T("/");
211 static const wxChar
*TESTDIR
= _T("/usr");
212 #elif defined(__WXMSW__)
213 static const wxChar
*ROOTDIR
= _T("c:\\");
214 static const wxChar
*TESTDIR
= _T("d:\\");
216 #error "don't know where the root directory is"
219 static void TestDirEnumHelper(wxDir
& dir
,
220 int flags
= wxDIR_DEFAULT
,
221 const wxString
& filespec
= wxEmptyString
)
225 if ( !dir
.IsOpened() )
228 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
231 printf("\t%s\n", filename
.c_str());
233 cont
= dir
.GetNext(&filename
);
239 static void TestDirEnum()
241 puts("*** Testing wxDir::GetFirst/GetNext ***");
243 wxDir
dir(wxGetCwd());
245 puts("Enumerating everything in current directory:");
246 TestDirEnumHelper(dir
);
248 puts("Enumerating really everything in current directory:");
249 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
251 puts("Enumerating object files in current directory:");
252 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
254 puts("Enumerating directories in current directory:");
255 TestDirEnumHelper(dir
, wxDIR_DIRS
);
257 puts("Enumerating files in current directory:");
258 TestDirEnumHelper(dir
, wxDIR_FILES
);
260 puts("Enumerating files including hidden in current directory:");
261 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
265 puts("Enumerating everything in root directory:");
266 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
268 puts("Enumerating directories in root directory:");
269 TestDirEnumHelper(dir
, wxDIR_DIRS
);
271 puts("Enumerating files in root directory:");
272 TestDirEnumHelper(dir
, wxDIR_FILES
);
274 puts("Enumerating files including hidden in root directory:");
275 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
277 puts("Enumerating files in non existing directory:");
278 wxDir
dirNo("nosuchdir");
279 TestDirEnumHelper(dirNo
);
282 class DirPrintTraverser
: public wxDirTraverser
285 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
287 return wxDIR_CONTINUE
;
290 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
292 wxString path
, name
, ext
;
293 wxSplitPath(dirname
, &path
, &name
, &ext
);
296 name
<< _T('.') << ext
;
299 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
301 if ( wxIsPathSeparator(*p
) )
305 printf("%s%s\n", indent
.c_str(), name
.c_str());
307 return wxDIR_CONTINUE
;
311 static void TestDirTraverse()
313 puts("*** Testing wxDir::Traverse() ***");
317 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
318 printf("There are %u files under '%s'\n", n
, TESTDIR
);
321 printf("First one is '%s'\n", files
[0u]);
322 printf(" last one is '%s'\n", files
[n
- 1]);
325 // enum again with custom traverser
327 DirPrintTraverser traverser
;
328 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
333 // ----------------------------------------------------------------------------
335 // ----------------------------------------------------------------------------
337 #ifdef TEST_DLLLOADER
339 #include <wx/dynlib.h>
341 static void TestDllLoad()
343 #if defined(__WXMSW__)
344 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
345 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
346 #elif defined(__UNIX__)
347 // weird: using just libc.so does *not* work!
348 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
349 static const wxChar
*FUNC_NAME
= _T("strlen");
351 #error "don't know how to test wxDllLoader on this platform"
354 puts("*** testing wxDllLoader ***\n");
356 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
359 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
363 typedef int (*strlenType
)(char *);
364 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
367 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
368 FUNC_NAME
, LIB_NAME
);
372 if ( pfnStrlen("foo") != 3 )
374 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
382 wxDllLoader::UnloadLibrary(dllHandle
);
386 #endif // TEST_DLLLOADER
388 // ----------------------------------------------------------------------------
390 // ----------------------------------------------------------------------------
394 #include <wx/utils.h>
396 static wxString
MyGetEnv(const wxString
& var
)
399 if ( !wxGetEnv(var
, &val
) )
402 val
= wxString(_T('\'')) + val
+ _T('\'');
407 static void TestEnvironment()
409 const wxChar
*var
= _T("wxTestVar");
411 puts("*** testing environment access functions ***");
413 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
414 wxSetEnv(var
, _T("value for wxTestVar"));
415 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
416 wxSetEnv(var
, _T("another value"));
417 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
419 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
420 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
423 #endif // TEST_ENVIRON
425 // ----------------------------------------------------------------------------
427 // ----------------------------------------------------------------------------
431 #include <wx/utils.h>
433 static void TestExecute()
435 puts("*** testing wxExecute ***");
438 #define COMMAND "cat -n ../../Makefile" // "echo hi"
439 #define SHELL_COMMAND "echo hi from shell"
440 #define REDIRECT_COMMAND COMMAND // "date"
441 #elif defined(__WXMSW__)
442 #define COMMAND "command.com -c 'echo hi'"
443 #define SHELL_COMMAND "echo hi"
444 #define REDIRECT_COMMAND COMMAND
446 #error "no command to exec"
449 printf("Testing wxShell: ");
451 if ( wxShell(SHELL_COMMAND
) )
456 printf("Testing wxExecute: ");
458 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
463 #if 0 // no, it doesn't work (yet?)
464 printf("Testing async wxExecute: ");
466 if ( wxExecute(COMMAND
) != 0 )
467 puts("Ok (command launched).");
472 printf("Testing wxExecute with redirection:\n");
473 wxArrayString output
;
474 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
480 size_t count
= output
.GetCount();
481 for ( size_t n
= 0; n
< count
; n
++ )
483 printf("\t%s\n", output
[n
].c_str());
490 #endif // TEST_EXECUTE
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
499 #include <wx/ffile.h>
500 #include <wx/textfile.h>
502 static void TestFileRead()
504 puts("*** wxFile read test ***");
506 wxFile
file(_T("testdata.fc"));
507 if ( file
.IsOpened() )
509 printf("File length: %lu\n", file
.Length());
511 puts("File dump:\n----------");
513 static const off_t len
= 1024;
517 off_t nRead
= file
.Read(buf
, len
);
518 if ( nRead
== wxInvalidOffset
)
520 printf("Failed to read the file.");
524 fwrite(buf
, nRead
, 1, stdout
);
534 printf("ERROR: can't open test file.\n");
540 static void TestTextFileRead()
542 puts("*** wxTextFile read test ***");
544 wxTextFile
file(_T("testdata.fc"));
547 printf("Number of lines: %u\n", file
.GetLineCount());
548 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
552 puts("\nDumping the entire file:");
553 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
555 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
557 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
559 puts("\nAnd now backwards:");
560 for ( s
= file
.GetLastLine();
561 file
.GetCurrentLine() != 0;
562 s
= file
.GetPrevLine() )
564 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
566 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
570 printf("ERROR: can't open '%s'\n", file
.GetName());
576 static void TestFileCopy()
578 puts("*** Testing wxCopyFile ***");
580 static const wxChar
*filename1
= _T("testdata.fc");
581 static const wxChar
*filename2
= _T("test2");
582 if ( !wxCopyFile(filename1
, filename2
) )
584 puts("ERROR: failed to copy file");
588 wxFFile
f1(filename1
, "rb"),
591 if ( !f1
.IsOpened() || !f2
.IsOpened() )
593 puts("ERROR: failed to open file(s)");
598 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
600 puts("ERROR: failed to read file(s)");
604 if ( (s1
.length() != s2
.length()) ||
605 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
607 puts("ERROR: copy error!");
611 puts("File was copied ok.");
617 if ( !wxRemoveFile(filename2
) )
619 puts("ERROR: failed to remove the file");
627 // ----------------------------------------------------------------------------
629 // ----------------------------------------------------------------------------
633 #include <wx/confbase.h>
634 #include <wx/fileconf.h>
636 static const struct FileConfTestData
638 const wxChar
*name
; // value name
639 const wxChar
*value
; // the value from the file
642 { _T("value1"), _T("one") },
643 { _T("value2"), _T("two") },
644 { _T("novalue"), _T("default") },
647 static void TestFileConfRead()
649 puts("*** testing wxFileConfig loading/reading ***");
651 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
652 _T("testdata.fc"), wxEmptyString
,
653 wxCONFIG_USE_RELATIVE_PATH
);
655 // test simple reading
656 puts("\nReading config file:");
657 wxString
defValue(_T("default")), value
;
658 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
660 const FileConfTestData
& data
= fcTestData
[n
];
661 value
= fileconf
.Read(data
.name
, defValue
);
662 printf("\t%s = %s ", data
.name
, value
.c_str());
663 if ( value
== data
.value
)
669 printf("(ERROR: should be %s)\n", data
.value
);
673 // test enumerating the entries
674 puts("\nEnumerating all root entries:");
677 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
680 printf("\t%s = %s\n",
682 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
684 cont
= fileconf
.GetNextEntry(name
, dummy
);
688 #endif // TEST_FILECONF
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
696 #include <wx/filename.h>
698 static struct FileNameInfo
700 const wxChar
*fullname
;
706 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
707 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
708 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
709 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
710 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
711 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
712 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
713 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
716 static void TestFileNameConstruction()
718 puts("*** testing wxFileName construction ***");
720 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
722 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
724 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
725 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
727 puts("ERROR (couldn't be normalized)");
731 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
738 static void TestFileNameSplit()
740 puts("*** testing wxFileName splitting ***");
742 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
744 const FileNameInfo
&fni
= filenames
[n
];
745 wxString path
, name
, ext
;
746 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
748 printf("%s -> path = '%s', name = '%s', ext = '%s'",
749 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
750 if ( path
!= fni
.path
)
751 printf(" (ERROR: path = '%s')", fni
.path
);
752 if ( name
!= fni
.name
)
753 printf(" (ERROR: name = '%s')", fni
.name
);
754 if ( ext
!= fni
.ext
)
755 printf(" (ERROR: ext = '%s')", fni
.ext
);
762 static void TestFileNameComparison()
767 static void TestFileNameOperations()
772 static void TestFileNameCwd()
777 #endif // TEST_FILENAME
779 // ----------------------------------------------------------------------------
781 // ----------------------------------------------------------------------------
789 Foo(int n_
) { n
= n_
; count
++; }
797 size_t Foo::count
= 0;
799 WX_DECLARE_LIST(Foo
, wxListFoos
);
800 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
802 #include <wx/listimpl.cpp>
804 WX_DEFINE_LIST(wxListFoos
);
806 static void TestHash()
808 puts("*** Testing wxHashTable ***\n");
812 hash
.DeleteContents(TRUE
);
814 printf("Hash created: %u foos in hash, %u foos totally\n",
815 hash
.GetCount(), Foo::count
);
817 static const int hashTestData
[] =
819 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
823 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
825 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
828 printf("Hash filled: %u foos in hash, %u foos totally\n",
829 hash
.GetCount(), Foo::count
);
831 puts("Hash access test:");
832 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
834 printf("\tGetting element with key %d, value %d: ",
836 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
839 printf("ERROR, not found.\n");
843 printf("%d (%s)\n", foo
->n
,
844 (size_t)foo
->n
== n
? "ok" : "ERROR");
848 printf("\nTrying to get an element not in hash: ");
850 if ( hash
.Get(1234) || hash
.Get(1, 0) )
852 puts("ERROR: found!");
856 puts("ok (not found)");
860 printf("Hash destroyed: %u foos left\n", Foo::count
);
865 // ----------------------------------------------------------------------------
867 // ----------------------------------------------------------------------------
873 WX_DECLARE_LIST(Bar
, wxListBars
);
874 #include <wx/listimpl.cpp>
875 WX_DEFINE_LIST(wxListBars
);
877 static void TestListCtor()
879 puts("*** Testing wxList construction ***\n");
883 list1
.Append(new Bar(_T("first")));
884 list1
.Append(new Bar(_T("second")));
886 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
887 list1
.GetCount(), Bar::GetNumber());
892 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
893 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
895 list1
.DeleteContents(TRUE
);
898 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
903 // ----------------------------------------------------------------------------
905 // ----------------------------------------------------------------------------
910 #include "wx/utils.h" // for wxSetEnv
912 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
914 // find the name of the language from its value
915 static const char *GetLangName(int lang
)
917 static const char *languageNames
[] =
938 "ARABIC_SAUDI_ARABIA",
963 "CHINESE_SIMPLIFIED",
964 "CHINESE_TRADITIONAL",
986 "ENGLISH_NEW_ZEALAND",
987 "ENGLISH_PHILIPPINES",
988 "ENGLISH_SOUTH_AFRICA",
1000 "FRENCH_LUXEMBOURG",
1009 "GERMAN_LIECHTENSTEIN",
1010 "GERMAN_LUXEMBOURG",
1051 "MALAY_BRUNEI_DARUSSALAM",
1063 "NORWEGIAN_NYNORSK",
1070 "PORTUGUESE_BRAZILIAN",
1095 "SPANISH_ARGENTINA",
1099 "SPANISH_COSTA_RICA",
1100 "SPANISH_DOMINICAN_REPUBLIC",
1102 "SPANISH_EL_SALVADOR",
1103 "SPANISH_GUATEMALA",
1107 "SPANISH_NICARAGUA",
1111 "SPANISH_PUERTO_RICO",
1114 "SPANISH_VENEZUELA",
1151 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1152 return languageNames
[lang
];
1157 static void TestDefaultLang()
1159 puts("*** Testing wxLocale::GetSystemLanguage ***");
1161 static const wxChar
*langStrings
[] =
1163 NULL
, // system default
1170 _T("de_DE.iso88591"),
1172 _T("?"), // invalid lang spec
1173 _T("klingonese"), // I bet on some systems it does exist...
1176 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1178 const char *langStr
= langStrings
[n
];
1180 wxSetEnv(_T("LC_ALL"), langStr
);
1182 int lang
= gs_localeDefault
.GetSystemLanguage();
1183 printf("Locale for '%s' is %s.\n",
1184 langStr
? langStr
: "system default", GetLangName(lang
));
1188 #endif // TEST_LOCALE
1190 // ----------------------------------------------------------------------------
1192 // ----------------------------------------------------------------------------
1196 #include <wx/mimetype.h>
1198 static void TestMimeEnum()
1200 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1202 wxArrayString mimetypes
;
1204 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1206 printf("*** All %u known filetypes: ***\n", count
);
1211 for ( size_t n
= 0; n
< count
; n
++ )
1213 wxFileType
*filetype
=
1214 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1217 printf("nothing known about the filetype '%s'!\n",
1218 mimetypes
[n
].c_str());
1222 filetype
->GetDescription(&desc
);
1223 filetype
->GetExtensions(exts
);
1225 filetype
->GetIcon(NULL
);
1228 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1231 extsAll
<< _T(", ");
1235 printf("\t%s: %s (%s)\n",
1236 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1242 static void TestMimeOverride()
1244 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1246 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1247 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1249 if ( wxFile::Exists(mailcap
) )
1250 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1252 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1254 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1257 if ( wxFile::Exists(mimetypes
) )
1258 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1260 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1262 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1268 static void TestMimeFilename()
1270 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1272 static const wxChar
*filenames
[] =
1279 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1281 const wxString fname
= filenames
[n
];
1282 wxString ext
= fname
.AfterLast(_T('.'));
1283 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1286 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1291 if ( !ft
->GetDescription(&desc
) )
1292 desc
= _T("<no description>");
1295 if ( !ft
->GetOpenCommand(&cmd
,
1296 wxFileType::MessageParameters(fname
, _T(""))) )
1297 cmd
= _T("<no command available>");
1299 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1300 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1309 static void TestMimeAssociate()
1311 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1313 wxFileTypeInfo
ftInfo(
1314 _T("application/x-xyz"),
1315 _T("xyzview '%s'"), // open cmd
1316 _T(""), // print cmd
1317 _T("XYZ File") // description
1318 _T(".xyz"), // extensions
1319 NULL
// end of extensions
1321 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1323 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1326 wxPuts(_T("ERROR: failed to create association!"));
1330 // TODO: read it back
1339 // ----------------------------------------------------------------------------
1340 // misc information functions
1341 // ----------------------------------------------------------------------------
1343 #ifdef TEST_INFO_FUNCTIONS
1345 #include <wx/utils.h>
1347 static void TestOsInfo()
1349 puts("*** Testing OS info functions ***\n");
1352 wxGetOsVersion(&major
, &minor
);
1353 printf("Running under: %s, version %d.%d\n",
1354 wxGetOsDescription().c_str(), major
, minor
);
1356 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1358 printf("Host name is %s (%s).\n",
1359 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1364 static void TestUserInfo()
1366 puts("*** Testing user info functions ***\n");
1368 printf("User id is:\t%s\n", wxGetUserId().c_str());
1369 printf("User name is:\t%s\n", wxGetUserName().c_str());
1370 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1371 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1376 #endif // TEST_INFO_FUNCTIONS
1378 // ----------------------------------------------------------------------------
1380 // ----------------------------------------------------------------------------
1382 #ifdef TEST_LONGLONG
1384 #include <wx/longlong.h>
1385 #include <wx/timer.h>
1387 // make a 64 bit number from 4 16 bit ones
1388 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1390 // get a random 64 bit number
1391 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1393 #if wxUSE_LONGLONG_WX
1394 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1395 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1396 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1397 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1398 #endif // wxUSE_LONGLONG_WX
1400 static void TestSpeed()
1402 static const long max
= 100000000;
1409 for ( n
= 0; n
< max
; n
++ )
1414 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1417 #if wxUSE_LONGLONG_NATIVE
1422 for ( n
= 0; n
< max
; n
++ )
1427 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1429 #endif // wxUSE_LONGLONG_NATIVE
1435 for ( n
= 0; n
< max
; n
++ )
1440 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1444 static void TestLongLongConversion()
1446 puts("*** Testing wxLongLong conversions ***\n");
1450 for ( size_t n
= 0; n
< 100000; n
++ )
1454 #if wxUSE_LONGLONG_NATIVE
1455 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1457 wxASSERT_MSG( a
== b
, "conversions failure" );
1459 puts("Can't do it without native long long type, test skipped.");
1462 #endif // wxUSE_LONGLONG_NATIVE
1464 if ( !(nTested
% 1000) )
1476 static void TestMultiplication()
1478 puts("*** Testing wxLongLong multiplication ***\n");
1482 for ( size_t n
= 0; n
< 100000; n
++ )
1487 #if wxUSE_LONGLONG_NATIVE
1488 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1489 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1491 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1492 #else // !wxUSE_LONGLONG_NATIVE
1493 puts("Can't do it without native long long type, test skipped.");
1496 #endif // wxUSE_LONGLONG_NATIVE
1498 if ( !(nTested
% 1000) )
1510 static void TestDivision()
1512 puts("*** Testing wxLongLong division ***\n");
1516 for ( size_t n
= 0; n
< 100000; n
++ )
1518 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1519 // multiplication will not overflow)
1520 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1522 // get a random long (not wxLongLong for now) to divide it with
1527 #if wxUSE_LONGLONG_NATIVE
1528 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1530 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1531 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1532 #else // !wxUSE_LONGLONG_NATIVE
1533 // verify the result
1534 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1535 #endif // wxUSE_LONGLONG_NATIVE
1537 if ( !(nTested
% 1000) )
1549 static void TestAddition()
1551 puts("*** Testing wxLongLong addition ***\n");
1555 for ( size_t n
= 0; n
< 100000; n
++ )
1561 #if wxUSE_LONGLONG_NATIVE
1562 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1563 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1564 "addition failure" );
1565 #else // !wxUSE_LONGLONG_NATIVE
1566 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1567 #endif // wxUSE_LONGLONG_NATIVE
1569 if ( !(nTested
% 1000) )
1581 static void TestBitOperations()
1583 puts("*** Testing wxLongLong bit operation ***\n");
1587 for ( size_t n
= 0; n
< 100000; n
++ )
1591 #if wxUSE_LONGLONG_NATIVE
1592 for ( size_t n
= 0; n
< 33; n
++ )
1595 #else // !wxUSE_LONGLONG_NATIVE
1596 puts("Can't do it without native long long type, test skipped.");
1599 #endif // wxUSE_LONGLONG_NATIVE
1601 if ( !(nTested
% 1000) )
1613 static void TestLongLongComparison()
1615 puts("*** Testing wxLongLong comparison ***\n");
1617 static const long testLongs
[] =
1628 static const long ls
[2] =
1634 wxLongLongWx lls
[2];
1638 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1642 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1644 res
= lls
[m
] > testLongs
[n
];
1645 printf("0x%lx > 0x%lx is %s (%s)\n",
1646 ls
[m
], testLongs
[n
], res
? "true" : "false",
1647 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1649 res
= lls
[m
] < testLongs
[n
];
1650 printf("0x%lx < 0x%lx is %s (%s)\n",
1651 ls
[m
], testLongs
[n
], res
? "true" : "false",
1652 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1654 res
= lls
[m
] == testLongs
[n
];
1655 printf("0x%lx == 0x%lx is %s (%s)\n",
1656 ls
[m
], testLongs
[n
], res
? "true" : "false",
1657 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1665 #endif // TEST_LONGLONG
1667 // ----------------------------------------------------------------------------
1669 // ----------------------------------------------------------------------------
1671 #ifdef TEST_PATHLIST
1673 static void TestPathList()
1675 puts("*** Testing wxPathList ***\n");
1677 wxPathList pathlist
;
1678 pathlist
.AddEnvList("PATH");
1679 wxString path
= pathlist
.FindValidPath("ls");
1682 printf("ERROR: command not found in the path.\n");
1686 printf("Command found in the path as '%s'.\n", path
.c_str());
1690 #endif // TEST_PATHLIST
1692 // ----------------------------------------------------------------------------
1693 // registry and related stuff
1694 // ----------------------------------------------------------------------------
1696 // this is for MSW only
1699 #undef TEST_REGISTRY
1704 #include <wx/confbase.h>
1705 #include <wx/msw/regconf.h>
1707 static void TestRegConfWrite()
1709 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1710 regconf
.Write(_T("Hello"), wxString(_T("world")));
1713 #endif // TEST_REGCONF
1715 #ifdef TEST_REGISTRY
1717 #include <wx/msw/registry.h>
1719 // I chose this one because I liked its name, but it probably only exists under
1721 static const wxChar
*TESTKEY
=
1722 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1724 static void TestRegistryRead()
1726 puts("*** testing registry reading ***");
1728 wxRegKey
key(TESTKEY
);
1729 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1732 puts("ERROR: test key can't be opened, aborting test.");
1737 size_t nSubKeys
, nValues
;
1738 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1740 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1743 printf("Enumerating values:\n");
1747 bool cont
= key
.GetFirstValue(value
, dummy
);
1750 printf("Value '%s': type ", value
.c_str());
1751 switch ( key
.GetValueType(value
) )
1753 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1754 case wxRegKey::Type_String
: printf("SZ"); break;
1755 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1756 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1757 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1758 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1759 default: printf("other (unknown)"); break;
1762 printf(", value = ");
1763 if ( key
.IsNumericValue(value
) )
1766 key
.QueryValue(value
, &val
);
1772 key
.QueryValue(value
, val
);
1773 printf("'%s'", val
.c_str());
1775 key
.QueryRawValue(value
, val
);
1776 printf(" (raw value '%s')", val
.c_str());
1781 cont
= key
.GetNextValue(value
, dummy
);
1785 static void TestRegistryAssociation()
1788 The second call to deleteself genertaes an error message, with a
1789 messagebox saying .flo is crucial to system operation, while the .ddf
1790 call also fails, but with no error message
1795 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1797 key
= "ddxf_auto_file" ;
1798 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1800 key
= "ddxf_auto_file" ;
1801 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1804 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1806 key
= "program \"%1\"" ;
1808 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1810 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1812 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1814 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1818 #endif // TEST_REGISTRY
1820 // ----------------------------------------------------------------------------
1822 // ----------------------------------------------------------------------------
1826 #include <wx/socket.h>
1827 #include <wx/protocol/protocol.h>
1828 #include <wx/protocol/http.h>
1830 static void TestSocketServer()
1832 puts("*** Testing wxSocketServer ***\n");
1834 static const int PORT
= 3000;
1839 wxSocketServer
*server
= new wxSocketServer(addr
);
1840 if ( !server
->Ok() )
1842 puts("ERROR: failed to bind");
1849 printf("Server: waiting for connection on port %d...\n", PORT
);
1851 wxSocketBase
*socket
= server
->Accept();
1854 puts("ERROR: wxSocketServer::Accept() failed.");
1858 puts("Server: got a client.");
1860 server
->SetTimeout(60); // 1 min
1862 while ( socket
->IsConnected() )
1868 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1870 // don't log error if the client just close the connection
1871 if ( socket
->IsConnected() )
1873 puts("ERROR: in wxSocket::Read.");
1893 printf("Server: got '%s'.\n", s
.c_str());
1894 if ( s
== _T("bye") )
1901 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1902 socket
->Write("\r\n", 2);
1903 printf("Server: wrote '%s'.\n", s
.c_str());
1906 puts("Server: lost a client.");
1911 // same as "delete server" but is consistent with GUI programs
1915 static void TestSocketClient()
1917 puts("*** Testing wxSocketClient ***\n");
1919 static const char *hostname
= "www.wxwindows.org";
1922 addr
.Hostname(hostname
);
1925 printf("--- Attempting to connect to %s:80...\n", hostname
);
1927 wxSocketClient client
;
1928 if ( !client
.Connect(addr
) )
1930 printf("ERROR: failed to connect to %s\n", hostname
);
1934 printf("--- Connected to %s:%u...\n",
1935 addr
.Hostname().c_str(), addr
.Service());
1939 // could use simply "GET" here I suppose
1941 wxString::Format("GET http://%s/\r\n", hostname
);
1942 client
.Write(cmdGet
, cmdGet
.length());
1943 printf("--- Sent command '%s' to the server\n",
1944 MakePrintable(cmdGet
).c_str());
1945 client
.Read(buf
, WXSIZEOF(buf
));
1946 printf("--- Server replied:\n%s", buf
);
1950 #endif // TEST_SOCKETS
1952 // ----------------------------------------------------------------------------
1954 // ----------------------------------------------------------------------------
1958 #include <wx/protocol/ftp.h>
1962 #define FTP_ANONYMOUS
1964 #ifdef FTP_ANONYMOUS
1965 static const char *directory
= "/pub";
1966 static const char *filename
= "welcome.msg";
1968 static const char *directory
= "/etc";
1969 static const char *filename
= "issue";
1972 static bool TestFtpConnect()
1974 puts("*** Testing FTP connect ***");
1976 #ifdef FTP_ANONYMOUS
1977 static const char *hostname
= "ftp.wxwindows.org";
1979 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1980 #else // !FTP_ANONYMOUS
1981 static const char *hostname
= "localhost";
1984 fgets(user
, WXSIZEOF(user
), stdin
);
1985 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1989 printf("Password for %s: ", password
);
1990 fgets(password
, WXSIZEOF(password
), stdin
);
1991 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1992 ftp
.SetPassword(password
);
1994 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1995 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1997 if ( !ftp
.Connect(hostname
) )
1999 printf("ERROR: failed to connect to %s\n", hostname
);
2005 printf("--- Connected to %s, current directory is '%s'\n",
2006 hostname
, ftp
.Pwd().c_str());
2012 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2013 static void TestFtpWuFtpd()
2016 static const char *hostname
= "ftp.eudora.com";
2017 if ( !ftp
.Connect(hostname
) )
2019 printf("ERROR: failed to connect to %s\n", hostname
);
2023 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2024 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2027 printf("ERROR: couldn't get input stream for %s\n", filename
);
2031 size_t size
= in
->StreamSize();
2032 printf("Reading file %s (%u bytes)...", filename
, size
);
2034 char *data
= new char[size
];
2035 if ( !in
->Read(data
, size
) )
2037 puts("ERROR: read error");
2041 printf("Successfully retrieved the file.\n");
2050 static void TestFtpList()
2052 puts("*** Testing wxFTP file listing ***\n");
2055 if ( !ftp
.ChDir(directory
) )
2057 printf("ERROR: failed to cd to %s\n", directory
);
2060 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2062 // test NLIST and LIST
2063 wxArrayString files
;
2064 if ( !ftp
.GetFilesList(files
) )
2066 puts("ERROR: failed to get NLIST of files");
2070 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2071 size_t count
= files
.GetCount();
2072 for ( size_t n
= 0; n
< count
; n
++ )
2074 printf("\t%s\n", files
[n
].c_str());
2076 puts("End of the file list");
2079 if ( !ftp
.GetDirList(files
) )
2081 puts("ERROR: failed to get LIST of files");
2085 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2086 size_t count
= files
.GetCount();
2087 for ( size_t n
= 0; n
< count
; n
++ )
2089 printf("\t%s\n", files
[n
].c_str());
2091 puts("End of the file list");
2094 if ( !ftp
.ChDir(_T("..")) )
2096 puts("ERROR: failed to cd to ..");
2099 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2102 static void TestFtpDownload()
2104 puts("*** Testing wxFTP download ***\n");
2107 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2110 printf("ERROR: couldn't get input stream for %s\n", filename
);
2114 size_t size
= in
->StreamSize();
2115 printf("Reading file %s (%u bytes)...", filename
, size
);
2118 char *data
= new char[size
];
2119 if ( !in
->Read(data
, size
) )
2121 puts("ERROR: read error");
2125 printf("\nContents of %s:\n%s\n", filename
, data
);
2133 static void TestFtpFileSize()
2135 puts("*** Testing FTP SIZE command ***");
2137 if ( !ftp
.ChDir(directory
) )
2139 printf("ERROR: failed to cd to %s\n", directory
);
2142 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2144 if ( ftp
.FileExists(filename
) )
2146 int size
= ftp
.GetFileSize(filename
);
2148 printf("ERROR: couldn't get size of '%s'\n", filename
);
2150 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2154 printf("ERROR: '%s' doesn't exist\n", filename
);
2158 static void TestFtpMisc()
2160 puts("*** Testing miscellaneous wxFTP functions ***");
2162 if ( ftp
.SendCommand("STAT") != '2' )
2164 puts("ERROR: STAT failed");
2168 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2171 if ( ftp
.SendCommand("HELP SITE") != '2' )
2173 puts("ERROR: HELP SITE failed");
2177 printf("The list of site-specific commands:\n\n%s\n",
2178 ftp
.GetLastResult().c_str());
2182 static void TestFtpInteractive()
2184 puts("\n*** Interactive wxFTP test ***");
2190 printf("Enter FTP command: ");
2191 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2194 // kill the last '\n'
2195 buf
[strlen(buf
) - 1] = 0;
2197 // special handling of LIST and NLST as they require data connection
2198 wxString
start(buf
, 4);
2200 if ( start
== "LIST" || start
== "NLST" )
2203 if ( strlen(buf
) > 4 )
2206 wxArrayString files
;
2207 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2209 printf("ERROR: failed to get %s of files\n", start
.c_str());
2213 printf("--- %s of '%s' under '%s':\n",
2214 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2215 size_t count
= files
.GetCount();
2216 for ( size_t n
= 0; n
< count
; n
++ )
2218 printf("\t%s\n", files
[n
].c_str());
2220 puts("--- End of the file list");
2225 char ch
= ftp
.SendCommand(buf
);
2226 printf("Command %s", ch
? "succeeded" : "failed");
2229 printf(" (return code %c)", ch
);
2232 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2236 puts("\n*** done ***");
2239 static void TestFtpUpload()
2241 puts("*** Testing wxFTP uploading ***\n");
2244 static const char *file1
= "test1";
2245 static const char *file2
= "test2";
2246 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2249 printf("--- Uploading to %s ---\n", file1
);
2250 out
->Write("First hello", 11);
2254 // send a command to check the remote file
2255 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2257 printf("ERROR: STAT %s failed\n", file1
);
2261 printf("STAT %s returned:\n\n%s\n",
2262 file1
, ftp
.GetLastResult().c_str());
2265 out
= ftp
.GetOutputStream(file2
);
2268 printf("--- Uploading to %s ---\n", file1
);
2269 out
->Write("Second hello", 12);
2276 // ----------------------------------------------------------------------------
2278 // ----------------------------------------------------------------------------
2282 #include <wx/wfstream.h>
2283 #include <wx/mstream.h>
2285 static void TestFileStream()
2287 puts("*** Testing wxFileInputStream ***");
2289 static const wxChar
*filename
= _T("testdata.fs");
2291 wxFileOutputStream
fsOut(filename
);
2292 fsOut
.Write("foo", 3);
2295 wxFileInputStream
fsIn(filename
);
2296 printf("File stream size: %u\n", fsIn
.GetSize());
2297 while ( !fsIn
.Eof() )
2299 putchar(fsIn
.GetC());
2302 if ( !wxRemoveFile(filename
) )
2304 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2307 puts("\n*** wxFileInputStream test done ***");
2310 static void TestMemoryStream()
2312 puts("*** Testing wxMemoryInputStream ***");
2315 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2317 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2318 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2319 while ( !memInpStream
.Eof() )
2321 putchar(memInpStream
.GetC());
2324 puts("\n*** wxMemoryInputStream test done ***");
2327 #endif // TEST_STREAMS
2329 // ----------------------------------------------------------------------------
2331 // ----------------------------------------------------------------------------
2335 #include <wx/timer.h>
2336 #include <wx/utils.h>
2338 static void TestStopWatch()
2340 puts("*** Testing wxStopWatch ***\n");
2343 printf("Sleeping 3 seconds...");
2345 printf("\telapsed time: %ldms\n", sw
.Time());
2348 printf("Sleeping 2 more seconds...");
2350 printf("\telapsed time: %ldms\n", sw
.Time());
2353 printf("And 3 more seconds...");
2355 printf("\telapsed time: %ldms\n", sw
.Time());
2358 puts("\nChecking for 'backwards clock' bug...");
2359 for ( size_t n
= 0; n
< 70; n
++ )
2363 for ( size_t m
= 0; m
< 100000; m
++ )
2365 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2367 puts("\ntime is negative - ERROR!");
2377 #endif // TEST_TIMER
2379 // ----------------------------------------------------------------------------
2381 // ----------------------------------------------------------------------------
2385 #include <wx/vcard.h>
2387 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2390 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2394 wxString(_T('\t'), level
).c_str(),
2395 vcObj
->GetName().c_str());
2398 switch ( vcObj
->GetType() )
2400 case wxVCardObject::String
:
2401 case wxVCardObject::UString
:
2404 vcObj
->GetValue(&val
);
2405 value
<< _T('"') << val
<< _T('"');
2409 case wxVCardObject::Int
:
2412 vcObj
->GetValue(&i
);
2413 value
.Printf(_T("%u"), i
);
2417 case wxVCardObject::Long
:
2420 vcObj
->GetValue(&l
);
2421 value
.Printf(_T("%lu"), l
);
2425 case wxVCardObject::None
:
2428 case wxVCardObject::Object
:
2429 value
= _T("<node>");
2433 value
= _T("<unknown value type>");
2437 printf(" = %s", value
.c_str());
2440 DumpVObject(level
+ 1, *vcObj
);
2443 vcObj
= vcard
.GetNextProp(&cookie
);
2447 static void DumpVCardAddresses(const wxVCard
& vcard
)
2449 puts("\nShowing all addresses from vCard:\n");
2453 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2457 int flags
= addr
->GetFlags();
2458 if ( flags
& wxVCardAddress::Domestic
)
2460 flagsStr
<< _T("domestic ");
2462 if ( flags
& wxVCardAddress::Intl
)
2464 flagsStr
<< _T("international ");
2466 if ( flags
& wxVCardAddress::Postal
)
2468 flagsStr
<< _T("postal ");
2470 if ( flags
& wxVCardAddress::Parcel
)
2472 flagsStr
<< _T("parcel ");
2474 if ( flags
& wxVCardAddress::Home
)
2476 flagsStr
<< _T("home ");
2478 if ( flags
& wxVCardAddress::Work
)
2480 flagsStr
<< _T("work ");
2483 printf("Address %u:\n"
2485 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2488 addr
->GetPostOffice().c_str(),
2489 addr
->GetExtAddress().c_str(),
2490 addr
->GetStreet().c_str(),
2491 addr
->GetLocality().c_str(),
2492 addr
->GetRegion().c_str(),
2493 addr
->GetPostalCode().c_str(),
2494 addr
->GetCountry().c_str()
2498 addr
= vcard
.GetNextAddress(&cookie
);
2502 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2504 puts("\nShowing all phone numbers from vCard:\n");
2508 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2512 int flags
= phone
->GetFlags();
2513 if ( flags
& wxVCardPhoneNumber::Voice
)
2515 flagsStr
<< _T("voice ");
2517 if ( flags
& wxVCardPhoneNumber::Fax
)
2519 flagsStr
<< _T("fax ");
2521 if ( flags
& wxVCardPhoneNumber::Cellular
)
2523 flagsStr
<< _T("cellular ");
2525 if ( flags
& wxVCardPhoneNumber::Modem
)
2527 flagsStr
<< _T("modem ");
2529 if ( flags
& wxVCardPhoneNumber::Home
)
2531 flagsStr
<< _T("home ");
2533 if ( flags
& wxVCardPhoneNumber::Work
)
2535 flagsStr
<< _T("work ");
2538 printf("Phone number %u:\n"
2543 phone
->GetNumber().c_str()
2547 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2551 static void TestVCardRead()
2553 puts("*** Testing wxVCard reading ***\n");
2555 wxVCard
vcard(_T("vcard.vcf"));
2556 if ( !vcard
.IsOk() )
2558 puts("ERROR: couldn't load vCard.");
2562 // read individual vCard properties
2563 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2567 vcObj
->GetValue(&value
);
2572 value
= _T("<none>");
2575 printf("Full name retrieved directly: %s\n", value
.c_str());
2578 if ( !vcard
.GetFullName(&value
) )
2580 value
= _T("<none>");
2583 printf("Full name from wxVCard API: %s\n", value
.c_str());
2585 // now show how to deal with multiply occuring properties
2586 DumpVCardAddresses(vcard
);
2587 DumpVCardPhoneNumbers(vcard
);
2589 // and finally show all
2590 puts("\nNow dumping the entire vCard:\n"
2591 "-----------------------------\n");
2593 DumpVObject(0, vcard
);
2597 static void TestVCardWrite()
2599 puts("*** Testing wxVCard writing ***\n");
2602 if ( !vcard
.IsOk() )
2604 puts("ERROR: couldn't create vCard.");
2609 vcard
.SetName("Zeitlin", "Vadim");
2610 vcard
.SetFullName("Vadim Zeitlin");
2611 vcard
.SetOrganization("wxWindows", "R&D");
2613 // just dump the vCard back
2614 puts("Entire vCard follows:\n");
2615 puts(vcard
.Write());
2619 #endif // TEST_VCARD
2621 // ----------------------------------------------------------------------------
2622 // wide char (Unicode) support
2623 // ----------------------------------------------------------------------------
2627 #include <wx/strconv.h>
2628 #include <wx/fontenc.h>
2629 #include <wx/encconv.h>
2630 #include <wx/buffer.h>
2632 static void TestUtf8()
2634 puts("*** Testing UTF8 support ***\n");
2636 static const char textInUtf8
[] =
2638 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2639 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2640 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2641 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2642 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2643 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2644 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2649 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2651 puts("ERROR: UTF-8 decoding failed.");
2655 // using wxEncodingConverter
2657 wxEncodingConverter ec
;
2658 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2659 ec
.Convert(wbuf
, buf
);
2660 #else // using wxCSConv
2661 wxCSConv
conv(_T("koi8-r"));
2662 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2664 puts("ERROR: conversion to KOI8-R failed.");
2669 printf("The resulting string (in koi8-r): %s\n", buf
);
2673 #endif // TEST_WCHAR
2675 // ----------------------------------------------------------------------------
2677 // ----------------------------------------------------------------------------
2681 #include "wx/filesys.h"
2682 #include "wx/fs_zip.h"
2683 #include "wx/zipstrm.h"
2685 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2687 static void TestZipStreamRead()
2689 puts("*** Testing ZIP reading ***\n");
2691 static const wxChar
*filename
= _T("foo");
2692 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2693 printf("Archive size: %u\n", istr
.GetSize());
2695 printf("Dumping the file '%s':\n", filename
);
2696 while ( !istr
.Eof() )
2698 putchar(istr
.GetC());
2702 puts("\n----- done ------");
2705 static void DumpZipDirectory(wxFileSystem
& fs
,
2706 const wxString
& dir
,
2707 const wxString
& indent
)
2709 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2710 TESTFILE_ZIP
, dir
.c_str());
2711 wxString wildcard
= prefix
+ _T("/*");
2713 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2714 while ( !dirname
.empty() )
2716 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2718 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2723 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2725 DumpZipDirectory(fs
, dirname
,
2726 indent
+ wxString(_T(' '), 4));
2728 dirname
= fs
.FindNext();
2731 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2732 while ( !filename
.empty() )
2734 if ( !filename
.StartsWith(prefix
, &filename
) )
2736 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2741 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2743 filename
= fs
.FindNext();
2747 static void TestZipFileSystem()
2749 puts("*** Testing ZIP file system ***\n");
2751 wxFileSystem::AddHandler(new wxZipFSHandler
);
2753 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2755 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2760 // ----------------------------------------------------------------------------
2762 // ----------------------------------------------------------------------------
2766 #include <wx/zstream.h>
2767 #include <wx/wfstream.h>
2769 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2770 static const char *TEST_DATA
= "hello and hello again";
2772 static void TestZlibStreamWrite()
2774 puts("*** Testing Zlib stream reading ***\n");
2776 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2777 wxZlibOutputStream
ostr(fileOutStream
, 0);
2778 printf("Compressing the test string... ");
2779 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2782 puts("(ERROR: failed)");
2789 puts("\n----- done ------");
2792 static void TestZlibStreamRead()
2794 puts("*** Testing Zlib stream reading ***\n");
2796 wxFileInputStream
fileInStream(FILENAME_GZ
);
2797 wxZlibInputStream
istr(fileInStream
);
2798 printf("Archive size: %u\n", istr
.GetSize());
2800 puts("Dumping the file:");
2801 while ( !istr
.Eof() )
2803 putchar(istr
.GetC());
2807 puts("\n----- done ------");
2812 // ----------------------------------------------------------------------------
2814 // ----------------------------------------------------------------------------
2816 #ifdef TEST_DATETIME
2820 #include <wx/date.h>
2822 #include <wx/datetime.h>
2827 wxDateTime::wxDateTime_t day
;
2828 wxDateTime::Month month
;
2830 wxDateTime::wxDateTime_t hour
, min
, sec
;
2832 wxDateTime::WeekDay wday
;
2833 time_t gmticks
, ticks
;
2835 void Init(const wxDateTime::Tm
& tm
)
2844 gmticks
= ticks
= -1;
2847 wxDateTime
DT() const
2848 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2850 bool SameDay(const wxDateTime::Tm
& tm
) const
2852 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2855 wxString
Format() const
2858 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2860 wxDateTime::GetMonthName(month
).c_str(),
2862 abs(wxDateTime::ConvertYearToBC(year
)),
2863 year
> 0 ? "AD" : "BC");
2867 wxString
FormatDate() const
2870 s
.Printf("%02d-%s-%4d%s",
2872 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2873 abs(wxDateTime::ConvertYearToBC(year
)),
2874 year
> 0 ? "AD" : "BC");
2879 static const Date testDates
[] =
2881 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2882 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2883 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2884 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2885 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2886 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2887 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2888 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2889 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2890 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2891 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2892 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2893 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2894 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2895 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2898 // this test miscellaneous static wxDateTime functions
2899 static void TestTimeStatic()
2901 puts("\n*** wxDateTime static methods test ***");
2903 // some info about the current date
2904 int year
= wxDateTime::GetCurrentYear();
2905 printf("Current year %d is %sa leap one and has %d days.\n",
2907 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2908 wxDateTime::GetNumberOfDays(year
));
2910 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2911 printf("Current month is '%s' ('%s') and it has %d days\n",
2912 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2913 wxDateTime::GetMonthName(month
).c_str(),
2914 wxDateTime::GetNumberOfDays(month
));
2917 static const size_t nYears
= 5;
2918 static const size_t years
[2][nYears
] =
2920 // first line: the years to test
2921 { 1990, 1976, 2000, 2030, 1984, },
2923 // second line: TRUE if leap, FALSE otherwise
2924 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2927 for ( size_t n
= 0; n
< nYears
; n
++ )
2929 int year
= years
[0][n
];
2930 bool should
= years
[1][n
] != 0,
2931 is
= wxDateTime::IsLeapYear(year
);
2933 printf("Year %d is %sa leap year (%s)\n",
2936 should
== is
? "ok" : "ERROR");
2938 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2942 // test constructing wxDateTime objects
2943 static void TestTimeSet()
2945 puts("\n*** wxDateTime construction test ***");
2947 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2949 const Date
& d1
= testDates
[n
];
2950 wxDateTime dt
= d1
.DT();
2953 d2
.Init(dt
.GetTm());
2955 wxString s1
= d1
.Format(),
2958 printf("Date: %s == %s (%s)\n",
2959 s1
.c_str(), s2
.c_str(),
2960 s1
== s2
? "ok" : "ERROR");
2964 // test time zones stuff
2965 static void TestTimeZones()
2967 puts("\n*** wxDateTime timezone test ***");
2969 wxDateTime now
= wxDateTime::Now();
2971 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2972 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2973 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2974 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2975 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2976 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2978 wxDateTime::Tm tm
= now
.GetTm();
2979 if ( wxDateTime(tm
) != now
)
2981 printf("ERROR: got %s instead of %s\n",
2982 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2986 // test some minimal support for the dates outside the standard range
2987 static void TestTimeRange()
2989 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2991 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2993 printf("Unix epoch:\t%s\n",
2994 wxDateTime(2440587.5).Format(fmt
).c_str());
2995 printf("Feb 29, 0: \t%s\n",
2996 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2997 printf("JDN 0: \t%s\n",
2998 wxDateTime(0.0).Format(fmt
).c_str());
2999 printf("Jan 1, 1AD:\t%s\n",
3000 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3001 printf("May 29, 2099:\t%s\n",
3002 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3005 static void TestTimeTicks()
3007 puts("\n*** wxDateTime ticks test ***");
3009 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3011 const Date
& d
= testDates
[n
];
3012 if ( d
.ticks
== -1 )
3015 wxDateTime dt
= d
.DT();
3016 long ticks
= (dt
.GetValue() / 1000).ToLong();
3017 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3018 if ( ticks
== d
.ticks
)
3024 printf(" (ERROR: should be %ld, delta = %ld)\n",
3025 d
.ticks
, ticks
- d
.ticks
);
3028 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3029 ticks
= (dt
.GetValue() / 1000).ToLong();
3030 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3031 if ( ticks
== d
.gmticks
)
3037 printf(" (ERROR: should be %ld, delta = %ld)\n",
3038 d
.gmticks
, ticks
- d
.gmticks
);
3045 // test conversions to JDN &c
3046 static void TestTimeJDN()
3048 puts("\n*** wxDateTime to JDN test ***");
3050 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3052 const Date
& d
= testDates
[n
];
3053 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3054 double jdn
= dt
.GetJulianDayNumber();
3056 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3063 printf(" (ERROR: should be %f, delta = %f)\n",
3064 d
.jdn
, jdn
- d
.jdn
);
3069 // test week days computation
3070 static void TestTimeWDays()
3072 puts("\n*** wxDateTime weekday test ***");
3074 // test GetWeekDay()
3076 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3078 const Date
& d
= testDates
[n
];
3079 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3081 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3084 wxDateTime::GetWeekDayName(wday
).c_str());
3085 if ( wday
== d
.wday
)
3091 printf(" (ERROR: should be %s)\n",
3092 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3098 // test SetToWeekDay()
3099 struct WeekDateTestData
3101 Date date
; // the real date (precomputed)
3102 int nWeek
; // its week index in the month
3103 wxDateTime::WeekDay wday
; // the weekday
3104 wxDateTime::Month month
; // the month
3105 int year
; // and the year
3107 wxString
Format() const
3110 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3112 case 1: which
= "first"; break;
3113 case 2: which
= "second"; break;
3114 case 3: which
= "third"; break;
3115 case 4: which
= "fourth"; break;
3116 case 5: which
= "fifth"; break;
3118 case -1: which
= "last"; break;
3123 which
+= " from end";
3126 s
.Printf("The %s %s of %s in %d",
3128 wxDateTime::GetWeekDayName(wday
).c_str(),
3129 wxDateTime::GetMonthName(month
).c_str(),
3136 // the array data was generated by the following python program
3138 from DateTime import *
3139 from whrandom import *
3140 from string import *
3142 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3143 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3145 week = DateTimeDelta(7)
3148 year = randint(1900, 2100)
3149 month = randint(1, 12)
3150 day = randint(1, 28)
3151 dt = DateTime(year, month, day)
3152 wday = dt.day_of_week
3154 countFromEnd = choice([-1, 1])
3157 while dt.month is month:
3158 dt = dt - countFromEnd * week
3159 weekNum = weekNum + countFromEnd
3161 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3163 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3164 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3167 static const WeekDateTestData weekDatesTestData
[] =
3169 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3170 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3171 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3172 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3173 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3174 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3175 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3176 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3177 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3178 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3179 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3180 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3181 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3182 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3183 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3184 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3185 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3186 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3187 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3188 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3191 static const char *fmt
= "%d-%b-%Y";
3194 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3196 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3198 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3200 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3202 const Date
& d
= wd
.date
;
3203 if ( d
.SameDay(dt
.GetTm()) )
3209 dt
.Set(d
.day
, d
.month
, d
.year
);
3211 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3216 // test the computation of (ISO) week numbers
3217 static void TestTimeWNumber()
3219 puts("\n*** wxDateTime week number test ***");
3221 struct WeekNumberTestData
3223 Date date
; // the date
3224 wxDateTime::wxDateTime_t week
; // the week number in the year
3225 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3226 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3227 wxDateTime::wxDateTime_t dnum
; // day number in the year
3230 // data generated with the following python script:
3232 from DateTime import *
3233 from whrandom import *
3234 from string import *
3236 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3237 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3239 def GetMonthWeek(dt):
3240 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3241 if weekNumMonth < 0:
3242 weekNumMonth = weekNumMonth + 53
3245 def GetLastSundayBefore(dt):
3246 if dt.iso_week[2] == 7:
3249 return dt - DateTimeDelta(dt.iso_week[2])
3252 year = randint(1900, 2100)
3253 month = randint(1, 12)
3254 day = randint(1, 28)
3255 dt = DateTime(year, month, day)
3256 dayNum = dt.day_of_year
3257 weekNum = dt.iso_week[1]
3258 weekNumMonth = GetMonthWeek(dt)
3261 dtSunday = GetLastSundayBefore(dt)
3263 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3264 weekNumMonth2 = weekNumMonth2 + 1
3265 dtSunday = dtSunday - DateTimeDelta(7)
3267 data = { 'day': rjust(`day`, 2), \
3268 'month': monthNames[month - 1], \
3270 'weekNum': rjust(`weekNum`, 2), \
3271 'weekNumMonth': weekNumMonth, \
3272 'weekNumMonth2': weekNumMonth2, \
3273 'dayNum': rjust(`dayNum`, 3) }
3275 print " { { %(day)s, "\
3276 "wxDateTime::%(month)s, "\
3279 "%(weekNumMonth)s, "\
3280 "%(weekNumMonth2)s, "\
3281 "%(dayNum)s }," % data
3284 static const WeekNumberTestData weekNumberTestDates
[] =
3286 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3287 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3288 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3289 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3290 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3291 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3292 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3293 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3294 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3295 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3296 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3297 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3298 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3299 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3300 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3301 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3302 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3303 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3304 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3305 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3308 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3310 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3311 const Date
& d
= wn
.date
;
3313 wxDateTime dt
= d
.DT();
3315 wxDateTime::wxDateTime_t
3316 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3317 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3318 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3319 dnum
= dt
.GetDayOfYear();
3321 printf("%s: the day number is %d",
3322 d
.FormatDate().c_str(), dnum
);
3323 if ( dnum
== wn
.dnum
)
3329 printf(" (ERROR: should be %d)", wn
.dnum
);
3332 printf(", week in month is %d", wmon
);
3333 if ( wmon
== wn
.wmon
)
3339 printf(" (ERROR: should be %d)", wn
.wmon
);
3342 printf(" or %d", wmon2
);
3343 if ( wmon2
== wn
.wmon2
)
3349 printf(" (ERROR: should be %d)", wn
.wmon2
);
3352 printf(", week in year is %d", week
);
3353 if ( week
== wn
.week
)
3359 printf(" (ERROR: should be %d)\n", wn
.week
);
3364 // test DST calculations
3365 static void TestTimeDST()
3367 puts("\n*** wxDateTime DST test ***");
3369 printf("DST is%s in effect now.\n\n",
3370 wxDateTime::Now().IsDST() ? "" : " not");
3372 // taken from http://www.energy.ca.gov/daylightsaving.html
3373 static const Date datesDST
[2][2004 - 1900 + 1] =
3376 { 1, wxDateTime::Apr
, 1990 },
3377 { 7, wxDateTime::Apr
, 1991 },
3378 { 5, wxDateTime::Apr
, 1992 },
3379 { 4, wxDateTime::Apr
, 1993 },
3380 { 3, wxDateTime::Apr
, 1994 },
3381 { 2, wxDateTime::Apr
, 1995 },
3382 { 7, wxDateTime::Apr
, 1996 },
3383 { 6, wxDateTime::Apr
, 1997 },
3384 { 5, wxDateTime::Apr
, 1998 },
3385 { 4, wxDateTime::Apr
, 1999 },
3386 { 2, wxDateTime::Apr
, 2000 },
3387 { 1, wxDateTime::Apr
, 2001 },
3388 { 7, wxDateTime::Apr
, 2002 },
3389 { 6, wxDateTime::Apr
, 2003 },
3390 { 4, wxDateTime::Apr
, 2004 },
3393 { 28, wxDateTime::Oct
, 1990 },
3394 { 27, wxDateTime::Oct
, 1991 },
3395 { 25, wxDateTime::Oct
, 1992 },
3396 { 31, wxDateTime::Oct
, 1993 },
3397 { 30, wxDateTime::Oct
, 1994 },
3398 { 29, wxDateTime::Oct
, 1995 },
3399 { 27, wxDateTime::Oct
, 1996 },
3400 { 26, wxDateTime::Oct
, 1997 },
3401 { 25, wxDateTime::Oct
, 1998 },
3402 { 31, wxDateTime::Oct
, 1999 },
3403 { 29, wxDateTime::Oct
, 2000 },
3404 { 28, wxDateTime::Oct
, 2001 },
3405 { 27, wxDateTime::Oct
, 2002 },
3406 { 26, wxDateTime::Oct
, 2003 },
3407 { 31, wxDateTime::Oct
, 2004 },
3412 for ( year
= 1990; year
< 2005; year
++ )
3414 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3415 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3417 printf("DST period in the US for year %d: from %s to %s",
3418 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3420 size_t n
= year
- 1990;
3421 const Date
& dBegin
= datesDST
[0][n
];
3422 const Date
& dEnd
= datesDST
[1][n
];
3424 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3430 printf(" (ERROR: should be %s %d to %s %d)\n",
3431 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3432 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3438 for ( year
= 1990; year
< 2005; year
++ )
3440 printf("DST period in Europe for year %d: from %s to %s\n",
3442 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3443 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3447 // test wxDateTime -> text conversion
3448 static void TestTimeFormat()
3450 puts("\n*** wxDateTime formatting test ***");
3452 // some information may be lost during conversion, so store what kind
3453 // of info should we recover after a round trip
3456 CompareNone
, // don't try comparing
3457 CompareBoth
, // dates and times should be identical
3458 CompareDate
, // dates only
3459 CompareTime
// time only
3464 CompareKind compareKind
;
3466 } formatTestFormats
[] =
3468 { CompareBoth
, "---> %c" },
3469 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3470 { CompareBoth
, "Date is %x, time is %X" },
3471 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3472 { CompareNone
, "The day of year: %j, the week of year: %W" },
3473 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3476 static const Date formatTestDates
[] =
3478 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3479 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3481 // this test can't work for other centuries because it uses two digit
3482 // years in formats, so don't even try it
3483 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3484 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3485 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3489 // an extra test (as it doesn't depend on date, don't do it in the loop)
3490 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3492 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3496 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3497 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3499 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3500 printf("%s", s
.c_str());
3502 // what can we recover?
3503 int kind
= formatTestFormats
[n
].compareKind
;
3507 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3510 // converion failed - should it have?
3511 if ( kind
== CompareNone
)
3514 puts(" (ERROR: conversion back failed)");
3518 // should have parsed the entire string
3519 puts(" (ERROR: conversion back stopped too soon)");
3523 bool equal
= FALSE
; // suppress compilaer warning
3531 equal
= dt
.IsSameDate(dt2
);
3535 equal
= dt
.IsSameTime(dt2
);
3541 printf(" (ERROR: got back '%s' instead of '%s')\n",
3542 dt2
.Format().c_str(), dt
.Format().c_str());
3553 // test text -> wxDateTime conversion
3554 static void TestTimeParse()
3556 puts("\n*** wxDateTime parse test ***");
3558 struct ParseTestData
3565 static const ParseTestData parseTestDates
[] =
3567 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3568 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3571 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3573 const char *format
= parseTestDates
[n
].format
;
3575 printf("%s => ", format
);
3578 if ( dt
.ParseRfc822Date(format
) )
3580 printf("%s ", dt
.Format().c_str());
3582 if ( parseTestDates
[n
].good
)
3584 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3591 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3596 puts("(ERROR: bad format)");
3601 printf("bad format (%s)\n",
3602 parseTestDates
[n
].good
? "ERROR" : "ok");
3607 static void TestDateTimeInteractive()
3609 puts("\n*** interactive wxDateTime tests ***");
3615 printf("Enter a date: ");
3616 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3619 // kill the last '\n'
3620 buf
[strlen(buf
) - 1] = 0;
3623 const char *p
= dt
.ParseDate(buf
);
3626 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3632 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3635 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3636 dt
.Format("%b %d, %Y").c_str(),
3638 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3639 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3640 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3643 puts("\n*** done ***");
3646 static void TestTimeMS()
3648 puts("*** testing millisecond-resolution support in wxDateTime ***");
3650 wxDateTime dt1
= wxDateTime::Now(),
3651 dt2
= wxDateTime::UNow();
3653 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3654 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3655 printf("Dummy loop: ");
3656 for ( int i
= 0; i
< 6000; i
++ )
3658 //for ( int j = 0; j < 10; j++ )
3661 s
.Printf("%g", sqrt(i
));
3670 dt2
= wxDateTime::UNow();
3671 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3673 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3675 puts("\n*** done ***");
3678 static void TestTimeArithmetics()
3680 puts("\n*** testing arithmetic operations on wxDateTime ***");
3682 static const struct ArithmData
3684 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3685 : span(sp
), name(nam
) { }
3689 } testArithmData
[] =
3691 ArithmData(wxDateSpan::Day(), "day"),
3692 ArithmData(wxDateSpan::Week(), "week"),
3693 ArithmData(wxDateSpan::Month(), "month"),
3694 ArithmData(wxDateSpan::Year(), "year"),
3695 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3698 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3700 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3702 wxDateSpan span
= testArithmData
[n
].span
;
3706 const char *name
= testArithmData
[n
].name
;
3707 printf("%s + %s = %s, %s - %s = %s\n",
3708 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3709 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3711 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3712 if ( dt1
- span
== dt
)
3718 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3721 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3722 if ( dt2
+ span
== dt
)
3728 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3731 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3732 if ( dt2
+ 2*span
== dt1
)
3738 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3745 static void TestTimeHolidays()
3747 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3749 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3750 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3751 dtEnd
= dtStart
.GetLastMonthDay();
3753 wxDateTimeArray hol
;
3754 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3756 const wxChar
*format
= "%d-%b-%Y (%a)";
3758 printf("All holidays between %s and %s:\n",
3759 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3761 size_t count
= hol
.GetCount();
3762 for ( size_t n
= 0; n
< count
; n
++ )
3764 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3770 static void TestTimeZoneBug()
3772 puts("\n*** testing for DST/timezone bug ***\n");
3774 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3775 for ( int i
= 0; i
< 31; i
++ )
3777 printf("Date %s: week day %s.\n",
3778 date
.Format(_T("%d-%m-%Y")).c_str(),
3779 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3781 date
+= wxDateSpan::Day();
3787 static void TestTimeSpanFormat()
3789 puts("\n*** wxTimeSpan tests ***");
3791 static const char *formats
[] =
3793 _T("(default) %H:%M:%S"),
3794 _T("%E weeks and %D days"),
3795 _T("%l milliseconds"),
3796 _T("(with ms) %H:%M:%S:%l"),
3797 _T("100%% of minutes is %M"), // test "%%"
3798 _T("%D days and %H hours"),
3801 wxTimeSpan
ts1(1, 2, 3, 4),
3803 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3805 printf("ts1 = %s\tts2 = %s\n",
3806 ts1
.Format(formats
[n
]).c_str(),
3807 ts2
.Format(formats
[n
]).c_str());
3815 // test compatibility with the old wxDate/wxTime classes
3816 static void TestTimeCompatibility()
3818 puts("\n*** wxDateTime compatibility test ***");
3820 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3821 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3823 double jdnNow
= wxDateTime::Now().GetJDN();
3824 long jdnMidnight
= (long)(jdnNow
- 0.5);
3825 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3827 jdnMidnight
= wxDate().Set().GetJulianDate();
3828 printf("wxDateTime for today: %s\n",
3829 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3831 int flags
= wxEUROPEAN
;//wxFULL;
3834 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3835 for ( int n
= 0; n
< 7; n
++ )
3837 printf("Previous %s is %s\n",
3838 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3839 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3845 #endif // TEST_DATETIME
3847 // ----------------------------------------------------------------------------
3849 // ----------------------------------------------------------------------------
3853 #include <wx/thread.h>
3855 static size_t gs_counter
= (size_t)-1;
3856 static wxCriticalSection gs_critsect
;
3857 static wxCondition gs_cond
;
3859 class MyJoinableThread
: public wxThread
3862 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3863 { m_n
= n
; Create(); }
3865 // thread execution starts here
3866 virtual ExitCode
Entry();
3872 wxThread::ExitCode
MyJoinableThread::Entry()
3874 unsigned long res
= 1;
3875 for ( size_t n
= 1; n
< m_n
; n
++ )
3879 // it's a loooong calculation :-)
3883 return (ExitCode
)res
;
3886 class MyDetachedThread
: public wxThread
3889 MyDetachedThread(size_t n
, char ch
)
3893 m_cancelled
= FALSE
;
3898 // thread execution starts here
3899 virtual ExitCode
Entry();
3902 virtual void OnExit();
3905 size_t m_n
; // number of characters to write
3906 char m_ch
; // character to write
3908 bool m_cancelled
; // FALSE if we exit normally
3911 wxThread::ExitCode
MyDetachedThread::Entry()
3914 wxCriticalSectionLocker
lock(gs_critsect
);
3915 if ( gs_counter
== (size_t)-1 )
3921 for ( size_t n
= 0; n
< m_n
; n
++ )
3923 if ( TestDestroy() )
3933 wxThread::Sleep(100);
3939 void MyDetachedThread::OnExit()
3941 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3943 wxCriticalSectionLocker
lock(gs_critsect
);
3944 if ( !--gs_counter
&& !m_cancelled
)
3948 void TestDetachedThreads()
3950 puts("\n*** Testing detached threads ***");
3952 static const size_t nThreads
= 3;
3953 MyDetachedThread
*threads
[nThreads
];
3955 for ( n
= 0; n
< nThreads
; n
++ )
3957 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3960 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3961 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3963 for ( n
= 0; n
< nThreads
; n
++ )
3968 // wait until all threads terminate
3974 void TestJoinableThreads()
3976 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3978 // calc 10! in the background
3979 MyJoinableThread
thread(10);
3982 printf("\nThread terminated with exit code %lu.\n",
3983 (unsigned long)thread
.Wait());
3986 void TestThreadSuspend()
3988 puts("\n*** Testing thread suspend/resume functions ***");
3990 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3994 // this is for this demo only, in a real life program we'd use another
3995 // condition variable which would be signaled from wxThread::Entry() to
3996 // tell us that the thread really started running - but here just wait a
3997 // bit and hope that it will be enough (the problem is, of course, that
3998 // the thread might still not run when we call Pause() which will result
4000 wxThread::Sleep(300);
4002 for ( size_t n
= 0; n
< 3; n
++ )
4006 puts("\nThread suspended");
4009 // don't sleep but resume immediately the first time
4010 wxThread::Sleep(300);
4012 puts("Going to resume the thread");
4017 puts("Waiting until it terminates now");
4019 // wait until the thread terminates
4025 void TestThreadDelete()
4027 // As above, using Sleep() is only for testing here - we must use some
4028 // synchronisation object instead to ensure that the thread is still
4029 // running when we delete it - deleting a detached thread which already
4030 // terminated will lead to a crash!
4032 puts("\n*** Testing thread delete function ***");
4034 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4038 puts("\nDeleted a thread which didn't start to run yet.");
4040 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4044 wxThread::Sleep(300);
4048 puts("\nDeleted a running thread.");
4050 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4054 wxThread::Sleep(300);
4060 puts("\nDeleted a sleeping thread.");
4062 MyJoinableThread
thread3(20);
4067 puts("\nDeleted a joinable thread.");
4069 MyJoinableThread
thread4(2);
4072 wxThread::Sleep(300);
4076 puts("\nDeleted a joinable thread which already terminated.");
4081 #endif // TEST_THREADS
4083 // ----------------------------------------------------------------------------
4085 // ----------------------------------------------------------------------------
4089 static void PrintArray(const char* name
, const wxArrayString
& array
)
4091 printf("Dump of the array '%s'\n", name
);
4093 size_t nCount
= array
.GetCount();
4094 for ( size_t n
= 0; n
< nCount
; n
++ )
4096 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4100 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4102 printf("Dump of the array '%s'\n", name
);
4104 size_t nCount
= array
.GetCount();
4105 for ( size_t n
= 0; n
< nCount
; n
++ )
4107 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4111 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4112 const wxString
& second
)
4114 return first
.length() - second
.length();
4117 int wxCMPFUNC_CONV
IntCompare(int *first
,
4120 return *first
- *second
;
4123 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4126 return *second
- *first
;
4129 static void TestArrayOfInts()
4131 puts("*** Testing wxArrayInt ***\n");
4142 puts("After sort:");
4146 puts("After reverse sort:");
4147 a
.Sort(IntRevCompare
);
4151 #include "wx/dynarray.h"
4153 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4154 #include "wx/arrimpl.cpp"
4155 WX_DEFINE_OBJARRAY(ArrayBars
);
4157 static void TestArrayOfObjects()
4159 puts("*** Testing wxObjArray ***\n");
4163 Bar
bar("second bar");
4165 printf("Initially: %u objects in the array, %u objects total.\n",
4166 bars
.GetCount(), Bar::GetNumber());
4168 bars
.Add(new Bar("first bar"));
4171 printf("Now: %u objects in the array, %u objects total.\n",
4172 bars
.GetCount(), Bar::GetNumber());
4176 printf("After Empty(): %u objects in the array, %u objects total.\n",
4177 bars
.GetCount(), Bar::GetNumber());
4180 printf("Finally: no more objects in the array, %u objects total.\n",
4184 #endif // TEST_ARRAYS
4186 // ----------------------------------------------------------------------------
4188 // ----------------------------------------------------------------------------
4192 #include "wx/timer.h"
4193 #include "wx/tokenzr.h"
4195 static void TestStringConstruction()
4197 puts("*** Testing wxString constructores ***");
4199 #define TEST_CTOR(args, res) \
4202 printf("wxString%s = %s ", #args, s.c_str()); \
4209 printf("(ERROR: should be %s)\n", res); \
4213 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4214 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4215 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4216 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4218 static const wxChar
*s
= _T("?really!");
4219 const wxChar
*start
= wxStrchr(s
, _T('r'));
4220 const wxChar
*end
= wxStrchr(s
, _T('!'));
4221 TEST_CTOR((start
, end
), _T("really"));
4226 static void TestString()
4236 for (int i
= 0; i
< 1000000; ++i
)
4240 c
= "! How'ya doin'?";
4243 c
= "Hello world! What's up?";
4248 printf ("TestString elapsed time: %ld\n", sw
.Time());
4251 static void TestPChar()
4259 for (int i
= 0; i
< 1000000; ++i
)
4261 strcpy (a
, "Hello");
4262 strcpy (b
, " world");
4263 strcpy (c
, "! How'ya doin'?");
4266 strcpy (c
, "Hello world! What's up?");
4267 if (strcmp (c
, a
) == 0)
4271 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4274 static void TestStringSub()
4276 wxString
s("Hello, world!");
4278 puts("*** Testing wxString substring extraction ***");
4280 printf("String = '%s'\n", s
.c_str());
4281 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4282 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4283 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4284 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4285 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4286 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4288 static const wxChar
*prefixes
[] =
4292 _T("Hello, world!"),
4293 _T("Hello, world!!!"),
4299 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4301 wxString prefix
= prefixes
[n
], rest
;
4302 bool rc
= s
.StartsWith(prefix
, &rest
);
4303 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4306 printf(" (the rest is '%s')\n", rest
.c_str());
4317 static void TestStringFormat()
4319 puts("*** Testing wxString formatting ***");
4322 s
.Printf("%03d", 18);
4324 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4325 printf("Number 18: %s\n", s
.c_str());
4330 // returns "not found" for npos, value for all others
4331 static wxString
PosToString(size_t res
)
4333 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4334 : wxString::Format(_T("%u"), res
);
4338 static void TestStringFind()
4340 puts("*** Testing wxString find() functions ***");
4342 static const wxChar
*strToFind
= _T("ell");
4343 static const struct StringFindTest
4347 result
; // of searching "ell" in str
4350 { _T("Well, hello world"), 0, 1 },
4351 { _T("Well, hello world"), 6, 7 },
4352 { _T("Well, hello world"), 9, wxString::npos
},
4355 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4357 const StringFindTest
& ft
= findTestData
[n
];
4358 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4360 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4361 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4363 size_t resTrue
= ft
.result
;
4364 if ( res
== resTrue
)
4370 printf(_T("(ERROR: should be %s)\n"),
4371 PosToString(resTrue
).c_str());
4378 static void TestStringTokenizer()
4380 puts("*** Testing wxStringTokenizer ***");
4382 static const wxChar
*modeNames
[] =
4386 _T("return all empty"),
4391 static const struct StringTokenizerTest
4393 const wxChar
*str
; // string to tokenize
4394 const wxChar
*delims
; // delimiters to use
4395 size_t count
; // count of token
4396 wxStringTokenizerMode mode
; // how should we tokenize it
4397 } tokenizerTestData
[] =
4399 { _T(""), _T(" "), 0 },
4400 { _T("Hello, world"), _T(" "), 2 },
4401 { _T("Hello, world "), _T(" "), 2 },
4402 { _T("Hello, world"), _T(","), 2 },
4403 { _T("Hello, world!"), _T(",!"), 2 },
4404 { _T("Hello,, world!"), _T(",!"), 3 },
4405 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4406 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4407 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4408 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4409 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4410 { _T("01/02/99"), _T("/-"), 3 },
4411 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4414 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4416 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4417 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4419 size_t count
= tkz
.CountTokens();
4420 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4421 MakePrintable(tt
.str
).c_str(),
4423 MakePrintable(tt
.delims
).c_str(),
4424 modeNames
[tkz
.GetMode()]);
4425 if ( count
== tt
.count
)
4431 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4436 // if we emulate strtok(), check that we do it correctly
4437 wxChar
*buf
, *s
= NULL
, *last
;
4439 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4441 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4442 wxStrcpy(buf
, tt
.str
);
4444 s
= wxStrtok(buf
, tt
.delims
, &last
);
4451 // now show the tokens themselves
4453 while ( tkz
.HasMoreTokens() )
4455 wxString token
= tkz
.GetNextToken();
4457 printf(_T("\ttoken %u: '%s'"),
4459 MakePrintable(token
).c_str());
4469 printf(" (ERROR: should be %s)\n", s
);
4472 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4476 // nothing to compare with
4481 if ( count2
!= count
)
4483 puts(_T("\tERROR: token count mismatch"));
4492 static void TestStringReplace()
4494 puts("*** Testing wxString::replace ***");
4496 static const struct StringReplaceTestData
4498 const wxChar
*original
; // original test string
4499 size_t start
, len
; // the part to replace
4500 const wxChar
*replacement
; // the replacement string
4501 const wxChar
*result
; // and the expected result
4502 } stringReplaceTestData
[] =
4504 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4505 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4506 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4507 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4508 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4511 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4513 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4515 wxString original
= data
.original
;
4516 original
.replace(data
.start
, data
.len
, data
.replacement
);
4518 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4519 data
.original
, data
.start
, data
.len
, data
.replacement
,
4522 if ( original
== data
.result
)
4528 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4535 #endif // TEST_STRINGS
4537 // ----------------------------------------------------------------------------
4539 // ----------------------------------------------------------------------------
4541 int main(int argc
, char **argv
)
4543 if ( !wxInitialize() )
4545 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4550 #endif // TEST_CHARSET
4553 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4555 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4556 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4558 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4559 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4560 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4561 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4563 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4564 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4569 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4571 parser
.AddOption("project_name", "", "full path to project file",
4572 wxCMD_LINE_VAL_STRING
,
4573 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4575 switch ( parser
.Parse() )
4578 wxLogMessage("Help was given, terminating.");
4582 ShowCmdLine(parser
);
4586 wxLogMessage("Syntax error detected, aborting.");
4589 #endif // TEST_CMDLINE
4600 TestStringConstruction();
4603 TestStringTokenizer();
4604 TestStringReplace();
4606 #endif // TEST_STRINGS
4619 puts("*** Initially:");
4621 PrintArray("a1", a1
);
4623 wxArrayString
a2(a1
);
4624 PrintArray("a2", a2
);
4626 wxSortedArrayString
a3(a1
);
4627 PrintArray("a3", a3
);
4629 puts("*** After deleting a string from a1");
4632 PrintArray("a1", a1
);
4633 PrintArray("a2", a2
);
4634 PrintArray("a3", a3
);
4636 puts("*** After reassigning a1 to a2 and a3");
4638 PrintArray("a2", a2
);
4639 PrintArray("a3", a3
);
4641 puts("*** After sorting a1");
4643 PrintArray("a1", a1
);
4645 puts("*** After sorting a1 in reverse order");
4647 PrintArray("a1", a1
);
4649 puts("*** After sorting a1 by the string length");
4650 a1
.Sort(StringLenCompare
);
4651 PrintArray("a1", a1
);
4653 TestArrayOfObjects();
4656 #endif // TEST_ARRAYS
4664 #ifdef TEST_DLLLOADER
4666 #endif // TEST_DLLLOADER
4670 #endif // TEST_ENVIRON
4674 #endif // TEST_EXECUTE
4676 #ifdef TEST_FILECONF
4678 #endif // TEST_FILECONF
4686 #endif // TEST_LOCALE
4690 for ( size_t n
= 0; n
< 8000; n
++ )
4692 s
<< (char)('A' + (n
% 26));
4696 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4698 // this one shouldn't be truncated
4701 // but this one will because log functions use fixed size buffer
4702 // (note that it doesn't need '\n' at the end neither - will be added
4704 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4716 #ifdef TEST_FILENAME
4717 TestFileNameSplit();
4720 TestFileNameConstruction();
4722 TestFileNameComparison();
4723 TestFileNameOperations();
4725 #endif // TEST_FILENAME
4728 int nCPUs
= wxThread::GetCPUCount();
4729 printf("This system has %d CPUs\n", nCPUs
);
4731 wxThread::SetConcurrency(nCPUs
);
4733 if ( argc
> 1 && argv
[1][0] == 't' )
4734 wxLog::AddTraceMask("thread");
4737 TestDetachedThreads();
4739 TestJoinableThreads();
4741 TestThreadSuspend();
4745 #endif // TEST_THREADS
4747 #ifdef TEST_LONGLONG
4748 // seed pseudo random generator
4749 srand((unsigned)time(NULL
));
4757 TestMultiplication();
4760 TestLongLongConversion();
4761 TestBitOperations();
4763 TestLongLongComparison();
4764 #endif // TEST_LONGLONG
4771 wxLog::AddTraceMask(_T("mime"));
4779 TestMimeAssociate();
4782 #ifdef TEST_INFO_FUNCTIONS
4785 #endif // TEST_INFO_FUNCTIONS
4787 #ifdef TEST_PATHLIST
4789 #endif // TEST_PATHLIST
4793 #endif // TEST_REGCONF
4795 #ifdef TEST_REGISTRY
4798 TestRegistryAssociation();
4799 #endif // TEST_REGISTRY
4807 #endif // TEST_SOCKETS
4810 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4811 if ( TestFtpConnect() )
4822 TestFtpInteractive();
4824 //else: connecting to the FTP server failed
4834 #endif // TEST_STREAMS
4838 #endif // TEST_TIMER
4840 #ifdef TEST_DATETIME
4853 TestTimeArithmetics();
4860 TestTimeSpanFormat();
4862 TestDateTimeInteractive();
4863 #endif // TEST_DATETIME
4866 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4868 #endif // TEST_USLEEP
4874 #endif // TEST_VCARD
4878 #endif // TEST_WCHAR
4882 TestZipStreamRead();
4883 TestZipFileSystem();
4888 TestZlibStreamWrite();
4889 TestZlibStreamRead();