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)?
43 #define TEST_DLLLOADER
51 #define TEST_INFO_FUNCTIONS
66 //#define TEST_VCARD -- don't enable this (VZ)
72 #include <wx/snglinst.h>
73 #endif // TEST_SNGLINST
75 // ----------------------------------------------------------------------------
76 // test class for container objects
77 // ----------------------------------------------------------------------------
79 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
81 class Bar
// Foo is already taken in the hash test
84 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
87 static size_t GetNumber() { return ms_bars
; }
89 const char *GetName() const { return m_name
; }
94 static size_t ms_bars
;
97 size_t Bar::ms_bars
= 0;
99 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
101 // ============================================================================
103 // ============================================================================
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
111 // replace TABs with \t and CRs with \n
112 static wxString
MakePrintable(const wxChar
*s
)
115 (void)str
.Replace(_T("\t"), _T("\\t"));
116 (void)str
.Replace(_T("\n"), _T("\\n"));
117 (void)str
.Replace(_T("\r"), _T("\\r"));
122 #endif // MakePrintable() is used
124 // ----------------------------------------------------------------------------
125 // wxFontMapper::CharsetToEncoding
126 // ----------------------------------------------------------------------------
130 #include <wx/fontmap.h>
132 static void TestCharset()
134 static const wxChar
*charsets
[] =
136 // some vali charsets
145 // and now some bogus ones
152 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
154 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
155 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
157 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
158 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
162 #endif // TEST_CHARSET
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
170 #include <wx/cmdline.h>
171 #include <wx/datetime.h>
173 static void ShowCmdLine(const wxCmdLineParser
& parser
)
175 wxString s
= "Input files: ";
177 size_t count
= parser
.GetParamCount();
178 for ( size_t param
= 0; param
< count
; param
++ )
180 s
<< parser
.GetParam(param
) << ' ';
184 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
185 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
190 if ( parser
.Found("o", &strVal
) )
191 s
<< "Output file:\t" << strVal
<< '\n';
192 if ( parser
.Found("i", &strVal
) )
193 s
<< "Input dir:\t" << strVal
<< '\n';
194 if ( parser
.Found("s", &lVal
) )
195 s
<< "Size:\t" << lVal
<< '\n';
196 if ( parser
.Found("d", &dt
) )
197 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
198 if ( parser
.Found("project_name", &strVal
) )
199 s
<< "Project:\t" << strVal
<< '\n';
204 #endif // TEST_CMDLINE
206 // ----------------------------------------------------------------------------
208 // ----------------------------------------------------------------------------
215 static const wxChar
*ROOTDIR
= _T("/");
216 static const wxChar
*TESTDIR
= _T("/usr");
217 #elif defined(__WXMSW__)
218 static const wxChar
*ROOTDIR
= _T("c:\\");
219 static const wxChar
*TESTDIR
= _T("d:\\");
221 #error "don't know where the root directory is"
224 static void TestDirEnumHelper(wxDir
& dir
,
225 int flags
= wxDIR_DEFAULT
,
226 const wxString
& filespec
= wxEmptyString
)
230 if ( !dir
.IsOpened() )
233 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
236 printf("\t%s\n", filename
.c_str());
238 cont
= dir
.GetNext(&filename
);
244 static void TestDirEnum()
246 puts("*** Testing wxDir::GetFirst/GetNext ***");
248 wxDir
dir(wxGetCwd());
250 puts("Enumerating everything in current directory:");
251 TestDirEnumHelper(dir
);
253 puts("Enumerating really everything in current directory:");
254 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
256 puts("Enumerating object files in current directory:");
257 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
259 puts("Enumerating directories in current directory:");
260 TestDirEnumHelper(dir
, wxDIR_DIRS
);
262 puts("Enumerating files in current directory:");
263 TestDirEnumHelper(dir
, wxDIR_FILES
);
265 puts("Enumerating files including hidden in current directory:");
266 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
270 puts("Enumerating everything in root directory:");
271 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
273 puts("Enumerating directories in root directory:");
274 TestDirEnumHelper(dir
, wxDIR_DIRS
);
276 puts("Enumerating files in root directory:");
277 TestDirEnumHelper(dir
, wxDIR_FILES
);
279 puts("Enumerating files including hidden in root directory:");
280 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
282 puts("Enumerating files in non existing directory:");
283 wxDir
dirNo("nosuchdir");
284 TestDirEnumHelper(dirNo
);
287 class DirPrintTraverser
: public wxDirTraverser
290 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
292 return wxDIR_CONTINUE
;
295 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
297 wxString path
, name
, ext
;
298 wxSplitPath(dirname
, &path
, &name
, &ext
);
301 name
<< _T('.') << ext
;
304 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
306 if ( wxIsPathSeparator(*p
) )
310 printf("%s%s\n", indent
.c_str(), name
.c_str());
312 return wxDIR_CONTINUE
;
316 static void TestDirTraverse()
318 puts("*** Testing wxDir::Traverse() ***");
322 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
323 printf("There are %u files under '%s'\n", n
, TESTDIR
);
326 printf("First one is '%s'\n", files
[0u].c_str());
327 printf(" last one is '%s'\n", files
[n
- 1].c_str());
330 // enum again with custom traverser
332 DirPrintTraverser traverser
;
333 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
338 // ----------------------------------------------------------------------------
340 // ----------------------------------------------------------------------------
342 #ifdef TEST_DLLLOADER
344 #include <wx/dynlib.h>
346 static void TestDllLoad()
348 #if defined(__WXMSW__)
349 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
350 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
351 #elif defined(__UNIX__)
352 // weird: using just libc.so does *not* work!
353 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
354 static const wxChar
*FUNC_NAME
= _T("strlen");
356 #error "don't know how to test wxDllLoader on this platform"
359 puts("*** testing wxDllLoader ***\n");
361 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
364 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
368 typedef int (*strlenType
)(char *);
369 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
372 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
373 FUNC_NAME
, LIB_NAME
);
377 if ( pfnStrlen("foo") != 3 )
379 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
387 wxDllLoader::UnloadLibrary(dllHandle
);
391 #endif // TEST_DLLLOADER
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
399 #include <wx/utils.h>
401 static wxString
MyGetEnv(const wxString
& var
)
404 if ( !wxGetEnv(var
, &val
) )
407 val
= wxString(_T('\'')) + val
+ _T('\'');
412 static void TestEnvironment()
414 const wxChar
*var
= _T("wxTestVar");
416 puts("*** testing environment access functions ***");
418 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
419 wxSetEnv(var
, _T("value for wxTestVar"));
420 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
421 wxSetEnv(var
, _T("another value"));
422 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
424 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
425 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
428 #endif // TEST_ENVIRON
430 // ----------------------------------------------------------------------------
432 // ----------------------------------------------------------------------------
436 #include <wx/utils.h>
438 static void TestExecute()
440 puts("*** testing wxExecute ***");
443 #define COMMAND "cat -n ../../Makefile" // "echo hi"
444 #define SHELL_COMMAND "echo hi from shell"
445 #define REDIRECT_COMMAND COMMAND // "date"
446 #elif defined(__WXMSW__)
447 #define COMMAND "command.com -c 'echo hi'"
448 #define SHELL_COMMAND "echo hi"
449 #define REDIRECT_COMMAND COMMAND
451 #error "no command to exec"
454 printf("Testing wxShell: ");
456 if ( wxShell(SHELL_COMMAND
) )
461 printf("Testing wxExecute: ");
463 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
468 #if 0 // no, it doesn't work (yet?)
469 printf("Testing async wxExecute: ");
471 if ( wxExecute(COMMAND
) != 0 )
472 puts("Ok (command launched).");
477 printf("Testing wxExecute with redirection:\n");
478 wxArrayString output
;
479 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
485 size_t count
= output
.GetCount();
486 for ( size_t n
= 0; n
< count
; n
++ )
488 printf("\t%s\n", output
[n
].c_str());
495 #endif // TEST_EXECUTE
497 // ----------------------------------------------------------------------------
499 // ----------------------------------------------------------------------------
504 #include <wx/ffile.h>
505 #include <wx/textfile.h>
507 static void TestFileRead()
509 puts("*** wxFile read test ***");
511 wxFile
file(_T("testdata.fc"));
512 if ( file
.IsOpened() )
514 printf("File length: %lu\n", file
.Length());
516 puts("File dump:\n----------");
518 static const off_t len
= 1024;
522 off_t nRead
= file
.Read(buf
, len
);
523 if ( nRead
== wxInvalidOffset
)
525 printf("Failed to read the file.");
529 fwrite(buf
, nRead
, 1, stdout
);
539 printf("ERROR: can't open test file.\n");
545 static void TestTextFileRead()
547 puts("*** wxTextFile read test ***");
549 wxTextFile
file(_T("testdata.fc"));
552 printf("Number of lines: %u\n", file
.GetLineCount());
553 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
557 puts("\nDumping the entire file:");
558 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
560 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
562 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
564 puts("\nAnd now backwards:");
565 for ( s
= file
.GetLastLine();
566 file
.GetCurrentLine() != 0;
567 s
= file
.GetPrevLine() )
569 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
571 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
575 printf("ERROR: can't open '%s'\n", file
.GetName());
581 static void TestFileCopy()
583 puts("*** Testing wxCopyFile ***");
585 static const wxChar
*filename1
= _T("testdata.fc");
586 static const wxChar
*filename2
= _T("test2");
587 if ( !wxCopyFile(filename1
, filename2
) )
589 puts("ERROR: failed to copy file");
593 wxFFile
f1(filename1
, "rb"),
596 if ( !f1
.IsOpened() || !f2
.IsOpened() )
598 puts("ERROR: failed to open file(s)");
603 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
605 puts("ERROR: failed to read file(s)");
609 if ( (s1
.length() != s2
.length()) ||
610 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
612 puts("ERROR: copy error!");
616 puts("File was copied ok.");
622 if ( !wxRemoveFile(filename2
) )
624 puts("ERROR: failed to remove the file");
632 // ----------------------------------------------------------------------------
634 // ----------------------------------------------------------------------------
638 #include <wx/confbase.h>
639 #include <wx/fileconf.h>
641 static const struct FileConfTestData
643 const wxChar
*name
; // value name
644 const wxChar
*value
; // the value from the file
647 { _T("value1"), _T("one") },
648 { _T("value2"), _T("two") },
649 { _T("novalue"), _T("default") },
652 static void TestFileConfRead()
654 puts("*** testing wxFileConfig loading/reading ***");
656 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
657 _T("testdata.fc"), wxEmptyString
,
658 wxCONFIG_USE_RELATIVE_PATH
);
660 // test simple reading
661 puts("\nReading config file:");
662 wxString
defValue(_T("default")), value
;
663 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
665 const FileConfTestData
& data
= fcTestData
[n
];
666 value
= fileconf
.Read(data
.name
, defValue
);
667 printf("\t%s = %s ", data
.name
, value
.c_str());
668 if ( value
== data
.value
)
674 printf("(ERROR: should be %s)\n", data
.value
);
678 // test enumerating the entries
679 puts("\nEnumerating all root entries:");
682 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
685 printf("\t%s = %s\n",
687 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
689 cont
= fileconf
.GetNextEntry(name
, dummy
);
693 #endif // TEST_FILECONF
695 // ----------------------------------------------------------------------------
697 // ----------------------------------------------------------------------------
701 #include <wx/filename.h>
703 static struct FileNameInfo
705 const wxChar
*fullname
;
711 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
712 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
713 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
714 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
715 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
716 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
717 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
718 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
721 static void TestFileNameConstruction()
723 puts("*** testing wxFileName construction ***");
725 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
727 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
729 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
730 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
732 puts("ERROR (couldn't be normalized)");
736 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
743 static void TestFileNameSplit()
745 puts("*** testing wxFileName splitting ***");
747 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
749 const FileNameInfo
&fni
= filenames
[n
];
750 wxString path
, name
, ext
;
751 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
753 printf("%s -> path = '%s', name = '%s', ext = '%s'",
754 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
755 if ( path
!= fni
.path
)
756 printf(" (ERROR: path = '%s')", fni
.path
);
757 if ( name
!= fni
.name
)
758 printf(" (ERROR: name = '%s')", fni
.name
);
759 if ( ext
!= fni
.ext
)
760 printf(" (ERROR: ext = '%s')", fni
.ext
);
767 static void TestFileNameComparison()
772 static void TestFileNameOperations()
777 static void TestFileNameCwd()
782 #endif // TEST_FILENAME
784 // ----------------------------------------------------------------------------
786 // ----------------------------------------------------------------------------
794 Foo(int n_
) { n
= n_
; count
++; }
802 size_t Foo::count
= 0;
804 WX_DECLARE_LIST(Foo
, wxListFoos
);
805 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
807 #include <wx/listimpl.cpp>
809 WX_DEFINE_LIST(wxListFoos
);
811 static void TestHash()
813 puts("*** Testing wxHashTable ***\n");
817 hash
.DeleteContents(TRUE
);
819 printf("Hash created: %u foos in hash, %u foos totally\n",
820 hash
.GetCount(), Foo::count
);
822 static const int hashTestData
[] =
824 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
828 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
830 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
833 printf("Hash filled: %u foos in hash, %u foos totally\n",
834 hash
.GetCount(), Foo::count
);
836 puts("Hash access test:");
837 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
839 printf("\tGetting element with key %d, value %d: ",
841 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
844 printf("ERROR, not found.\n");
848 printf("%d (%s)\n", foo
->n
,
849 (size_t)foo
->n
== n
? "ok" : "ERROR");
853 printf("\nTrying to get an element not in hash: ");
855 if ( hash
.Get(1234) || hash
.Get(1, 0) )
857 puts("ERROR: found!");
861 puts("ok (not found)");
865 printf("Hash destroyed: %u foos left\n", Foo::count
);
870 // ----------------------------------------------------------------------------
872 // ----------------------------------------------------------------------------
878 WX_DECLARE_LIST(Bar
, wxListBars
);
879 #include <wx/listimpl.cpp>
880 WX_DEFINE_LIST(wxListBars
);
882 static void TestListCtor()
884 puts("*** Testing wxList construction ***\n");
888 list1
.Append(new Bar(_T("first")));
889 list1
.Append(new Bar(_T("second")));
891 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
892 list1
.GetCount(), Bar::GetNumber());
897 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
898 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
900 list1
.DeleteContents(TRUE
);
903 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
908 // ----------------------------------------------------------------------------
910 // ----------------------------------------------------------------------------
915 #include "wx/utils.h" // for wxSetEnv
917 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
919 // find the name of the language from its value
920 static const char *GetLangName(int lang
)
922 static const char *languageNames
[] =
943 "ARABIC_SAUDI_ARABIA",
968 "CHINESE_SIMPLIFIED",
969 "CHINESE_TRADITIONAL",
991 "ENGLISH_NEW_ZEALAND",
992 "ENGLISH_PHILIPPINES",
993 "ENGLISH_SOUTH_AFRICA",
1005 "FRENCH_LUXEMBOURG",
1014 "GERMAN_LIECHTENSTEIN",
1015 "GERMAN_LUXEMBOURG",
1056 "MALAY_BRUNEI_DARUSSALAM",
1068 "NORWEGIAN_NYNORSK",
1075 "PORTUGUESE_BRAZILIAN",
1100 "SPANISH_ARGENTINA",
1104 "SPANISH_COSTA_RICA",
1105 "SPANISH_DOMINICAN_REPUBLIC",
1107 "SPANISH_EL_SALVADOR",
1108 "SPANISH_GUATEMALA",
1112 "SPANISH_NICARAGUA",
1116 "SPANISH_PUERTO_RICO",
1119 "SPANISH_VENEZUELA",
1156 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1157 return languageNames
[lang
];
1162 static void TestDefaultLang()
1164 puts("*** Testing wxLocale::GetSystemLanguage ***");
1166 static const wxChar
*langStrings
[] =
1168 NULL
, // system default
1175 _T("de_DE.iso88591"),
1177 _T("?"), // invalid lang spec
1178 _T("klingonese"), // I bet on some systems it does exist...
1181 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1182 wxLocale::GetSystemEncodingName().c_str(),
1183 wxLocale::GetSystemEncoding());
1185 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1187 const char *langStr
= langStrings
[n
];
1190 // FIXME: this doesn't do anything at all under Windows, we need
1191 // to create a new wxLocale!
1192 wxSetEnv(_T("LC_ALL"), langStr
);
1195 int lang
= gs_localeDefault
.GetSystemLanguage();
1196 printf("Locale for '%s' is %s.\n",
1197 langStr
? langStr
: "system default", GetLangName(lang
));
1201 #endif // TEST_LOCALE
1203 // ----------------------------------------------------------------------------
1205 // ----------------------------------------------------------------------------
1209 #include <wx/mimetype.h>
1211 static void TestMimeEnum()
1213 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1215 wxArrayString mimetypes
;
1217 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1219 printf("*** All %u known filetypes: ***\n", count
);
1224 for ( size_t n
= 0; n
< count
; n
++ )
1226 wxFileType
*filetype
=
1227 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1230 printf("nothing known about the filetype '%s'!\n",
1231 mimetypes
[n
].c_str());
1235 filetype
->GetDescription(&desc
);
1236 filetype
->GetExtensions(exts
);
1238 filetype
->GetIcon(NULL
);
1241 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1244 extsAll
<< _T(", ");
1248 printf("\t%s: %s (%s)\n",
1249 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1255 static void TestMimeOverride()
1257 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1259 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1260 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1262 if ( wxFile::Exists(mailcap
) )
1263 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1265 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1267 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1270 if ( wxFile::Exists(mimetypes
) )
1271 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1273 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1275 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1281 static void TestMimeFilename()
1283 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1285 static const wxChar
*filenames
[] =
1292 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1294 const wxString fname
= filenames
[n
];
1295 wxString ext
= fname
.AfterLast(_T('.'));
1296 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1299 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1304 if ( !ft
->GetDescription(&desc
) )
1305 desc
= _T("<no description>");
1308 if ( !ft
->GetOpenCommand(&cmd
,
1309 wxFileType::MessageParameters(fname
, _T(""))) )
1310 cmd
= _T("<no command available>");
1312 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1313 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1322 static void TestMimeAssociate()
1324 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1326 wxFileTypeInfo
ftInfo(
1327 _T("application/x-xyz"),
1328 _T("xyzview '%s'"), // open cmd
1329 _T(""), // print cmd
1330 _T("XYZ File") // description
1331 _T(".xyz"), // extensions
1332 NULL
// end of extensions
1334 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1336 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1339 wxPuts(_T("ERROR: failed to create association!"));
1343 // TODO: read it back
1352 // ----------------------------------------------------------------------------
1353 // misc information functions
1354 // ----------------------------------------------------------------------------
1356 #ifdef TEST_INFO_FUNCTIONS
1358 #include <wx/utils.h>
1360 static void TestOsInfo()
1362 puts("*** Testing OS info functions ***\n");
1365 wxGetOsVersion(&major
, &minor
);
1366 printf("Running under: %s, version %d.%d\n",
1367 wxGetOsDescription().c_str(), major
, minor
);
1369 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1371 printf("Host name is %s (%s).\n",
1372 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1377 static void TestUserInfo()
1379 puts("*** Testing user info functions ***\n");
1381 printf("User id is:\t%s\n", wxGetUserId().c_str());
1382 printf("User name is:\t%s\n", wxGetUserName().c_str());
1383 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1384 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1389 #endif // TEST_INFO_FUNCTIONS
1391 // ----------------------------------------------------------------------------
1393 // ----------------------------------------------------------------------------
1395 #ifdef TEST_LONGLONG
1397 #include <wx/longlong.h>
1398 #include <wx/timer.h>
1400 // make a 64 bit number from 4 16 bit ones
1401 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1403 // get a random 64 bit number
1404 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1406 #if wxUSE_LONGLONG_WX
1407 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1408 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1409 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1410 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1411 #endif // wxUSE_LONGLONG_WX
1413 static void TestSpeed()
1415 static const long max
= 100000000;
1422 for ( n
= 0; n
< max
; n
++ )
1427 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1430 #if wxUSE_LONGLONG_NATIVE
1435 for ( n
= 0; n
< max
; n
++ )
1440 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1442 #endif // wxUSE_LONGLONG_NATIVE
1448 for ( n
= 0; n
< max
; n
++ )
1453 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1457 static void TestLongLongConversion()
1459 puts("*** Testing wxLongLong conversions ***\n");
1463 for ( size_t n
= 0; n
< 100000; n
++ )
1467 #if wxUSE_LONGLONG_NATIVE
1468 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1470 wxASSERT_MSG( a
== b
, "conversions failure" );
1472 puts("Can't do it without native long long type, test skipped.");
1475 #endif // wxUSE_LONGLONG_NATIVE
1477 if ( !(nTested
% 1000) )
1489 static void TestMultiplication()
1491 puts("*** Testing wxLongLong multiplication ***\n");
1495 for ( size_t n
= 0; n
< 100000; n
++ )
1500 #if wxUSE_LONGLONG_NATIVE
1501 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1502 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1504 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1505 #else // !wxUSE_LONGLONG_NATIVE
1506 puts("Can't do it without native long long type, test skipped.");
1509 #endif // wxUSE_LONGLONG_NATIVE
1511 if ( !(nTested
% 1000) )
1523 static void TestDivision()
1525 puts("*** Testing wxLongLong division ***\n");
1529 for ( size_t n
= 0; n
< 100000; n
++ )
1531 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1532 // multiplication will not overflow)
1533 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1535 // get a random long (not wxLongLong for now) to divide it with
1540 #if wxUSE_LONGLONG_NATIVE
1541 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1543 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1544 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1545 #else // !wxUSE_LONGLONG_NATIVE
1546 // verify the result
1547 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1548 #endif // wxUSE_LONGLONG_NATIVE
1550 if ( !(nTested
% 1000) )
1562 static void TestAddition()
1564 puts("*** Testing wxLongLong addition ***\n");
1568 for ( size_t n
= 0; n
< 100000; n
++ )
1574 #if wxUSE_LONGLONG_NATIVE
1575 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1576 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1577 "addition failure" );
1578 #else // !wxUSE_LONGLONG_NATIVE
1579 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1580 #endif // wxUSE_LONGLONG_NATIVE
1582 if ( !(nTested
% 1000) )
1594 static void TestBitOperations()
1596 puts("*** Testing wxLongLong bit operation ***\n");
1600 for ( size_t n
= 0; n
< 100000; n
++ )
1604 #if wxUSE_LONGLONG_NATIVE
1605 for ( size_t n
= 0; n
< 33; n
++ )
1608 #else // !wxUSE_LONGLONG_NATIVE
1609 puts("Can't do it without native long long type, test skipped.");
1612 #endif // wxUSE_LONGLONG_NATIVE
1614 if ( !(nTested
% 1000) )
1626 static void TestLongLongComparison()
1628 #if wxUSE_LONGLONG_WX
1629 puts("*** Testing wxLongLong comparison ***\n");
1631 static const long testLongs
[] =
1642 static const long ls
[2] =
1648 wxLongLongWx lls
[2];
1652 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1656 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1658 res
= lls
[m
] > testLongs
[n
];
1659 printf("0x%lx > 0x%lx is %s (%s)\n",
1660 ls
[m
], testLongs
[n
], res
? "true" : "false",
1661 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1663 res
= lls
[m
] < testLongs
[n
];
1664 printf("0x%lx < 0x%lx is %s (%s)\n",
1665 ls
[m
], testLongs
[n
], res
? "true" : "false",
1666 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1668 res
= lls
[m
] == testLongs
[n
];
1669 printf("0x%lx == 0x%lx is %s (%s)\n",
1670 ls
[m
], testLongs
[n
], res
? "true" : "false",
1671 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1674 #endif // wxUSE_LONGLONG_WX
1680 #endif // TEST_LONGLONG
1682 // ----------------------------------------------------------------------------
1684 // ----------------------------------------------------------------------------
1686 #ifdef TEST_PATHLIST
1688 static void TestPathList()
1690 puts("*** Testing wxPathList ***\n");
1692 wxPathList pathlist
;
1693 pathlist
.AddEnvList("PATH");
1694 wxString path
= pathlist
.FindValidPath("ls");
1697 printf("ERROR: command not found in the path.\n");
1701 printf("Command found in the path as '%s'.\n", path
.c_str());
1705 #endif // TEST_PATHLIST
1707 // ----------------------------------------------------------------------------
1708 // registry and related stuff
1709 // ----------------------------------------------------------------------------
1711 // this is for MSW only
1714 #undef TEST_REGISTRY
1719 #include <wx/confbase.h>
1720 #include <wx/msw/regconf.h>
1722 static void TestRegConfWrite()
1724 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1725 regconf
.Write(_T("Hello"), wxString(_T("world")));
1728 #endif // TEST_REGCONF
1730 #ifdef TEST_REGISTRY
1732 #include <wx/msw/registry.h>
1734 // I chose this one because I liked its name, but it probably only exists under
1736 static const wxChar
*TESTKEY
=
1737 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1739 static void TestRegistryRead()
1741 puts("*** testing registry reading ***");
1743 wxRegKey
key(TESTKEY
);
1744 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1747 puts("ERROR: test key can't be opened, aborting test.");
1752 size_t nSubKeys
, nValues
;
1753 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1755 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1758 printf("Enumerating values:\n");
1762 bool cont
= key
.GetFirstValue(value
, dummy
);
1765 printf("Value '%s': type ", value
.c_str());
1766 switch ( key
.GetValueType(value
) )
1768 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1769 case wxRegKey::Type_String
: printf("SZ"); break;
1770 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1771 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1772 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1773 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1774 default: printf("other (unknown)"); break;
1777 printf(", value = ");
1778 if ( key
.IsNumericValue(value
) )
1781 key
.QueryValue(value
, &val
);
1787 key
.QueryValue(value
, val
);
1788 printf("'%s'", val
.c_str());
1790 key
.QueryRawValue(value
, val
);
1791 printf(" (raw value '%s')", val
.c_str());
1796 cont
= key
.GetNextValue(value
, dummy
);
1800 static void TestRegistryAssociation()
1803 The second call to deleteself genertaes an error message, with a
1804 messagebox saying .flo is crucial to system operation, while the .ddf
1805 call also fails, but with no error message
1810 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1812 key
= "ddxf_auto_file" ;
1813 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1815 key
= "ddxf_auto_file" ;
1816 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1819 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1821 key
= "program \"%1\"" ;
1823 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1825 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1827 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1829 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1833 #endif // TEST_REGISTRY
1835 // ----------------------------------------------------------------------------
1837 // ----------------------------------------------------------------------------
1841 #include <wx/socket.h>
1842 #include <wx/protocol/protocol.h>
1843 #include <wx/protocol/http.h>
1845 static void TestSocketServer()
1847 puts("*** Testing wxSocketServer ***\n");
1849 static const int PORT
= 3000;
1854 wxSocketServer
*server
= new wxSocketServer(addr
);
1855 if ( !server
->Ok() )
1857 puts("ERROR: failed to bind");
1864 printf("Server: waiting for connection on port %d...\n", PORT
);
1866 wxSocketBase
*socket
= server
->Accept();
1869 puts("ERROR: wxSocketServer::Accept() failed.");
1873 puts("Server: got a client.");
1875 server
->SetTimeout(60); // 1 min
1877 while ( socket
->IsConnected() )
1883 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1885 // don't log error if the client just close the connection
1886 if ( socket
->IsConnected() )
1888 puts("ERROR: in wxSocket::Read.");
1908 printf("Server: got '%s'.\n", s
.c_str());
1909 if ( s
== _T("bye") )
1916 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1917 socket
->Write("\r\n", 2);
1918 printf("Server: wrote '%s'.\n", s
.c_str());
1921 puts("Server: lost a client.");
1926 // same as "delete server" but is consistent with GUI programs
1930 static void TestSocketClient()
1932 puts("*** Testing wxSocketClient ***\n");
1934 static const char *hostname
= "www.wxwindows.org";
1937 addr
.Hostname(hostname
);
1940 printf("--- Attempting to connect to %s:80...\n", hostname
);
1942 wxSocketClient client
;
1943 if ( !client
.Connect(addr
) )
1945 printf("ERROR: failed to connect to %s\n", hostname
);
1949 printf("--- Connected to %s:%u...\n",
1950 addr
.Hostname().c_str(), addr
.Service());
1954 // could use simply "GET" here I suppose
1956 wxString::Format("GET http://%s/\r\n", hostname
);
1957 client
.Write(cmdGet
, cmdGet
.length());
1958 printf("--- Sent command '%s' to the server\n",
1959 MakePrintable(cmdGet
).c_str());
1960 client
.Read(buf
, WXSIZEOF(buf
));
1961 printf("--- Server replied:\n%s", buf
);
1965 #endif // TEST_SOCKETS
1967 // ----------------------------------------------------------------------------
1969 // ----------------------------------------------------------------------------
1973 #include <wx/protocol/ftp.h>
1977 #define FTP_ANONYMOUS
1979 #ifdef FTP_ANONYMOUS
1980 static const char *directory
= "/pub";
1981 static const char *filename
= "welcome.msg";
1983 static const char *directory
= "/etc";
1984 static const char *filename
= "issue";
1987 static bool TestFtpConnect()
1989 puts("*** Testing FTP connect ***");
1991 #ifdef FTP_ANONYMOUS
1992 static const char *hostname
= "ftp.wxwindows.org";
1994 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1995 #else // !FTP_ANONYMOUS
1996 static const char *hostname
= "localhost";
1999 fgets(user
, WXSIZEOF(user
), stdin
);
2000 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2004 printf("Password for %s: ", password
);
2005 fgets(password
, WXSIZEOF(password
), stdin
);
2006 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2007 ftp
.SetPassword(password
);
2009 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2010 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2012 if ( !ftp
.Connect(hostname
) )
2014 printf("ERROR: failed to connect to %s\n", hostname
);
2020 printf("--- Connected to %s, current directory is '%s'\n",
2021 hostname
, ftp
.Pwd().c_str());
2027 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2028 static void TestFtpWuFtpd()
2031 static const char *hostname
= "ftp.eudora.com";
2032 if ( !ftp
.Connect(hostname
) )
2034 printf("ERROR: failed to connect to %s\n", hostname
);
2038 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2039 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2042 printf("ERROR: couldn't get input stream for %s\n", filename
);
2046 size_t size
= in
->StreamSize();
2047 printf("Reading file %s (%u bytes)...", filename
, size
);
2049 char *data
= new char[size
];
2050 if ( !in
->Read(data
, size
) )
2052 puts("ERROR: read error");
2056 printf("Successfully retrieved the file.\n");
2065 static void TestFtpList()
2067 puts("*** Testing wxFTP file listing ***\n");
2070 if ( !ftp
.ChDir(directory
) )
2072 printf("ERROR: failed to cd to %s\n", directory
);
2075 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2077 // test NLIST and LIST
2078 wxArrayString files
;
2079 if ( !ftp
.GetFilesList(files
) )
2081 puts("ERROR: failed to get NLIST of files");
2085 printf("Brief 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
.GetDirList(files
) )
2096 puts("ERROR: failed to get LIST of files");
2100 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2101 size_t count
= files
.GetCount();
2102 for ( size_t n
= 0; n
< count
; n
++ )
2104 printf("\t%s\n", files
[n
].c_str());
2106 puts("End of the file list");
2109 if ( !ftp
.ChDir(_T("..")) )
2111 puts("ERROR: failed to cd to ..");
2114 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2117 static void TestFtpDownload()
2119 puts("*** Testing wxFTP download ***\n");
2122 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2125 printf("ERROR: couldn't get input stream for %s\n", filename
);
2129 size_t size
= in
->StreamSize();
2130 printf("Reading file %s (%u bytes)...", filename
, size
);
2133 char *data
= new char[size
];
2134 if ( !in
->Read(data
, size
) )
2136 puts("ERROR: read error");
2140 printf("\nContents of %s:\n%s\n", filename
, data
);
2148 static void TestFtpFileSize()
2150 puts("*** Testing FTP SIZE command ***");
2152 if ( !ftp
.ChDir(directory
) )
2154 printf("ERROR: failed to cd to %s\n", directory
);
2157 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2159 if ( ftp
.FileExists(filename
) )
2161 int size
= ftp
.GetFileSize(filename
);
2163 printf("ERROR: couldn't get size of '%s'\n", filename
);
2165 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2169 printf("ERROR: '%s' doesn't exist\n", filename
);
2173 static void TestFtpMisc()
2175 puts("*** Testing miscellaneous wxFTP functions ***");
2177 if ( ftp
.SendCommand("STAT") != '2' )
2179 puts("ERROR: STAT failed");
2183 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2186 if ( ftp
.SendCommand("HELP SITE") != '2' )
2188 puts("ERROR: HELP SITE failed");
2192 printf("The list of site-specific commands:\n\n%s\n",
2193 ftp
.GetLastResult().c_str());
2197 static void TestFtpInteractive()
2199 puts("\n*** Interactive wxFTP test ***");
2205 printf("Enter FTP command: ");
2206 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2209 // kill the last '\n'
2210 buf
[strlen(buf
) - 1] = 0;
2212 // special handling of LIST and NLST as they require data connection
2213 wxString
start(buf
, 4);
2215 if ( start
== "LIST" || start
== "NLST" )
2218 if ( strlen(buf
) > 4 )
2221 wxArrayString files
;
2222 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2224 printf("ERROR: failed to get %s of files\n", start
.c_str());
2228 printf("--- %s of '%s' under '%s':\n",
2229 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2230 size_t count
= files
.GetCount();
2231 for ( size_t n
= 0; n
< count
; n
++ )
2233 printf("\t%s\n", files
[n
].c_str());
2235 puts("--- End of the file list");
2240 char ch
= ftp
.SendCommand(buf
);
2241 printf("Command %s", ch
? "succeeded" : "failed");
2244 printf(" (return code %c)", ch
);
2247 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2251 puts("\n*** done ***");
2254 static void TestFtpUpload()
2256 puts("*** Testing wxFTP uploading ***\n");
2259 static const char *file1
= "test1";
2260 static const char *file2
= "test2";
2261 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2264 printf("--- Uploading to %s ---\n", file1
);
2265 out
->Write("First hello", 11);
2269 // send a command to check the remote file
2270 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2272 printf("ERROR: STAT %s failed\n", file1
);
2276 printf("STAT %s returned:\n\n%s\n",
2277 file1
, ftp
.GetLastResult().c_str());
2280 out
= ftp
.GetOutputStream(file2
);
2283 printf("--- Uploading to %s ---\n", file1
);
2284 out
->Write("Second hello", 12);
2291 // ----------------------------------------------------------------------------
2293 // ----------------------------------------------------------------------------
2297 #include <wx/wfstream.h>
2298 #include <wx/mstream.h>
2300 static void TestFileStream()
2302 puts("*** Testing wxFileInputStream ***");
2304 static const wxChar
*filename
= _T("testdata.fs");
2306 wxFileOutputStream
fsOut(filename
);
2307 fsOut
.Write("foo", 3);
2310 wxFileInputStream
fsIn(filename
);
2311 printf("File stream size: %u\n", fsIn
.GetSize());
2312 while ( !fsIn
.Eof() )
2314 putchar(fsIn
.GetC());
2317 if ( !wxRemoveFile(filename
) )
2319 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2322 puts("\n*** wxFileInputStream test done ***");
2325 static void TestMemoryStream()
2327 puts("*** Testing wxMemoryInputStream ***");
2330 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2332 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2333 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2334 while ( !memInpStream
.Eof() )
2336 putchar(memInpStream
.GetC());
2339 puts("\n*** wxMemoryInputStream test done ***");
2342 #endif // TEST_STREAMS
2344 // ----------------------------------------------------------------------------
2346 // ----------------------------------------------------------------------------
2350 #include <wx/timer.h>
2351 #include <wx/utils.h>
2353 static void TestStopWatch()
2355 puts("*** Testing wxStopWatch ***\n");
2358 printf("Sleeping 3 seconds...");
2360 printf("\telapsed time: %ldms\n", sw
.Time());
2363 printf("Sleeping 2 more seconds...");
2365 printf("\telapsed time: %ldms\n", sw
.Time());
2368 printf("And 3 more seconds...");
2370 printf("\telapsed time: %ldms\n", sw
.Time());
2373 puts("\nChecking for 'backwards clock' bug...");
2374 for ( size_t n
= 0; n
< 70; n
++ )
2378 for ( size_t m
= 0; m
< 100000; m
++ )
2380 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2382 puts("\ntime is negative - ERROR!");
2392 #endif // TEST_TIMER
2394 // ----------------------------------------------------------------------------
2396 // ----------------------------------------------------------------------------
2400 #include <wx/vcard.h>
2402 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2405 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2409 wxString(_T('\t'), level
).c_str(),
2410 vcObj
->GetName().c_str());
2413 switch ( vcObj
->GetType() )
2415 case wxVCardObject::String
:
2416 case wxVCardObject::UString
:
2419 vcObj
->GetValue(&val
);
2420 value
<< _T('"') << val
<< _T('"');
2424 case wxVCardObject::Int
:
2427 vcObj
->GetValue(&i
);
2428 value
.Printf(_T("%u"), i
);
2432 case wxVCardObject::Long
:
2435 vcObj
->GetValue(&l
);
2436 value
.Printf(_T("%lu"), l
);
2440 case wxVCardObject::None
:
2443 case wxVCardObject::Object
:
2444 value
= _T("<node>");
2448 value
= _T("<unknown value type>");
2452 printf(" = %s", value
.c_str());
2455 DumpVObject(level
+ 1, *vcObj
);
2458 vcObj
= vcard
.GetNextProp(&cookie
);
2462 static void DumpVCardAddresses(const wxVCard
& vcard
)
2464 puts("\nShowing all addresses from vCard:\n");
2468 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2472 int flags
= addr
->GetFlags();
2473 if ( flags
& wxVCardAddress::Domestic
)
2475 flagsStr
<< _T("domestic ");
2477 if ( flags
& wxVCardAddress::Intl
)
2479 flagsStr
<< _T("international ");
2481 if ( flags
& wxVCardAddress::Postal
)
2483 flagsStr
<< _T("postal ");
2485 if ( flags
& wxVCardAddress::Parcel
)
2487 flagsStr
<< _T("parcel ");
2489 if ( flags
& wxVCardAddress::Home
)
2491 flagsStr
<< _T("home ");
2493 if ( flags
& wxVCardAddress::Work
)
2495 flagsStr
<< _T("work ");
2498 printf("Address %u:\n"
2500 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2503 addr
->GetPostOffice().c_str(),
2504 addr
->GetExtAddress().c_str(),
2505 addr
->GetStreet().c_str(),
2506 addr
->GetLocality().c_str(),
2507 addr
->GetRegion().c_str(),
2508 addr
->GetPostalCode().c_str(),
2509 addr
->GetCountry().c_str()
2513 addr
= vcard
.GetNextAddress(&cookie
);
2517 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2519 puts("\nShowing all phone numbers from vCard:\n");
2523 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2527 int flags
= phone
->GetFlags();
2528 if ( flags
& wxVCardPhoneNumber::Voice
)
2530 flagsStr
<< _T("voice ");
2532 if ( flags
& wxVCardPhoneNumber::Fax
)
2534 flagsStr
<< _T("fax ");
2536 if ( flags
& wxVCardPhoneNumber::Cellular
)
2538 flagsStr
<< _T("cellular ");
2540 if ( flags
& wxVCardPhoneNumber::Modem
)
2542 flagsStr
<< _T("modem ");
2544 if ( flags
& wxVCardPhoneNumber::Home
)
2546 flagsStr
<< _T("home ");
2548 if ( flags
& wxVCardPhoneNumber::Work
)
2550 flagsStr
<< _T("work ");
2553 printf("Phone number %u:\n"
2558 phone
->GetNumber().c_str()
2562 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2566 static void TestVCardRead()
2568 puts("*** Testing wxVCard reading ***\n");
2570 wxVCard
vcard(_T("vcard.vcf"));
2571 if ( !vcard
.IsOk() )
2573 puts("ERROR: couldn't load vCard.");
2577 // read individual vCard properties
2578 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2582 vcObj
->GetValue(&value
);
2587 value
= _T("<none>");
2590 printf("Full name retrieved directly: %s\n", value
.c_str());
2593 if ( !vcard
.GetFullName(&value
) )
2595 value
= _T("<none>");
2598 printf("Full name from wxVCard API: %s\n", value
.c_str());
2600 // now show how to deal with multiply occuring properties
2601 DumpVCardAddresses(vcard
);
2602 DumpVCardPhoneNumbers(vcard
);
2604 // and finally show all
2605 puts("\nNow dumping the entire vCard:\n"
2606 "-----------------------------\n");
2608 DumpVObject(0, vcard
);
2612 static void TestVCardWrite()
2614 puts("*** Testing wxVCard writing ***\n");
2617 if ( !vcard
.IsOk() )
2619 puts("ERROR: couldn't create vCard.");
2624 vcard
.SetName("Zeitlin", "Vadim");
2625 vcard
.SetFullName("Vadim Zeitlin");
2626 vcard
.SetOrganization("wxWindows", "R&D");
2628 // just dump the vCard back
2629 puts("Entire vCard follows:\n");
2630 puts(vcard
.Write());
2634 #endif // TEST_VCARD
2636 // ----------------------------------------------------------------------------
2637 // wide char (Unicode) support
2638 // ----------------------------------------------------------------------------
2642 #include <wx/strconv.h>
2643 #include <wx/fontenc.h>
2644 #include <wx/encconv.h>
2645 #include <wx/buffer.h>
2647 static void TestUtf8()
2649 puts("*** Testing UTF8 support ***\n");
2651 static const char textInUtf8
[] =
2653 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2654 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2655 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2656 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2657 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2658 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2659 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2664 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2666 puts("ERROR: UTF-8 decoding failed.");
2670 // using wxEncodingConverter
2672 wxEncodingConverter ec
;
2673 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2674 ec
.Convert(wbuf
, buf
);
2675 #else // using wxCSConv
2676 wxCSConv
conv(_T("koi8-r"));
2677 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2679 puts("ERROR: conversion to KOI8-R failed.");
2684 printf("The resulting string (in koi8-r): %s\n", buf
);
2688 #endif // TEST_WCHAR
2690 // ----------------------------------------------------------------------------
2692 // ----------------------------------------------------------------------------
2696 #include "wx/filesys.h"
2697 #include "wx/fs_zip.h"
2698 #include "wx/zipstrm.h"
2700 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2702 static void TestZipStreamRead()
2704 puts("*** Testing ZIP reading ***\n");
2706 static const wxChar
*filename
= _T("foo");
2707 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2708 printf("Archive size: %u\n", istr
.GetSize());
2710 printf("Dumping the file '%s':\n", filename
);
2711 while ( !istr
.Eof() )
2713 putchar(istr
.GetC());
2717 puts("\n----- done ------");
2720 static void DumpZipDirectory(wxFileSystem
& fs
,
2721 const wxString
& dir
,
2722 const wxString
& indent
)
2724 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2725 TESTFILE_ZIP
, dir
.c_str());
2726 wxString wildcard
= prefix
+ _T("/*");
2728 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2729 while ( !dirname
.empty() )
2731 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2733 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2738 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2740 DumpZipDirectory(fs
, dirname
,
2741 indent
+ wxString(_T(' '), 4));
2743 dirname
= fs
.FindNext();
2746 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2747 while ( !filename
.empty() )
2749 if ( !filename
.StartsWith(prefix
, &filename
) )
2751 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2756 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2758 filename
= fs
.FindNext();
2762 static void TestZipFileSystem()
2764 puts("*** Testing ZIP file system ***\n");
2766 wxFileSystem::AddHandler(new wxZipFSHandler
);
2768 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2770 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2775 // ----------------------------------------------------------------------------
2777 // ----------------------------------------------------------------------------
2781 #include <wx/zstream.h>
2782 #include <wx/wfstream.h>
2784 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2785 static const char *TEST_DATA
= "hello and hello again";
2787 static void TestZlibStreamWrite()
2789 puts("*** Testing Zlib stream reading ***\n");
2791 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2792 wxZlibOutputStream
ostr(fileOutStream
, 0);
2793 printf("Compressing the test string... ");
2794 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2797 puts("(ERROR: failed)");
2804 puts("\n----- done ------");
2807 static void TestZlibStreamRead()
2809 puts("*** Testing Zlib stream reading ***\n");
2811 wxFileInputStream
fileInStream(FILENAME_GZ
);
2812 wxZlibInputStream
istr(fileInStream
);
2813 printf("Archive size: %u\n", istr
.GetSize());
2815 puts("Dumping the file:");
2816 while ( !istr
.Eof() )
2818 putchar(istr
.GetC());
2822 puts("\n----- done ------");
2827 // ----------------------------------------------------------------------------
2829 // ----------------------------------------------------------------------------
2831 #ifdef TEST_DATETIME
2835 #include <wx/date.h>
2837 #include <wx/datetime.h>
2842 wxDateTime::wxDateTime_t day
;
2843 wxDateTime::Month month
;
2845 wxDateTime::wxDateTime_t hour
, min
, sec
;
2847 wxDateTime::WeekDay wday
;
2848 time_t gmticks
, ticks
;
2850 void Init(const wxDateTime::Tm
& tm
)
2859 gmticks
= ticks
= -1;
2862 wxDateTime
DT() const
2863 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2865 bool SameDay(const wxDateTime::Tm
& tm
) const
2867 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2870 wxString
Format() const
2873 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2875 wxDateTime::GetMonthName(month
).c_str(),
2877 abs(wxDateTime::ConvertYearToBC(year
)),
2878 year
> 0 ? "AD" : "BC");
2882 wxString
FormatDate() const
2885 s
.Printf("%02d-%s-%4d%s",
2887 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2888 abs(wxDateTime::ConvertYearToBC(year
)),
2889 year
> 0 ? "AD" : "BC");
2894 static const Date testDates
[] =
2896 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2897 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2898 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2899 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2900 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2901 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2902 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2903 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2904 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2905 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2906 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2907 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2908 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2909 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2910 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2913 // this test miscellaneous static wxDateTime functions
2914 static void TestTimeStatic()
2916 puts("\n*** wxDateTime static methods test ***");
2918 // some info about the current date
2919 int year
= wxDateTime::GetCurrentYear();
2920 printf("Current year %d is %sa leap one and has %d days.\n",
2922 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2923 wxDateTime::GetNumberOfDays(year
));
2925 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2926 printf("Current month is '%s' ('%s') and it has %d days\n",
2927 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2928 wxDateTime::GetMonthName(month
).c_str(),
2929 wxDateTime::GetNumberOfDays(month
));
2932 static const size_t nYears
= 5;
2933 static const size_t years
[2][nYears
] =
2935 // first line: the years to test
2936 { 1990, 1976, 2000, 2030, 1984, },
2938 // second line: TRUE if leap, FALSE otherwise
2939 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2942 for ( size_t n
= 0; n
< nYears
; n
++ )
2944 int year
= years
[0][n
];
2945 bool should
= years
[1][n
] != 0,
2946 is
= wxDateTime::IsLeapYear(year
);
2948 printf("Year %d is %sa leap year (%s)\n",
2951 should
== is
? "ok" : "ERROR");
2953 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2957 // test constructing wxDateTime objects
2958 static void TestTimeSet()
2960 puts("\n*** wxDateTime construction test ***");
2962 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2964 const Date
& d1
= testDates
[n
];
2965 wxDateTime dt
= d1
.DT();
2968 d2
.Init(dt
.GetTm());
2970 wxString s1
= d1
.Format(),
2973 printf("Date: %s == %s (%s)\n",
2974 s1
.c_str(), s2
.c_str(),
2975 s1
== s2
? "ok" : "ERROR");
2979 // test time zones stuff
2980 static void TestTimeZones()
2982 puts("\n*** wxDateTime timezone test ***");
2984 wxDateTime now
= wxDateTime::Now();
2986 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2987 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2988 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2989 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2990 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2991 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2993 wxDateTime::Tm tm
= now
.GetTm();
2994 if ( wxDateTime(tm
) != now
)
2996 printf("ERROR: got %s instead of %s\n",
2997 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3001 // test some minimal support for the dates outside the standard range
3002 static void TestTimeRange()
3004 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3006 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3008 printf("Unix epoch:\t%s\n",
3009 wxDateTime(2440587.5).Format(fmt
).c_str());
3010 printf("Feb 29, 0: \t%s\n",
3011 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3012 printf("JDN 0: \t%s\n",
3013 wxDateTime(0.0).Format(fmt
).c_str());
3014 printf("Jan 1, 1AD:\t%s\n",
3015 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3016 printf("May 29, 2099:\t%s\n",
3017 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3020 static void TestTimeTicks()
3022 puts("\n*** wxDateTime ticks test ***");
3024 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3026 const Date
& d
= testDates
[n
];
3027 if ( d
.ticks
== -1 )
3030 wxDateTime dt
= d
.DT();
3031 long ticks
= (dt
.GetValue() / 1000).ToLong();
3032 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3033 if ( ticks
== d
.ticks
)
3039 printf(" (ERROR: should be %ld, delta = %ld)\n",
3040 d
.ticks
, ticks
- d
.ticks
);
3043 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3044 ticks
= (dt
.GetValue() / 1000).ToLong();
3045 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3046 if ( ticks
== d
.gmticks
)
3052 printf(" (ERROR: should be %ld, delta = %ld)\n",
3053 d
.gmticks
, ticks
- d
.gmticks
);
3060 // test conversions to JDN &c
3061 static void TestTimeJDN()
3063 puts("\n*** wxDateTime to JDN test ***");
3065 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3067 const Date
& d
= testDates
[n
];
3068 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3069 double jdn
= dt
.GetJulianDayNumber();
3071 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3078 printf(" (ERROR: should be %f, delta = %f)\n",
3079 d
.jdn
, jdn
- d
.jdn
);
3084 // test week days computation
3085 static void TestTimeWDays()
3087 puts("\n*** wxDateTime weekday test ***");
3089 // test GetWeekDay()
3091 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3093 const Date
& d
= testDates
[n
];
3094 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3096 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3099 wxDateTime::GetWeekDayName(wday
).c_str());
3100 if ( wday
== d
.wday
)
3106 printf(" (ERROR: should be %s)\n",
3107 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3113 // test SetToWeekDay()
3114 struct WeekDateTestData
3116 Date date
; // the real date (precomputed)
3117 int nWeek
; // its week index in the month
3118 wxDateTime::WeekDay wday
; // the weekday
3119 wxDateTime::Month month
; // the month
3120 int year
; // and the year
3122 wxString
Format() const
3125 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3127 case 1: which
= "first"; break;
3128 case 2: which
= "second"; break;
3129 case 3: which
= "third"; break;
3130 case 4: which
= "fourth"; break;
3131 case 5: which
= "fifth"; break;
3133 case -1: which
= "last"; break;
3138 which
+= " from end";
3141 s
.Printf("The %s %s of %s in %d",
3143 wxDateTime::GetWeekDayName(wday
).c_str(),
3144 wxDateTime::GetMonthName(month
).c_str(),
3151 // the array data was generated by the following python program
3153 from DateTime import *
3154 from whrandom import *
3155 from string import *
3157 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3158 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3160 week = DateTimeDelta(7)
3163 year = randint(1900, 2100)
3164 month = randint(1, 12)
3165 day = randint(1, 28)
3166 dt = DateTime(year, month, day)
3167 wday = dt.day_of_week
3169 countFromEnd = choice([-1, 1])
3172 while dt.month is month:
3173 dt = dt - countFromEnd * week
3174 weekNum = weekNum + countFromEnd
3176 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3178 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3179 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3182 static const WeekDateTestData weekDatesTestData
[] =
3184 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3185 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3186 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3187 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3188 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3189 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3190 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3191 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3192 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3193 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3194 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3195 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3196 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3197 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3198 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3199 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3200 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3201 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3202 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3203 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3206 static const char *fmt
= "%d-%b-%Y";
3209 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3211 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3213 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3215 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3217 const Date
& d
= wd
.date
;
3218 if ( d
.SameDay(dt
.GetTm()) )
3224 dt
.Set(d
.day
, d
.month
, d
.year
);
3226 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3231 // test the computation of (ISO) week numbers
3232 static void TestTimeWNumber()
3234 puts("\n*** wxDateTime week number test ***");
3236 struct WeekNumberTestData
3238 Date date
; // the date
3239 wxDateTime::wxDateTime_t week
; // the week number in the year
3240 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3241 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3242 wxDateTime::wxDateTime_t dnum
; // day number in the year
3245 // data generated with the following python script:
3247 from DateTime import *
3248 from whrandom import *
3249 from string import *
3251 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3252 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3254 def GetMonthWeek(dt):
3255 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3256 if weekNumMonth < 0:
3257 weekNumMonth = weekNumMonth + 53
3260 def GetLastSundayBefore(dt):
3261 if dt.iso_week[2] == 7:
3264 return dt - DateTimeDelta(dt.iso_week[2])
3267 year = randint(1900, 2100)
3268 month = randint(1, 12)
3269 day = randint(1, 28)
3270 dt = DateTime(year, month, day)
3271 dayNum = dt.day_of_year
3272 weekNum = dt.iso_week[1]
3273 weekNumMonth = GetMonthWeek(dt)
3276 dtSunday = GetLastSundayBefore(dt)
3278 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3279 weekNumMonth2 = weekNumMonth2 + 1
3280 dtSunday = dtSunday - DateTimeDelta(7)
3282 data = { 'day': rjust(`day`, 2), \
3283 'month': monthNames[month - 1], \
3285 'weekNum': rjust(`weekNum`, 2), \
3286 'weekNumMonth': weekNumMonth, \
3287 'weekNumMonth2': weekNumMonth2, \
3288 'dayNum': rjust(`dayNum`, 3) }
3290 print " { { %(day)s, "\
3291 "wxDateTime::%(month)s, "\
3294 "%(weekNumMonth)s, "\
3295 "%(weekNumMonth2)s, "\
3296 "%(dayNum)s }," % data
3299 static const WeekNumberTestData weekNumberTestDates
[] =
3301 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3302 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3303 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3304 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3305 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3306 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3307 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3308 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3309 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3310 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3311 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3312 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3313 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3314 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3315 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3316 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3317 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3318 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3319 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3320 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3323 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3325 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3326 const Date
& d
= wn
.date
;
3328 wxDateTime dt
= d
.DT();
3330 wxDateTime::wxDateTime_t
3331 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3332 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3333 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3334 dnum
= dt
.GetDayOfYear();
3336 printf("%s: the day number is %d",
3337 d
.FormatDate().c_str(), dnum
);
3338 if ( dnum
== wn
.dnum
)
3344 printf(" (ERROR: should be %d)", wn
.dnum
);
3347 printf(", week in month is %d", wmon
);
3348 if ( wmon
== wn
.wmon
)
3354 printf(" (ERROR: should be %d)", wn
.wmon
);
3357 printf(" or %d", wmon2
);
3358 if ( wmon2
== wn
.wmon2
)
3364 printf(" (ERROR: should be %d)", wn
.wmon2
);
3367 printf(", week in year is %d", week
);
3368 if ( week
== wn
.week
)
3374 printf(" (ERROR: should be %d)\n", wn
.week
);
3379 // test DST calculations
3380 static void TestTimeDST()
3382 puts("\n*** wxDateTime DST test ***");
3384 printf("DST is%s in effect now.\n\n",
3385 wxDateTime::Now().IsDST() ? "" : " not");
3387 // taken from http://www.energy.ca.gov/daylightsaving.html
3388 static const Date datesDST
[2][2004 - 1900 + 1] =
3391 { 1, wxDateTime::Apr
, 1990 },
3392 { 7, wxDateTime::Apr
, 1991 },
3393 { 5, wxDateTime::Apr
, 1992 },
3394 { 4, wxDateTime::Apr
, 1993 },
3395 { 3, wxDateTime::Apr
, 1994 },
3396 { 2, wxDateTime::Apr
, 1995 },
3397 { 7, wxDateTime::Apr
, 1996 },
3398 { 6, wxDateTime::Apr
, 1997 },
3399 { 5, wxDateTime::Apr
, 1998 },
3400 { 4, wxDateTime::Apr
, 1999 },
3401 { 2, wxDateTime::Apr
, 2000 },
3402 { 1, wxDateTime::Apr
, 2001 },
3403 { 7, wxDateTime::Apr
, 2002 },
3404 { 6, wxDateTime::Apr
, 2003 },
3405 { 4, wxDateTime::Apr
, 2004 },
3408 { 28, wxDateTime::Oct
, 1990 },
3409 { 27, wxDateTime::Oct
, 1991 },
3410 { 25, wxDateTime::Oct
, 1992 },
3411 { 31, wxDateTime::Oct
, 1993 },
3412 { 30, wxDateTime::Oct
, 1994 },
3413 { 29, wxDateTime::Oct
, 1995 },
3414 { 27, wxDateTime::Oct
, 1996 },
3415 { 26, wxDateTime::Oct
, 1997 },
3416 { 25, wxDateTime::Oct
, 1998 },
3417 { 31, wxDateTime::Oct
, 1999 },
3418 { 29, wxDateTime::Oct
, 2000 },
3419 { 28, wxDateTime::Oct
, 2001 },
3420 { 27, wxDateTime::Oct
, 2002 },
3421 { 26, wxDateTime::Oct
, 2003 },
3422 { 31, wxDateTime::Oct
, 2004 },
3427 for ( year
= 1990; year
< 2005; year
++ )
3429 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3430 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3432 printf("DST period in the US for year %d: from %s to %s",
3433 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3435 size_t n
= year
- 1990;
3436 const Date
& dBegin
= datesDST
[0][n
];
3437 const Date
& dEnd
= datesDST
[1][n
];
3439 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3445 printf(" (ERROR: should be %s %d to %s %d)\n",
3446 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3447 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3453 for ( year
= 1990; year
< 2005; year
++ )
3455 printf("DST period in Europe for year %d: from %s to %s\n",
3457 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3458 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3462 // test wxDateTime -> text conversion
3463 static void TestTimeFormat()
3465 puts("\n*** wxDateTime formatting test ***");
3467 // some information may be lost during conversion, so store what kind
3468 // of info should we recover after a round trip
3471 CompareNone
, // don't try comparing
3472 CompareBoth
, // dates and times should be identical
3473 CompareDate
, // dates only
3474 CompareTime
// time only
3479 CompareKind compareKind
;
3481 } formatTestFormats
[] =
3483 { CompareBoth
, "---> %c" },
3484 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3485 { CompareBoth
, "Date is %x, time is %X" },
3486 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3487 { CompareNone
, "The day of year: %j, the week of year: %W" },
3488 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3491 static const Date formatTestDates
[] =
3493 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3494 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3496 // this test can't work for other centuries because it uses two digit
3497 // years in formats, so don't even try it
3498 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3499 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3500 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3504 // an extra test (as it doesn't depend on date, don't do it in the loop)
3505 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3507 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3511 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3512 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3514 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3515 printf("%s", s
.c_str());
3517 // what can we recover?
3518 int kind
= formatTestFormats
[n
].compareKind
;
3522 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3525 // converion failed - should it have?
3526 if ( kind
== CompareNone
)
3529 puts(" (ERROR: conversion back failed)");
3533 // should have parsed the entire string
3534 puts(" (ERROR: conversion back stopped too soon)");
3538 bool equal
= FALSE
; // suppress compilaer warning
3546 equal
= dt
.IsSameDate(dt2
);
3550 equal
= dt
.IsSameTime(dt2
);
3556 printf(" (ERROR: got back '%s' instead of '%s')\n",
3557 dt2
.Format().c_str(), dt
.Format().c_str());
3568 // test text -> wxDateTime conversion
3569 static void TestTimeParse()
3571 puts("\n*** wxDateTime parse test ***");
3573 struct ParseTestData
3580 static const ParseTestData parseTestDates
[] =
3582 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3583 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3586 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3588 const char *format
= parseTestDates
[n
].format
;
3590 printf("%s => ", format
);
3593 if ( dt
.ParseRfc822Date(format
) )
3595 printf("%s ", dt
.Format().c_str());
3597 if ( parseTestDates
[n
].good
)
3599 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3606 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3611 puts("(ERROR: bad format)");
3616 printf("bad format (%s)\n",
3617 parseTestDates
[n
].good
? "ERROR" : "ok");
3622 static void TestDateTimeInteractive()
3624 puts("\n*** interactive wxDateTime tests ***");
3630 printf("Enter a date: ");
3631 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3634 // kill the last '\n'
3635 buf
[strlen(buf
) - 1] = 0;
3638 const char *p
= dt
.ParseDate(buf
);
3641 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3647 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3650 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3651 dt
.Format("%b %d, %Y").c_str(),
3653 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3654 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3655 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3658 puts("\n*** done ***");
3661 static void TestTimeMS()
3663 puts("*** testing millisecond-resolution support in wxDateTime ***");
3665 wxDateTime dt1
= wxDateTime::Now(),
3666 dt2
= wxDateTime::UNow();
3668 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3669 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3670 printf("Dummy loop: ");
3671 for ( int i
= 0; i
< 6000; i
++ )
3673 //for ( int j = 0; j < 10; j++ )
3676 s
.Printf("%g", sqrt(i
));
3685 dt2
= wxDateTime::UNow();
3686 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3688 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3690 puts("\n*** done ***");
3693 static void TestTimeArithmetics()
3695 puts("\n*** testing arithmetic operations on wxDateTime ***");
3697 static const struct ArithmData
3699 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3700 : span(sp
), name(nam
) { }
3704 } testArithmData
[] =
3706 ArithmData(wxDateSpan::Day(), "day"),
3707 ArithmData(wxDateSpan::Week(), "week"),
3708 ArithmData(wxDateSpan::Month(), "month"),
3709 ArithmData(wxDateSpan::Year(), "year"),
3710 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3713 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3715 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3717 wxDateSpan span
= testArithmData
[n
].span
;
3721 const char *name
= testArithmData
[n
].name
;
3722 printf("%s + %s = %s, %s - %s = %s\n",
3723 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3724 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3726 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3727 if ( dt1
- span
== dt
)
3733 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3736 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3737 if ( dt2
+ span
== dt
)
3743 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3746 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3747 if ( dt2
+ 2*span
== dt1
)
3753 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3760 static void TestTimeHolidays()
3762 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3764 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3765 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3766 dtEnd
= dtStart
.GetLastMonthDay();
3768 wxDateTimeArray hol
;
3769 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3771 const wxChar
*format
= "%d-%b-%Y (%a)";
3773 printf("All holidays between %s and %s:\n",
3774 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3776 size_t count
= hol
.GetCount();
3777 for ( size_t n
= 0; n
< count
; n
++ )
3779 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3785 static void TestTimeZoneBug()
3787 puts("\n*** testing for DST/timezone bug ***\n");
3789 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3790 for ( int i
= 0; i
< 31; i
++ )
3792 printf("Date %s: week day %s.\n",
3793 date
.Format(_T("%d-%m-%Y")).c_str(),
3794 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3796 date
+= wxDateSpan::Day();
3802 static void TestTimeSpanFormat()
3804 puts("\n*** wxTimeSpan tests ***");
3806 static const char *formats
[] =
3808 _T("(default) %H:%M:%S"),
3809 _T("%E weeks and %D days"),
3810 _T("%l milliseconds"),
3811 _T("(with ms) %H:%M:%S:%l"),
3812 _T("100%% of minutes is %M"), // test "%%"
3813 _T("%D days and %H hours"),
3816 wxTimeSpan
ts1(1, 2, 3, 4),
3818 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3820 printf("ts1 = %s\tts2 = %s\n",
3821 ts1
.Format(formats
[n
]).c_str(),
3822 ts2
.Format(formats
[n
]).c_str());
3830 // test compatibility with the old wxDate/wxTime classes
3831 static void TestTimeCompatibility()
3833 puts("\n*** wxDateTime compatibility test ***");
3835 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3836 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3838 double jdnNow
= wxDateTime::Now().GetJDN();
3839 long jdnMidnight
= (long)(jdnNow
- 0.5);
3840 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3842 jdnMidnight
= wxDate().Set().GetJulianDate();
3843 printf("wxDateTime for today: %s\n",
3844 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3846 int flags
= wxEUROPEAN
;//wxFULL;
3849 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3850 for ( int n
= 0; n
< 7; n
++ )
3852 printf("Previous %s is %s\n",
3853 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3854 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3860 #endif // TEST_DATETIME
3862 // ----------------------------------------------------------------------------
3864 // ----------------------------------------------------------------------------
3868 #include <wx/thread.h>
3870 static size_t gs_counter
= (size_t)-1;
3871 static wxCriticalSection gs_critsect
;
3872 static wxCondition gs_cond
;
3874 class MyJoinableThread
: public wxThread
3877 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3878 { m_n
= n
; Create(); }
3880 // thread execution starts here
3881 virtual ExitCode
Entry();
3887 wxThread::ExitCode
MyJoinableThread::Entry()
3889 unsigned long res
= 1;
3890 for ( size_t n
= 1; n
< m_n
; n
++ )
3894 // it's a loooong calculation :-)
3898 return (ExitCode
)res
;
3901 class MyDetachedThread
: public wxThread
3904 MyDetachedThread(size_t n
, char ch
)
3908 m_cancelled
= FALSE
;
3913 // thread execution starts here
3914 virtual ExitCode
Entry();
3917 virtual void OnExit();
3920 size_t m_n
; // number of characters to write
3921 char m_ch
; // character to write
3923 bool m_cancelled
; // FALSE if we exit normally
3926 wxThread::ExitCode
MyDetachedThread::Entry()
3929 wxCriticalSectionLocker
lock(gs_critsect
);
3930 if ( gs_counter
== (size_t)-1 )
3936 for ( size_t n
= 0; n
< m_n
; n
++ )
3938 if ( TestDestroy() )
3948 wxThread::Sleep(100);
3954 void MyDetachedThread::OnExit()
3956 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3958 wxCriticalSectionLocker
lock(gs_critsect
);
3959 if ( !--gs_counter
&& !m_cancelled
)
3963 void TestDetachedThreads()
3965 puts("\n*** Testing detached threads ***");
3967 static const size_t nThreads
= 3;
3968 MyDetachedThread
*threads
[nThreads
];
3970 for ( n
= 0; n
< nThreads
; n
++ )
3972 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3975 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3976 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3978 for ( n
= 0; n
< nThreads
; n
++ )
3983 // wait until all threads terminate
3989 void TestJoinableThreads()
3991 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3993 // calc 10! in the background
3994 MyJoinableThread
thread(10);
3997 printf("\nThread terminated with exit code %lu.\n",
3998 (unsigned long)thread
.Wait());
4001 void TestThreadSuspend()
4003 puts("\n*** Testing thread suspend/resume functions ***");
4005 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4009 // this is for this demo only, in a real life program we'd use another
4010 // condition variable which would be signaled from wxThread::Entry() to
4011 // tell us that the thread really started running - but here just wait a
4012 // bit and hope that it will be enough (the problem is, of course, that
4013 // the thread might still not run when we call Pause() which will result
4015 wxThread::Sleep(300);
4017 for ( size_t n
= 0; n
< 3; n
++ )
4021 puts("\nThread suspended");
4024 // don't sleep but resume immediately the first time
4025 wxThread::Sleep(300);
4027 puts("Going to resume the thread");
4032 puts("Waiting until it terminates now");
4034 // wait until the thread terminates
4040 void TestThreadDelete()
4042 // As above, using Sleep() is only for testing here - we must use some
4043 // synchronisation object instead to ensure that the thread is still
4044 // running when we delete it - deleting a detached thread which already
4045 // terminated will lead to a crash!
4047 puts("\n*** Testing thread delete function ***");
4049 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4053 puts("\nDeleted a thread which didn't start to run yet.");
4055 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4059 wxThread::Sleep(300);
4063 puts("\nDeleted a running thread.");
4065 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4069 wxThread::Sleep(300);
4075 puts("\nDeleted a sleeping thread.");
4077 MyJoinableThread
thread3(20);
4082 puts("\nDeleted a joinable thread.");
4084 MyJoinableThread
thread4(2);
4087 wxThread::Sleep(300);
4091 puts("\nDeleted a joinable thread which already terminated.");
4096 #endif // TEST_THREADS
4098 // ----------------------------------------------------------------------------
4100 // ----------------------------------------------------------------------------
4104 static void PrintArray(const char* name
, const wxArrayString
& array
)
4106 printf("Dump of the array '%s'\n", name
);
4108 size_t nCount
= array
.GetCount();
4109 for ( size_t n
= 0; n
< nCount
; n
++ )
4111 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4115 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4117 printf("Dump of the array '%s'\n", name
);
4119 size_t nCount
= array
.GetCount();
4120 for ( size_t n
= 0; n
< nCount
; n
++ )
4122 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4126 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4127 const wxString
& second
)
4129 return first
.length() - second
.length();
4132 int wxCMPFUNC_CONV
IntCompare(int *first
,
4135 return *first
- *second
;
4138 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4141 return *second
- *first
;
4144 static void TestArrayOfInts()
4146 puts("*** Testing wxArrayInt ***\n");
4157 puts("After sort:");
4161 puts("After reverse sort:");
4162 a
.Sort(IntRevCompare
);
4166 #include "wx/dynarray.h"
4168 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4169 #include "wx/arrimpl.cpp"
4170 WX_DEFINE_OBJARRAY(ArrayBars
);
4172 static void TestArrayOfObjects()
4174 puts("*** Testing wxObjArray ***\n");
4178 Bar
bar("second bar");
4180 printf("Initially: %u objects in the array, %u objects total.\n",
4181 bars
.GetCount(), Bar::GetNumber());
4183 bars
.Add(new Bar("first bar"));
4186 printf("Now: %u objects in the array, %u objects total.\n",
4187 bars
.GetCount(), Bar::GetNumber());
4191 printf("After Empty(): %u objects in the array, %u objects total.\n",
4192 bars
.GetCount(), Bar::GetNumber());
4195 printf("Finally: no more objects in the array, %u objects total.\n",
4199 #endif // TEST_ARRAYS
4201 // ----------------------------------------------------------------------------
4203 // ----------------------------------------------------------------------------
4207 #include "wx/timer.h"
4208 #include "wx/tokenzr.h"
4210 static void TestStringConstruction()
4212 puts("*** Testing wxString constructores ***");
4214 #define TEST_CTOR(args, res) \
4217 printf("wxString%s = %s ", #args, s.c_str()); \
4224 printf("(ERROR: should be %s)\n", res); \
4228 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4229 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4230 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4231 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4233 static const wxChar
*s
= _T("?really!");
4234 const wxChar
*start
= wxStrchr(s
, _T('r'));
4235 const wxChar
*end
= wxStrchr(s
, _T('!'));
4236 TEST_CTOR((start
, end
), _T("really"));
4241 static void TestString()
4251 for (int i
= 0; i
< 1000000; ++i
)
4255 c
= "! How'ya doin'?";
4258 c
= "Hello world! What's up?";
4263 printf ("TestString elapsed time: %ld\n", sw
.Time());
4266 static void TestPChar()
4274 for (int i
= 0; i
< 1000000; ++i
)
4276 strcpy (a
, "Hello");
4277 strcpy (b
, " world");
4278 strcpy (c
, "! How'ya doin'?");
4281 strcpy (c
, "Hello world! What's up?");
4282 if (strcmp (c
, a
) == 0)
4286 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4289 static void TestStringSub()
4291 wxString
s("Hello, world!");
4293 puts("*** Testing wxString substring extraction ***");
4295 printf("String = '%s'\n", s
.c_str());
4296 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4297 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4298 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4299 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4300 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4301 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4303 static const wxChar
*prefixes
[] =
4307 _T("Hello, world!"),
4308 _T("Hello, world!!!"),
4314 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4316 wxString prefix
= prefixes
[n
], rest
;
4317 bool rc
= s
.StartsWith(prefix
, &rest
);
4318 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4321 printf(" (the rest is '%s')\n", rest
.c_str());
4332 static void TestStringFormat()
4334 puts("*** Testing wxString formatting ***");
4337 s
.Printf("%03d", 18);
4339 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4340 printf("Number 18: %s\n", s
.c_str());
4345 // returns "not found" for npos, value for all others
4346 static wxString
PosToString(size_t res
)
4348 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4349 : wxString::Format(_T("%u"), res
);
4353 static void TestStringFind()
4355 puts("*** Testing wxString find() functions ***");
4357 static const wxChar
*strToFind
= _T("ell");
4358 static const struct StringFindTest
4362 result
; // of searching "ell" in str
4365 { _T("Well, hello world"), 0, 1 },
4366 { _T("Well, hello world"), 6, 7 },
4367 { _T("Well, hello world"), 9, wxString::npos
},
4370 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4372 const StringFindTest
& ft
= findTestData
[n
];
4373 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4375 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4376 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4378 size_t resTrue
= ft
.result
;
4379 if ( res
== resTrue
)
4385 printf(_T("(ERROR: should be %s)\n"),
4386 PosToString(resTrue
).c_str());
4393 static void TestStringTokenizer()
4395 puts("*** Testing wxStringTokenizer ***");
4397 static const wxChar
*modeNames
[] =
4401 _T("return all empty"),
4406 static const struct StringTokenizerTest
4408 const wxChar
*str
; // string to tokenize
4409 const wxChar
*delims
; // delimiters to use
4410 size_t count
; // count of token
4411 wxStringTokenizerMode mode
; // how should we tokenize it
4412 } tokenizerTestData
[] =
4414 { _T(""), _T(" "), 0 },
4415 { _T("Hello, world"), _T(" "), 2 },
4416 { _T("Hello, world "), _T(" "), 2 },
4417 { _T("Hello, world"), _T(","), 2 },
4418 { _T("Hello, world!"), _T(",!"), 2 },
4419 { _T("Hello,, world!"), _T(",!"), 3 },
4420 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4421 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4422 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4423 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4424 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4425 { _T("01/02/99"), _T("/-"), 3 },
4426 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4429 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4431 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4432 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4434 size_t count
= tkz
.CountTokens();
4435 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4436 MakePrintable(tt
.str
).c_str(),
4438 MakePrintable(tt
.delims
).c_str(),
4439 modeNames
[tkz
.GetMode()]);
4440 if ( count
== tt
.count
)
4446 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4451 // if we emulate strtok(), check that we do it correctly
4452 wxChar
*buf
, *s
= NULL
, *last
;
4454 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4456 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4457 wxStrcpy(buf
, tt
.str
);
4459 s
= wxStrtok(buf
, tt
.delims
, &last
);
4466 // now show the tokens themselves
4468 while ( tkz
.HasMoreTokens() )
4470 wxString token
= tkz
.GetNextToken();
4472 printf(_T("\ttoken %u: '%s'"),
4474 MakePrintable(token
).c_str());
4484 printf(" (ERROR: should be %s)\n", s
);
4487 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4491 // nothing to compare with
4496 if ( count2
!= count
)
4498 puts(_T("\tERROR: token count mismatch"));
4507 static void TestStringReplace()
4509 puts("*** Testing wxString::replace ***");
4511 static const struct StringReplaceTestData
4513 const wxChar
*original
; // original test string
4514 size_t start
, len
; // the part to replace
4515 const wxChar
*replacement
; // the replacement string
4516 const wxChar
*result
; // and the expected result
4517 } stringReplaceTestData
[] =
4519 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4520 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4521 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4522 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4523 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4526 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4528 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4530 wxString original
= data
.original
;
4531 original
.replace(data
.start
, data
.len
, data
.replacement
);
4533 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4534 data
.original
, data
.start
, data
.len
, data
.replacement
,
4537 if ( original
== data
.result
)
4543 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4550 #endif // TEST_STRINGS
4552 // ----------------------------------------------------------------------------
4554 // ----------------------------------------------------------------------------
4556 int main(int argc
, char **argv
)
4558 wxInitializer initializer
;
4561 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4566 #ifdef TEST_SNGLINST
4567 wxSingleInstanceChecker checker
;
4568 if ( checker
.Create(_T(".wxconsole.lock")) )
4570 if ( checker
.IsAnotherRunning() )
4572 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4577 // wait some time to give time to launch another instance
4578 wxPrintf(_T("Press \"Enter\" to continue..."));
4581 else // failed to create
4583 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4585 #endif // TEST_SNGLINST
4589 #endif // TEST_CHARSET
4592 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4594 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4595 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4597 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4598 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4599 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4600 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4602 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4603 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4608 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4610 parser
.AddOption("project_name", "", "full path to project file",
4611 wxCMD_LINE_VAL_STRING
,
4612 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4614 switch ( parser
.Parse() )
4617 wxLogMessage("Help was given, terminating.");
4621 ShowCmdLine(parser
);
4625 wxLogMessage("Syntax error detected, aborting.");
4628 #endif // TEST_CMDLINE
4639 TestStringConstruction();
4642 TestStringTokenizer();
4643 TestStringReplace();
4645 #endif // TEST_STRINGS
4658 puts("*** Initially:");
4660 PrintArray("a1", a1
);
4662 wxArrayString
a2(a1
);
4663 PrintArray("a2", a2
);
4665 wxSortedArrayString
a3(a1
);
4666 PrintArray("a3", a3
);
4668 puts("*** After deleting a string from a1");
4671 PrintArray("a1", a1
);
4672 PrintArray("a2", a2
);
4673 PrintArray("a3", a3
);
4675 puts("*** After reassigning a1 to a2 and a3");
4677 PrintArray("a2", a2
);
4678 PrintArray("a3", a3
);
4680 puts("*** After sorting a1");
4682 PrintArray("a1", a1
);
4684 puts("*** After sorting a1 in reverse order");
4686 PrintArray("a1", a1
);
4688 puts("*** After sorting a1 by the string length");
4689 a1
.Sort(StringLenCompare
);
4690 PrintArray("a1", a1
);
4692 TestArrayOfObjects();
4695 #endif // TEST_ARRAYS
4703 #ifdef TEST_DLLLOADER
4705 #endif // TEST_DLLLOADER
4709 #endif // TEST_ENVIRON
4713 #endif // TEST_EXECUTE
4715 #ifdef TEST_FILECONF
4717 #endif // TEST_FILECONF
4725 #endif // TEST_LOCALE
4729 for ( size_t n
= 0; n
< 8000; n
++ )
4731 s
<< (char)('A' + (n
% 26));
4735 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4737 // this one shouldn't be truncated
4740 // but this one will because log functions use fixed size buffer
4741 // (note that it doesn't need '\n' at the end neither - will be added
4743 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4755 #ifdef TEST_FILENAME
4756 TestFileNameSplit();
4759 TestFileNameConstruction();
4761 TestFileNameComparison();
4762 TestFileNameOperations();
4764 #endif // TEST_FILENAME
4767 int nCPUs
= wxThread::GetCPUCount();
4768 printf("This system has %d CPUs\n", nCPUs
);
4770 wxThread::SetConcurrency(nCPUs
);
4772 if ( argc
> 1 && argv
[1][0] == 't' )
4773 wxLog::AddTraceMask("thread");
4776 TestDetachedThreads();
4778 TestJoinableThreads();
4780 TestThreadSuspend();
4784 #endif // TEST_THREADS
4786 #ifdef TEST_LONGLONG
4787 // seed pseudo random generator
4788 srand((unsigned)time(NULL
));
4796 TestMultiplication();
4799 TestLongLongConversion();
4800 TestBitOperations();
4802 TestLongLongComparison();
4803 #endif // TEST_LONGLONG
4810 wxLog::AddTraceMask(_T("mime"));
4818 TestMimeAssociate();
4821 #ifdef TEST_INFO_FUNCTIONS
4824 #endif // TEST_INFO_FUNCTIONS
4826 #ifdef TEST_PATHLIST
4828 #endif // TEST_PATHLIST
4832 #endif // TEST_REGCONF
4834 #ifdef TEST_REGISTRY
4837 TestRegistryAssociation();
4838 #endif // TEST_REGISTRY
4846 #endif // TEST_SOCKETS
4849 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4850 if ( TestFtpConnect() )
4861 TestFtpInteractive();
4863 //else: connecting to the FTP server failed
4873 #endif // TEST_STREAMS
4877 #endif // TEST_TIMER
4879 #ifdef TEST_DATETIME
4892 TestTimeArithmetics();
4899 TestTimeSpanFormat();
4901 TestDateTimeInteractive();
4902 #endif // TEST_DATETIME
4905 puts("Sleeping for 3 seconds... z-z-z-z-z...");
4907 #endif // TEST_USLEEP
4913 #endif // TEST_VCARD
4917 #endif // TEST_WCHAR
4921 TestZipStreamRead();
4922 TestZipFileSystem();
4927 TestZlibStreamWrite();
4928 TestZlibStreamRead();